-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathSiteTreeSubsites.php
577 lines (506 loc) · 20.5 KB
/
SiteTreeSubsites.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
<?php
namespace SilverStripe\Subsites\Extensions;
use SilverStripe\Dev\Deprecation;
use Page;
use SilverStripe\CMS\Forms\SiteTreeURLSegmentField;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTP;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Convert;
use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\FormAction;
use SilverStripe\Forms\ToggleCompositeField;
use SilverStripe\i18n\i18n;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataExtension;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DataQuery;
use SilverStripe\ORM\Map;
use SilverStripe\ORM\Queries\SQLSelect;
use SilverStripe\Security\Member;
use SilverStripe\Security\Security;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\Subsites\Model\Subsite;
use SilverStripe\Subsites\Service\ThemeResolver;
use SilverStripe\Subsites\State\SubsiteState;
use SilverStripe\View\SSViewer;
use SilverStripe\VersionedAdmin\Controllers\HistoryViewerController;
/**
* Extension for the SiteTree object to add subsites support
*/
class SiteTreeSubsites extends DataExtension
{
private static $has_one = [
'Subsite' => Subsite::class, // The subsite that this page belongs to
];
private static $many_many = [
'CrossSubsiteLinkTracking' => SiteTree::class // Stored separately, as the logic for URL rewriting is different
];
private static $many_many_extraFields = [
'CrossSubsiteLinkTracking' => ['FieldName' => 'Varchar']
];
public function isMainSite()
{
return $this->owner->SubsiteID == 0;
}
/**
* Update any requests to limit the results to the current site
* @param SQLSelect $query
* @param DataQuery $dataQuery
*/
public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
{
if (Subsite::$disable_subsite_filter) {
return;
}
if ($dataQuery && $dataQuery->getQueryParam('Subsite.filter') === false) {
return;
}
// If you're querying by ID, ignore the sub-site - this is a bit ugly...
// if(!$query->where
// || (strpos($query->where[0], ".\"ID\" = ") === false
// && strpos($query->where[0], ".`ID` = ") === false && strpos($query->where[0], ".ID = ") === false
// && strpos($query->where[0], "ID = ") !== 0)) {
if ($query->filtersOnID()) {
return;
}
$subsiteID = null;
if (Subsite::$force_subsite) {
$subsiteID = Subsite::$force_subsite;
} else {
$subsiteID = SubsiteState::singleton()->getSubsiteId();
}
if ($subsiteID === null) {
return;
}
// The foreach is an ugly way of getting the first key :-)
foreach ($query->getFrom() as $tableName => $info) {
// The tableName should be SiteTree or SiteTree_Live...
$siteTreeTableName = SiteTree::getSchema()->tableName(SiteTree::class);
if (strpos($tableName ?? '', $siteTreeTableName ?? '') === false) {
break;
}
$query->addWhere("\"$tableName\".\"SubsiteID\" IN ($subsiteID)");
break;
}
}
public function onBeforeWrite()
{
if (!$this->owner->ID && !$this->owner->SubsiteID) {
$this->owner->SubsiteID = SubsiteState::singleton()->getSubsiteId();
}
parent::onBeforeWrite();
}
public function updateCMSFields(FieldList $fields)
{
$subsites = Subsite::accessible_sites('CMS_ACCESS_CMSMain');
if ($subsites && $subsites->count()) {
$subsitesToMap = $subsites->exclude('ID', $this->owner->SubsiteID);
$subsitesMap = $subsitesToMap->map('ID', 'Title');
} else {
$subsitesMap = new Map(ArrayList::create());
}
$viewingPageHistory = Controller::has_curr() && Controller::curr() instanceof HistoryViewerController;
// Master page edit field (only allowed from default subsite to avoid inconsistent relationships)
$isDefaultSubsite = $this->owner->SubsiteID == 0 || $this->owner->Subsite()->DefaultSite;
if ($isDefaultSubsite && $subsitesMap->count() && !$viewingPageHistory) {
$fields->addFieldToTab(
'Root.Main',
ToggleCompositeField::create(
'SubsiteOperations',
_t(__CLASS__ . '.SubsiteOperations', 'Subsite Operations'),
[
DropdownField::create('CopyToSubsiteID', _t(
__CLASS__ . '.CopyToSubsite',
'Copy page to subsite'
), $subsitesMap),
CheckboxField::create(
'CopyToSubsiteWithChildren',
_t(__CLASS__ . '.CopyToSubsiteWithChildren', 'Include children pages?')
),
$copyAction = FormAction::create(
'copytosubsite',
_t(__CLASS__ . '.CopyAction', 'Copy')
)
]
)->setHeadingLevel(4)
);
$copyAction->addExtraClass('btn btn-primary font-icon-save ml-3');
// @todo check if this needs re-implementation
// $copyAction->includeDefaultJS(false);
}
// replace readonly link prefix
$subsite = $this->owner->Subsite();
$nested_urls_enabled = Config::inst()->get(SiteTree::class, 'nested_urls');
/** @var Subsite $subsite */
if ($subsite && $subsite->exists()) {
// Use baseurl from domain
$baseLink = $subsite->absoluteBaseURL();
// Add parent page if enabled
if ($nested_urls_enabled && $this->owner->ParentID) {
$baseLink = Controller::join_links(
$baseLink,
$this->owner->Parent()->RelativeLink(true)
);
}
$urlsegment = $fields->dataFieldByName('URLSegment');
if ($urlsegment && $urlsegment instanceof SiteTreeURLSegmentField) {
$urlsegment->setURLPrefix($baseLink);
}
}
}
/**
* Does the basic duplication, but doesn't write anything this means we can subclass this easier and do more
* complex relation duplication.
*
* Note that when duplicating including children, everything is written.
*
* @param Subsite|int $subsiteID
* @param bool $includeChildren
* @return SiteTree
*/
public function duplicateToSubsitePrep($subsiteID, $includeChildren)
{
if (is_object($subsiteID)) {
$subsiteID = $subsiteID->ID;
}
return SubsiteState::singleton()
->withState(function (SubsiteState $newState) use ($subsiteID, $includeChildren) {
$newState->setSubsiteId($subsiteID);
/** @var SiteTree $page */
$page = $this->owner;
try {
// We have no idea what the ParentID should be, but it shouldn't be the same as it was since
// we're now in a different subsite. As a workaround use the url-segment and subsite ID.
if ($page->Parent()) {
$parentSeg = $page->Parent()->URLSegment;
$newParentPage = Page::get()->filter('URLSegment', $parentSeg)->first();
$originalParentID = $page->ParentID;
if ($newParentPage) {
$page->ParentID = (int) $newParentPage->ID;
} else {
// reset it to the top level, so the user can decide where to put it
$page->ParentID = 0;
}
}
// Disable query filtering by subsite during actual duplication
$originalFilter = Subsite::$disable_subsite_filter;
Subsite::disable_subsite_filter(true);
return $includeChildren ? $page->duplicateWithChildren() : $page->duplicate(false);
} finally {
Subsite::disable_subsite_filter($originalFilter);
// Re-set the original parent ID for the current page
$page->ParentID = $originalParentID;
}
});
}
/**
* When duplicating a page, assign the current subsite ID from the state
*/
public function onBeforeDuplicate()
{
$subsiteId = SubsiteState::singleton()->getSubsiteId();
if ($subsiteId !== null) {
$this->owner->SubsiteID = $subsiteId;
}
}
/**
* Create a duplicate of this page and save it to another subsite
*
* @param Subsite|int $subsiteID The Subsite to copy to, or its ID
* @param boolean $includeChildren Whether to duplicate child pages too
* @return SiteTree The duplicated page
*/
public function duplicateToSubsite($subsiteID = null, $includeChildren = false)
{
/** @var SiteTree|SiteTreeSubsites */
$clone = $this->owner->duplicateToSubsitePrep($subsiteID, $includeChildren);
$clone->invokeWithExtensions('onBeforeDuplicateToSubsite', $this->owner);
if (!$includeChildren) {
// Write the new page if "include children" is false, because it is written by default when it's true.
$clone->write();
}
// Deprecated: manually duplicate any configured relationships
$clone->duplicateSubsiteRelations($this->owner);
$clone->invokeWithExtensions('onAfterDuplicateToSubsite', $this->owner);
return $clone;
}
/**
* Duplicate relations using a static property to define
* which ones we want to duplicate
*
* It may be that some relations are not diostinct to sub site so can stay
* whereas others may need to be duplicated
*
* This was originally deprecated - Use the "cascade_duplicates" config API instead
* Ideally this would be re-deprecated
*
* @param SiteTree $originalPage
*/
public function duplicateSubsiteRelations($originalPage)
{
$thisClass = $originalPage->ClassName;
$relations = Config::inst()->get($thisClass, 'duplicate_to_subsite_relations');
if ($relations && !empty($relations)) {
foreach ($relations as $relation) {
$items = $originalPage->$relation();
foreach ($items as $item) {
$duplicateItem = $item->duplicate(false);
$duplicateItem->{$thisClass.'ID'} = $this->owner->ID;
$duplicateItem->write();
}
}
}
}
/**
* @return SiteConfig
*/
public function alternateSiteConfig()
{
if (!$this->owner->SubsiteID) {
return false;
}
$sc = DataObject::get_one(SiteConfig::class, '"SubsiteID" = ' . $this->owner->SubsiteID);
if (!$sc) {
$sc = new SiteConfig();
$sc->SubsiteID = $this->owner->SubsiteID;
$sc->Title = _t('SilverStripe\\Subsites\\Model\\Subsite.SiteConfigTitle', 'Your Site Name');
$sc->Tagline = _t('SilverStripe\\Subsites\\Model\\Subsite.SiteConfigSubtitle', 'Your tagline here');
$sc->write();
}
return $sc;
}
/**
* Only allow editing of a page if the member satisfies one of the following conditions:
* - Is in a group which has access to the subsite this page belongs to
* - Is in a group with edit permissions on the "main site"
*
* If there are no subsites configured yet, this logic is skipped.
*
* @param Member|null $member
* @return bool|null
*/
public function canEdit($member = null)
{
if (!$member) {
$member = Security::getCurrentUser();
}
// Do not provide any input if there are no subsites configured
if (!Subsite::get()->exists()) {
return null;
}
// Find the sites that this user has access to
$goodSites = Subsite::accessible_sites('CMS_ACCESS_CMSMain', true, 'all', $member)->column('ID');
if (!is_null($this->owner->SubsiteID)) {
$subsiteID = $this->owner->SubsiteID;
} else {
// The relationships might not be available during the record creation when using a GridField.
// In this case the related objects will have empty fields, and SubsiteID will not be available.
//
// We do the second best: fetch the likely SubsiteID from the session. The drawback is this might
// make it possible to force relations to point to other (forbidden) subsites.
$subsiteID = SubsiteState::singleton()->getSubsiteId();
}
// Return true if they have access to this object's site
if (!(in_array(0, $goodSites ?? []) || in_array($subsiteID, $goodSites ?? []))) {
return false;
}
}
/**
* @param null $member
* @return bool
*/
public function canDelete($member = null)
{
if (!$member && $member !== false) {
$member = Security::getCurrentUser();
}
return $this->canEdit($member);
}
/**
* @param null $member
* @return bool
*/
public function canAddChildren($member = null)
{
if (!$member && $member !== false) {
$member = Security::getCurrentUser();
}
return $this->canEdit($member);
}
/**
* @param Member|null $member
* @return bool|null
*/
public function canPublish($member = null)
{
if (!$member && $member !== false) {
$member = Security::getCurrentUser();
}
return $this->canEdit($member);
}
/**
* Called by ContentController::init();
* @param $controller
*/
public static function contentcontrollerInit($controller)
{
/** @var Subsite $subsite */
$subsite = Subsite::currentSubsite();
if ($subsite && $subsite->Theme) {
SSViewer::set_themes(ThemeResolver::singleton()->getThemeList($subsite));
}
$ignore_subsite_locale = Config::inst()->get(self::class, 'ignore_subsite_locale');
if (!$ignore_subsite_locale
&& $subsite
&& $subsite->Language
&& i18n::getData()->validate($subsite->Language)
) {
i18n::set_locale($subsite->Language);
}
}
/**
* @param null $action
* @return string
*/
public function alternateAbsoluteLink($action = null)
{
// Generate the existing absolute URL and replace the domain with the subsite domain.
// This helps deal with Link() returning an absolute URL.
$url = Director::absoluteURL($this->owner->Link($action));
if ($this->owner->SubsiteID) {
$url = preg_replace('/\/\/[^\/]+\//', '//' . $this->owner->Subsite()->domain() . '/', $url ?? '');
}
return $url;
}
/**
* Use the CMS domain for iframed CMS previews to prevent single-origin violations
* and SSL cert problems. Always set SubsiteID to avoid errors because a page doesn't
* exist on the CMS domain.
*
* @param string &$link
* @param string|null $action
* @return string
*/
public function updatePreviewLink(&$link, $action = null)
{
$url = Director::absoluteURL($this->owner->Link($action));
$link = HTTP::setGetVar('SubsiteID', $this->owner->SubsiteID, $url);
return $link;
}
/**
* This function is marked as deprecated for removal in 5.0.0 in silverstripe/cms
* so now simply passes execution to where the functionality exists for backwards compatiblity.
* CMS 4.0.0 SiteTree already throws a SilverStripe deprecation error before calling this function.
* @deprecated 2.2.0 Use updatePreviewLink() instead
*
* @param string|null $action
* @return string
*/
public function alternatePreviewLink($action = null)
{
Deprecation::notice('2.2.0', 'Use updatePreviewLink() instead');
$link = '';
return $this->updatePreviewLink($link, $action);
}
/**
* Inject the subsite ID into the content so it can be used by frontend scripts.
* @param $tags
* @return string
*/
public function MetaTags(&$tags)
{
if ($this->owner->SubsiteID) {
$tags .= '<meta name="x-subsite-id" content="' . $this->owner->SubsiteID . "\" />\n";
}
return $tags;
}
public function augmentSyncLinkTracking()
{
// Set LinkTracking appropriately
$links = HTTP::getLinksIn($this->owner->Content);
$linkedPages = [];
if ($links) {
foreach ($links as $link) {
if (substr($link ?? '', 0, strlen('http://')) == 'http://') {
$withoutHttp = substr($link ?? '', strlen('http://'));
if (strpos($withoutHttp ?? '', '/') &&
strpos($withoutHttp ?? '', '/') < strlen($withoutHttp ?? '')
) {
$domain = substr($withoutHttp ?? '', 0, strpos($withoutHttp ?? '', '/'));
$rest = substr($withoutHttp ?? '', strpos($withoutHttp ?? '', '/') + 1);
$subsiteID = Subsite::getSubsiteIDForDomain($domain);
if ($subsiteID == 0) {
continue;
} // We have no idea what the domain for the main site is, so cant track links to it
$origDisableSubsiteFilter = Subsite::$disable_subsite_filter;
Subsite::disable_subsite_filter(true);
$candidatePage = SiteTree::get()->filter([
'URLSegment' => urldecode($rest),
'SubsiteID' => $subsiteID,
])->first();
Subsite::disable_subsite_filter($origDisableSubsiteFilter);
if ($candidatePage) {
$linkedPages[] = $candidatePage->ID;
} else {
$this->owner->HasBrokenLink = true;
}
}
}
}
}
$this->owner->CrossSubsiteLinkTracking()->setByIDList($linkedPages);
}
/**
* Ensure that valid url segments are checked within the correct subsite of the owner object,
* even if the current subsiteID is set to some other subsite.
*
* @return null|bool Either true or false, or null to not influence result
*/
public function augmentValidURLSegment()
{
// If this page is being filtered in the current subsite, then no custom validation query is required.
$subsite = Subsite::$force_subsite ?: SubsiteState::singleton()->getSubsiteId();
if (empty($this->owner->SubsiteID) || $subsite == $this->owner->SubsiteID) {
return null;
}
// Backup forced subsite
$prevForceSubsite = Subsite::$force_subsite;
Subsite::$force_subsite = $this->owner->SubsiteID;
// Repeat validation in the correct subsite
$isValid = $this->owner->validURLSegment();
// Restore
Subsite::$force_subsite = $prevForceSubsite;
return (bool)$isValid;
}
/**
* Return a piece of text to keep DataObject cache keys appropriately specific
*/
public function cacheKeyComponent()
{
return 'subsite-' . SubsiteState::singleton()->getSubsiteId();
}
/**
* @param Member $member
* @return boolean|null
*/
public function canCreate($member = null)
{
// Typically called on a singleton, so we're not using the Subsite() relation
$subsite = Subsite::currentSubsite();
if ($subsite && $subsite->exists() && $subsite->PageTypeBlacklist) {
// SS 4.1: JSON encoded. SS 4.0, comma delimited
$blacklist = json_decode($subsite->PageTypeBlacklist ?? '', true);
if ($blacklist === false) {
$blacklist = explode(',', $subsite->PageTypeBlacklist ?? '');
}
if (in_array(get_class($this->owner), (array) $blacklist)) {
return false;
}
}
}
}