-
Notifications
You must be signed in to change notification settings - Fork 333
/
VirtualPage.php
548 lines (485 loc) · 15.7 KB
/
VirtualPage.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
<?php
namespace SilverStripe\CMS\Model;
use Page;
use SilverStripe\Core\Convert;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\ReadonlyTransformation;
use SilverStripe\Forms\TreeDropdownField;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\ValidationResult;
use SilverStripe\Security\Member;
use SilverStripe\Versioned\Versioned;
use SilverStripe\View\HTML;
/**
* Virtual Page creates an instance of a page, with the same fields that the original page had, but readonly.
* This allows you can have a page in mulitple places in the site structure, with different children without
* duplicating the content.
*
* Note: This Only duplicates $db fields and not the $has_one etc..
*
* @method SiteTree CopyContentFrom()
* @property int $CopyContentFromID
*/
class VirtualPage extends Page
{
private static $description = 'Displays the content of another page';
private static $icon_class = 'font-icon-p-virtual';
public static $virtualFields;
/**
* @var array Define fields that are not virtual - the virtual page must define these fields themselves.
* Note that anything in {@link self::config()->initially_copied_fields} is implicitly included in this list.
*/
private static $non_virtual_fields = [
"ID",
"ClassName",
"ObsoleteClassName",
"SecurityTypeID",
"OwnerID",
"ParentID",
"URLSegment",
"Sort",
"Status",
'ShowInMenus',
// 'Locale'
'ShowInSearch',
'Version',
"Embargo",
"Expiry",
"CanViewType",
"CanEditType",
"CopyContentFromID",
"HasBrokenLink",
];
/**
* @var array Define fields that are initially copied to virtual pages but left modifiable after that.
*/
private static $initially_copied_fields = [
'ShowInMenus',
'ShowInSearch',
'URLSegment',
];
private static $has_one = [
"CopyContentFrom" => SiteTree::class,
];
private static $owns = [
"CopyContentFrom",
];
private static $db = [
"VersionID" => "Int",
];
private static $table_name = 'VirtualPage';
/**
* Generates the array of fields required for the page type.
*
* @return array
*/
public function getVirtualFields()
{
// Check if copied page exists
$record = $this->CopyContentFrom();
if (!$record || !$record->exists()) {
return [];
}
// Diff db with non-virtual fields
$fields = array_keys(static::getSchema()->fieldSpecs($record) ?? []);
$nonVirtualFields = $this->getNonVirtualisedFields();
return array_diff($fields ?? [], $nonVirtualFields);
}
/**
* List of fields or properties to never virtualise
*
* @return array
*/
public function getNonVirtualisedFields()
{
$config = self::config();
return array_merge(
$config->get('non_virtual_fields'),
$config->get('initially_copied_fields')
);
}
public function setCopyContentFromID($val)
{
// Sanity check to prevent pages virtualising other virtual pages
if ($val && DataObject::get_by_id(SiteTree::class, $val) instanceof VirtualPage) {
$val = 0;
}
return $this->setField("CopyContentFromID", $val);
}
public function ContentSource()
{
$copied = $this->CopyContentFrom();
if ($copied && $copied->exists()) {
return $copied;
}
return $this;
}
/**
* @return array
*/
public function MetaComponents()
{
$tags = parent::MetaComponents();
$copied = $this->CopyContentFrom();
if ($copied && $copied->exists()) {
$tags['canonical'] = [
'tag' => 'link',
'attributes' => [
'rel' => 'canonical',
'href' => $copied->AbsoluteLink(),
],
];
}
return $tags;
}
public function allowedChildren()
{
$copy = $this->CopyContentFrom();
if ($copy && $copy->exists()) {
return $copy->allowedChildren();
}
return [];
}
public function syncLinkTracking()
{
if ($this->CopyContentFromID) {
$this->HasBrokenLink = Versioned::get_by_stage(SiteTree::class, Versioned::DRAFT)
->filter('ID', $this->CopyContentFromID)
->count() === 0;
} else {
$this->HasBrokenLink = true;
}
}
/**
* We can only publish the page if there is a published source page
*
* @param Member $member Member to check
* @return bool
*/
public function canPublish($member = null)
{
return $this->isPublishable() && parent::canPublish($member);
}
/**
* Returns true if is page is publishable by anyone at all
* Return false if the source page isn't published yet.
*
* Note that isPublishable doesn't affect ete from live, only publish.
*/
public function isPublishable()
{
// No source
if (!$this->CopyContentFrom() || !$this->CopyContentFrom()->ID) {
return false;
}
// Unpublished source
if (!Versioned::get_versionnumber_by_stage(
SiteTree::class,
'Live',
$this->CopyContentFromID
)) {
return false;
}
// Default - publishable
return true;
}
/**
* Generate the CMS fields from the fields from the original page.
*/
public function getCMSFields()
{
$this->beforeUpdateCMSFields(function (FieldList $fields) {
// Setup the linking to the original page.
$copyContentFromField = TreeDropdownField::create(
'CopyContentFromID',
_t(self::class . '.CHOOSE', "Linked Page"),
SiteTree::class
);
// Setup virtual fields
if ($virtualFields = $this->getVirtualFields()) {
$roTransformation = new ReadonlyTransformation();
foreach ($virtualFields as $virtualField) {
if ($fields->dataFieldByName($virtualField)) {
$fields->replaceField(
$virtualField,
$fields->dataFieldByName($virtualField)->transform($roTransformation)
);
}
}
}
$msgs = [];
$fields->addFieldToTab('Root.Main', $copyContentFromField, 'Title');
// Create links back to the original object in the CMS
if ($this->CopyContentFrom()->exists()) {
$link = HTML::createTag(
'a',
[
'class' => 'cmsEditlink',
'href' => $this->CopyContentFrom()->CMSEditLink(),
],
_t(self::class . '.EditLink', 'edit')
);
$msgs[] = _t(
self::class . '.HEADERWITHLINK',
"This is a virtual page copying content from \"{title}\" ({link})",
[
'title' => $this->CopyContentFrom()->obj('Title'),
'link' => $link,
]
);
} else {
$msgs[] = _t(self::class . '.HEADER', "This is a virtual page");
$msgs[] = _t(
'SilverStripe\\CMS\\Model\\SiteTree.VIRTUALPAGEWARNING',
'Please choose a linked page and save first in order to publish this page'
);
}
if ($this->CopyContentFromID && !Versioned::get_versionnumber_by_stage(
SiteTree::class,
Versioned::LIVE,
$this->CopyContentFromID
)) {
$msgs[] = _t(
'SilverStripe\\CMS\\Model\\SiteTree.VIRTUALPAGEDRAFTWARNING',
'Please publish the linked page in order to publish the virtual page'
);
}
$fields->addFieldToTab("Root.Main", new LiteralField(
'VirtualPageMessage',
'<div class="alert alert-info">' . implode('. ', $msgs) . '.</div>'
), 'CopyContentFromID');
});
return parent::getCMSFields();
}
public function onBeforeWrite()
{
$this->refreshFromCopied();
parent::onBeforeWrite();
}
/**
* Copy any fields from the copied record to bootstrap /backup
*/
protected function refreshFromCopied()
{
// Skip if copied record isn't available
$source = $this->CopyContentFrom();
if (!$source || !$source->exists()) {
return;
}
// We also want to copy certain, but only if we're copying the source page for the first
// time. After this point, the user is free to customise these for the virtual page themselves.
if ($this->isChanged('CopyContentFromID', 2) && $this->CopyContentFromID) {
foreach (self::config()->get('initially_copied_fields') as $fieldName) {
$this->$fieldName = $source->$fieldName;
}
}
// Copy fields to the original record in case the class type changes
foreach ($this->getVirtualFields() as $virtualField) {
$this->$virtualField = $source->$virtualField;
}
}
public function getSettingsFields()
{
$fields = parent::getSettingsFields();
if (!$this->CopyContentFrom()->exists()) {
$fields->addFieldToTab(
"Root.Settings",
new LiteralField(
'VirtualPageWarning',
'<div class="message notice">'
. _t(
'SilverStripe\\CMS\\Model\\SiteTree.VIRTUALPAGEWARNINGSETTINGS',
'Please choose a linked page in the main content fields in order to publish'
)
. '</div>'
),
'ClassName'
);
}
return $fields;
}
public function validate()
{
$result = parent::validate();
// "Can be root" validation
$orig = $this->CopyContentFrom();
if ($orig && $orig->exists() && !$orig->config()->get('can_be_root') && !$this->ParentID) {
$result->addError(
_t(
self::class . '.PageTypNotAllowedOnRoot',
'Original page type "{type}" is not allowed on the root level for this virtual page',
['type' => $orig->i18n_singular_name()]
),
ValidationResult::TYPE_ERROR,
'CAN_BE_ROOT_VIRTUAL'
);
}
return $result;
}
/**
* @deprecated 4.2.0 Will be removed without equivalent functionality to replace it
*/
public function updateImageTracking()
{
Deprecation::notice('4.2.0', 'Will be removed without equivalent functionality to replace it');
// Doesn't work on unsaved records
if (!$this->isInDB()) {
return;
}
// Remove CopyContentFrom() from the cache
unset($this->components['CopyContentFrom']);
// Update ImageTracking
$copyContentFrom = $this->CopyContentFrom();
if (!$copyContentFrom || !$copyContentFrom->isInDB()) {
return;
}
$this->FileTracking()->setByIDList($copyContentFrom->FileTracking()->column('ID'));
}
public function CMSTreeClasses()
{
$parentClass = sprintf(
' VirtualPage-%s',
Convert::raw2htmlid($this->CopyContentFrom()->ClassName)
);
return parent::CMSTreeClasses() . $parentClass;
}
/**
* Use the target page's class name for fetching templates - as we need to take on its appearance
*
* @param string $suffix
* @return array
*/
public function getViewerTemplates($suffix = '')
{
$copy = $this->CopyContentFrom();
if ($copy && $copy->exists()) {
return $copy->getViewerTemplates($suffix);
}
return parent::getViewerTemplates($suffix);
}
/**
* Allow attributes on the master page to pass
* through to the virtual page
*
* @param string $field
* @return mixed
*/
public function __get($field)
{
if (parent::hasMethod($funcName = "get$field")) {
return $this->$funcName();
}
if (parent::hasField($field) || ($field === 'ID' && !$this->exists())) {
return $this->getField($field);
}
if (($copy = $this->CopyContentFrom()) && $copy->exists()) {
return $copy->$field;
}
return null;
}
public function getField($field)
{
if ($this->isFieldVirtualised($field)) {
return $this->CopyContentFrom()->getField($field);
}
return parent::getField($field);
}
/**
* Check if given field is virtualised
*
* @param string $field
* @return bool
*/
public function isFieldVirtualised($field)
{
// Don't defer if field is non-virtualised
$ignore = $this->getNonVirtualisedFields();
if (in_array($field, $ignore ?? [])) {
return false;
}
// Don't defer if no virtual page
$copied = $this->CopyContentFrom();
if (!$copied || !$copied->exists()) {
return false;
}
// Check if copied object has this field
return $copied->hasField($field);
}
/**
* Pass unrecognized method calls on to the original data object
*
* @param string $method
* @param array $args
* @return mixed
*/
public function __call($method, $args)
{
if (parent::hasMethod($method)) {
return parent::__call($method, $args);
} else {
return call_user_func_array([$this->CopyContentFrom(), $method], $args ?? []);
}
}
/**
* @param string $field
* @return bool
*/
public function hasField($field)
{
if (parent::hasField($field)) {
return true;
}
$copy = $this->CopyContentFrom();
return $copy && $copy->exists() && $copy->hasField($field);
}
/**
* @param string $method
* @return bool
*/
public function hasMethod($method)
{
if (parent::hasMethod($method)) {
return true;
}
$copy = $this->CopyContentFrom();
return $copy && $copy->exists() && $copy->hasMethod($method);
}
/**
* Return the "casting helper" (a piece of PHP code that when evaluated creates a casted value object) for a field
* on this object.
*
* @param string $field
* @return string
*/
public function castingHelper($field)
{
$copy = $this->CopyContentFrom();
if ($copy && $copy->exists() && ($helper = $copy->castingHelper($field))) {
return $helper;
}
return parent::castingHelper($field);
}
/**
* {@inheritdoc}
*/
public function allMethodNames($custom = false)
{
$methods = parent::allMethodNames($custom);
if ($copy = $this->CopyContentFrom()) {
$methods = array_merge($methods, $copy->allMethodNames($custom));
}
return $methods;
}
/**
* {@inheritdoc}
*/
public function getControllerName()
{
if ($copy = $this->CopyContentFrom()) {
return $copy->getControllerName();
}
return parent::getControllerName();
}
}