-
Notifications
You must be signed in to change notification settings - Fork 333
/
CMSMain.php
2403 lines (2104 loc) · 78.4 KB
/
CMSMain.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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace SilverStripe\CMS\Controllers;
use InvalidArgumentException;
use Psr\SimpleCache\CacheInterface;
use SilverStripe\Admin\AdminRootController;
use SilverStripe\Admin\CMSBatchActionHandler;
use SilverStripe\Admin\LeftAndMain;
use SilverStripe\Admin\LeftAndMainFormRequestHandler;
use SilverStripe\CMS\BatchActions\CMSBatchAction_Archive;
use SilverStripe\CMS\BatchActions\CMSBatchAction_Publish;
use SilverStripe\CMS\BatchActions\CMSBatchAction_Restore;
use SilverStripe\CMS\BatchActions\CMSBatchAction_Unpublish;
use SilverStripe\CMS\Controllers\CMSSiteTreeFilter_Search;
use SilverStripe\CMS\Model\CurrentPageIdentifier;
use SilverStripe\CMS\Model\RedirectorPage;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\CMS\Model\VirtualPage;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Control\HTTPResponse_Exception;
use SilverStripe\Core\Cache\MemberCacheFlusher;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Convert;
use SilverStripe\Core\Environment;
use SilverStripe\Core\Flushable;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Forms\DateField;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\FieldGroup;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\FormAction;
use SilverStripe\Forms\FormField;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\Forms\GridField\GridFieldDataColumns;
use SilverStripe\Forms\GridField\GridFieldLevelup;
use SilverStripe\Forms\GridField\GridFieldPaginator;
use SilverStripe\Forms\GridField\GridFieldSortableHeader;
use SilverStripe\Forms\HiddenField;
use SilverStripe\Forms\LabelField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\Tab;
use SilverStripe\Forms\TabSet;
use SilverStripe\Forms\TextField;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\CMSPreviewable;
use SilverStripe\ORM\DataList;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\FieldType\DBHTMLText;
use SilverStripe\ORM\HiddenClass;
use SilverStripe\ORM\Hierarchy\Hierarchy;
use SilverStripe\ORM\Hierarchy\MarkedSet;
use SilverStripe\ORM\SS_List;
use SilverStripe\ORM\ValidationResult;
use SilverStripe\Security\InheritedPermissions;
use SilverStripe\Security\Member;
use SilverStripe\Security\Permission;
use SilverStripe\Security\PermissionProvider;
use SilverStripe\Security\Security;
use SilverStripe\Security\SecurityToken;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\Versioned\ChangeSet;
use SilverStripe\Versioned\ChangeSetItem;
use SilverStripe\Versioned\Versioned;
use SilverStripe\View\ArrayData;
use SilverStripe\View\Requirements;
use Translatable;
/**
* The main "content" area of the CMS.
*
* This class creates a 2-frame layout - left-tree and right-form - to sit beneath the main
* admin menu.
*
* @todo Create some base classes to contain the generic functionality that will be replicated.
*
* @mixin LeftAndMainPageIconsExtension
*/
class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionProvider, Flushable, MemberCacheFlusher
{
/**
* Unique ID for page icons CSS block
*/
const PAGE_ICONS_ID = 'PageIcons';
private static $url_segment = 'pages';
private static $url_rule = '/$Action/$ID/$OtherID';
// Maintain a lower priority than other administration sections
// so that Director does not think they are actions of CMSMain
private static $url_priority = 39;
private static $menu_title = 'Edit Page';
private static $menu_icon_class = 'font-icon-sitemap';
private static $menu_priority = 10;
private static $tree_class = SiteTree::class;
private static $subitem_class = Member::class;
private static $session_namespace = self::class;
private static $required_permission_codes = 'CMS_ACCESS_CMSMain';
/**
* Should the archive warning message be dynamic based on the specific content? This is slow on larger sites and can be disabled.
*
* @config
* @var bool
*/
private static $enable_dynamic_archive_warning_message = true;
/**
* Amount of results showing on a single page.
*
* @config
* @var int
*/
private static $page_length = 15;
private static $allowed_actions = [
'archive',
'deleteitems',
'DeleteItemsForm',
'dialog',
'duplicate',
'duplicatewithchildren',
'publishall',
'publishitems',
'PublishItemsForm',
'submit',
'EditForm',
'schema',
'SearchForm',
'SiteTreeAsUL',
'getshowdeletedsubtree',
'savetreenode',
'getsubtree',
'updatetreenodes',
'batchactions',
'treeview',
'listview',
'ListViewForm',
'childfilter',
];
private static $url_handlers = [
'EditForm/$ID' => 'EditForm',
];
private static $casting = [
'TreeIsFiltered' => 'Boolean',
'AddForm' => 'HTMLFragment',
'LinkPages' => 'Text',
'Link' => 'Text',
'ListViewForm' => 'HTMLFragment',
'ExtraTreeTools' => 'HTMLFragment',
'PageList' => 'HTMLFragment',
'PageListSidebar' => 'HTMLFragment',
'SiteTreeHints' => 'HTMLFragment',
'SecurityID' => 'Text',
'SiteTreeAsUL' => 'HTMLFragment',
];
private static $dependencies = [
'HintsCache' => '%$' . CacheInterface::class . '.CMSMain_SiteTreeHints',
];
/**
* @var CacheInterface
*/
protected $hintsCache;
protected function init()
{
// set reading lang
if (SiteTree::has_extension('Translatable') && !$this->getRequest()->isAjax()) {
Translatable::choose_site_locale(array_keys(Translatable::get_existing_content_languages(SiteTree::class) ?? []));
}
parent::init();
Requirements::javascript('silverstripe/cms: client/dist/js/bundle.js');
Requirements::javascript('silverstripe/cms: client/dist/js/SilverStripeNavigator.js');
Requirements::css('silverstripe/cms: client/dist/styles/bundle.css');
Requirements::customCSS($this->generatePageIconsCss(), self::PAGE_ICONS_ID);
Requirements::add_i18n_javascript('silverstripe/cms: client/lang', false, true);
CMSBatchActionHandler::register('restore', CMSBatchAction_Restore::class);
CMSBatchActionHandler::register('archive', CMSBatchAction_Archive::class);
CMSBatchActionHandler::register('unpublish', CMSBatchAction_Unpublish::class);
CMSBatchActionHandler::register('publish', CMSBatchAction_Publish::class);
}
public function index($request)
{
// In case we're not showing a specific record, explicitly remove any session state,
// to avoid it being highlighted in the tree, and causing an edit form to show.
if (!$request->param('Action')) {
$this->setCurrentPageID(null);
}
return parent::index($request);
}
public function getResponseNegotiator()
{
$negotiator = parent::getResponseNegotiator();
// ListViewForm
$negotiator->setCallback('ListViewForm', function () {
return $this->ListViewForm()->forTemplate();
});
return $negotiator;
}
/**
* Get pages listing area
*
* @return DBHTMLText
*/
public function PageList()
{
return $this->renderWith($this->getTemplatesWithSuffix('_PageList'));
}
/**
* Page list view for edit-form
*
* @return DBHTMLText
*/
public function PageListSidebar()
{
return $this->renderWith($this->getTemplatesWithSuffix('_PageList_Sidebar'));
}
/**
* If this is set to true, the "switchView" context in the
* template is shown, with links to the staging and publish site.
*
* @return boolean
*/
public function ShowSwitchView()
{
return true;
}
/**
* Overloads the LeftAndMain::ShowView. Allows to pass a page as a parameter, so we are able
* to switch view also for archived versions.
*
* @param SiteTree $page
* @return array
*/
public function SwitchView($page = null)
{
if (!$page) {
$page = $this->currentPage();
}
if ($page) {
$nav = SilverStripeNavigator::get_for_record($page);
return $nav['items'];
}
}
//------------------------------------------------------------------------------------------//
// Main controllers
//------------------------------------------------------------------------------------------//
// Main UI components
/**
* Override {@link LeftAndMain} Link to allow blank URL segment for CMSMain.
*
* @param string|null $action Action to link to.
* @return string
*/
public function Link($action = null)
{
$link = Controller::join_links(
AdminRootController::admin_url(),
$this->config()->get('url_segment'), // in case we want to change the segment
'/', // trailing slash needed if $action is null!
"$action"
);
$this->extend('updateLink', $link);
return $link;
}
public function LinkPages()
{
return CMSPagesController::singleton()->Link();
}
public function LinkPagesWithSearch()
{
return $this->LinkWithSearch($this->LinkPages());
}
/**
* Get link to tree view
*
* @return string
*/
public function LinkTreeView()
{
// Tree view is just default link to main pages section (no /treeview suffix)
return CMSMain::singleton()->Link();
}
/**
* Get link to list view
*
* @return string
*/
public function LinkListView()
{
// Note : Force redirect to top level page controller (no parentid)
return $this->LinkWithSearch(CMSMain::singleton()->Link('listview'));
}
/**
* Link to list view for children of a parent page
*
* @param int|string $parentID Literal parentID, or placeholder (e.g. '%d') for
* client side substitution
* @return string
*/
public function LinkListViewChildren($parentID)
{
return sprintf(
'%s?ParentID=%s',
CMSMain::singleton()->Link(),
$parentID
);
}
/**
* @return string
*/
public function LinkListViewRoot()
{
return $this->LinkListViewChildren(0);
}
/**
* Link to lazy-load deferred tree view
*
* @return string
*/
public function LinkTreeViewDeferred()
{
return $this->Link('treeview');
}
/**
* Link to lazy-load deferred list view
*
* @return string
*/
public function LinkListViewDeferred()
{
return $this->Link('listview');
}
public function LinkPageEdit($id = null)
{
if (!$id) {
$id = $this->currentPageID();
}
return $this->LinkWithSearch(
Controller::join_links(CMSPageEditController::singleton()->Link('show'), $id)
);
}
public function LinkPageSettings()
{
if ($id = $this->currentPageID()) {
return $this->LinkWithSearch(
Controller::join_links(CMSPageSettingsController::singleton()->Link('show'), $id)
);
} else {
return null;
}
}
public function LinkPageHistory()
{
if ($id = $this->currentPageID()) {
return $this->LinkWithSearch(
Controller::join_links(CMSPageHistoryController::singleton()->Link('show'), $id)
);
} else {
return null;
}
}
/**
* Return the active tab identifier for the CMS. Used by templates to decide which tab to give the active state.
* The default value is "edit", as the primary content tab. Child controllers will override this.
*
* @return string
*/
public function getTabIdentifier()
{
return 'edit';
}
/**
* @param CacheInterface $cache
* @return $this
*/
public function setHintsCache(CacheInterface $cache)
{
$this->hintsCache = $cache;
return $this;
}
/**
* @return CacheInterface $cache
*/
public function getHintsCache()
{
return $this->hintsCache;
}
/**
* Clears all dependent cache backends
*/
public function clearCache()
{
$this->getHintsCache()->clear();
}
public function LinkWithSearch($link)
{
// Whitelist to avoid side effects
$params = [
'q' => (array)$this->getRequest()->getVar('q'),
'ParentID' => $this->getRequest()->getVar('ParentID')
];
$link = Controller::join_links(
$link,
array_filter(array_values($params ?? [])) ? '?' . http_build_query($params) : null
);
$this->extend('updateLinkWithSearch', $link);
return $link;
}
public function LinkPageAdd($extra = null, $placeholders = null)
{
$link = CMSPageAddController::singleton()->Link();
$this->extend('updateLinkPageAdd', $link);
if ($extra) {
$link = Controller::join_links($link, $extra);
}
if ($placeholders) {
$link .= (strpos($link ?? '', '?') === false ? "?$placeholders" : "&$placeholders");
}
return $link;
}
/**
* @return string
*/
public function LinkPreview()
{
$record = $this->getRecord($this->currentPageID());
$baseLink = Director::absoluteBaseURL();
if ($record && $record instanceof SiteTree) {
// if we are an external redirector don't show a link
if ($record instanceof RedirectorPage && $record->RedirectionType == 'External') {
$baseLink = false;
} else {
$baseLink = $record->Link('?stage=Stage');
}
}
return $baseLink;
}
/**
* Return the entire site tree as a nested set of ULs
*/
public function SiteTreeAsUL()
{
$treeClass = $this->config()->get('tree_class');
$filter = $this->getSearchFilter();
DataObject::singleton($treeClass)->prepopulateTreeDataCache(null, [
'childrenMethod' => $filter ? $filter->getChildrenMethod() : 'AllChildrenIncludingDeleted',
'numChildrenMethod' => $filter ? $filter->getNumChildrenMethod() : 'numChildren',
]);
$html = $this->getSiteTreeFor($treeClass);
$this->extend('updateSiteTreeAsUL', $html);
return $html;
}
/**
* Get a site tree HTML listing which displays the nodes under the given criteria.
*
* @param string $className The class of the root object
* @param string $rootID The ID of the root object. If this is null then a complete tree will be
* shown
* @param string $childrenMethod The method to call to get the children of the tree. For example,
* Children, AllChildrenIncludingDeleted, or AllHistoricalChildren
* @param string $numChildrenMethod
* @param callable $filterFunction
* @param int $nodeCountThreshold
* @return string Nested unordered list with links to each page
*/
public function getSiteTreeFor(
$className,
$rootID = null,
$childrenMethod = null,
$numChildrenMethod = null,
$filterFunction = null,
$nodeCountThreshold = null
) {
$nodeCountThreshold = is_null($nodeCountThreshold) ? Config::inst()->get($className, 'node_threshold_total') : $nodeCountThreshold;
// Provide better defaults from filter
$filter = $this->getSearchFilter();
if ($filter) {
if (!$childrenMethod) {
$childrenMethod = $filter->getChildrenMethod();
}
if (!$numChildrenMethod) {
$numChildrenMethod = $filter->getNumChildrenMethod();
}
if (!$filterFunction) {
$filterFunction = function ($node) use ($filter) {
return $filter->isPageIncluded($node);
};
}
}
// Build set from node and begin marking
$record = ($rootID) ? $this->getRecord($rootID) : null;
$rootNode = $record ? $record : DataObject::singleton($className);
$markingSet = MarkedSet::create($rootNode, $childrenMethod, $numChildrenMethod, $nodeCountThreshold);
// Set filter function
if ($filterFunction) {
$markingSet->setMarkingFilterFunction($filterFunction);
}
// Mark tree from this node
$markingSet->markPartialTree();
// Ensure current page is exposed
$currentPage = $this->currentPage();
if ($currentPage) {
$markingSet->markToExpose($currentPage);
}
// Pre-cache permissions
$checker = SiteTree::getPermissionChecker();
if ($checker instanceof InheritedPermissions) {
$checker->prePopulatePermissionCache(
InheritedPermissions::EDIT,
$markingSet->markedNodeIDs()
);
}
// Render using full-subtree template
return $markingSet->renderChildren(
[ self::class . '_SubTree', 'type' => 'Includes' ],
$this->getTreeNodeCustomisations()
);
}
/**
* Get callback to determine template customisations for nodes
*
* @return callable
*/
protected function getTreeNodeCustomisations()
{
$rootTitle = $this->getCMSTreeTitle();
return function (SiteTree $node) use ($rootTitle) {
return [
'listViewLink' => $this->LinkListViewChildren($node->ID),
'rootTitle' => $rootTitle,
'extraClass' => $this->getTreeNodeClasses($node),
'Title' => _t(
self::class . '.PAGETYPE_TITLE',
'(Page type: {type}) {title}',
[
'type' => $node->i18n_singular_name(),
'title' => $node->Title,
]
)
];
};
}
/**
* Get extra CSS classes for a page's tree node
*
* @param SiteTree $node
* @return string
*/
public function getTreeNodeClasses(SiteTree $node)
{
// Get classes from object
$classes = $node->CMSTreeClasses();
// Get status flag classes
$flags = $node->getStatusFlags();
if ($flags) {
$statuses = array_keys($flags ?? []);
foreach ($statuses as $s) {
$classes .= ' status-' . $s;
}
}
// Get additional filter classes
$filter = $this->getSearchFilter();
if ($filter && ($filterClasses = $filter->getPageClasses($node))) {
if (is_array($filterClasses)) {
$filterClasses = implode(' ', $filterClasses);
}
$classes .= ' ' . $filterClasses;
}
return trim($classes ?? '');
}
/**
* Get a subtree underneath the request param 'ID'.
* If ID = 0, then get the whole tree.
*
* @param HTTPRequest $request
* @return string
*/
public function getsubtree($request)
{
$html = $this->getSiteTreeFor(
$this->config()->get('tree_class'),
$request->getVar('ID'),
null,
null,
null,
$request->getVar('minNodeCount')
);
// Trim off the outer tag
$html = preg_replace('/^[\s\t\r\n]*<ul[^>]*>/', '', $html ?? '');
$html = preg_replace('/<\/ul[^>]*>[\s\t\r\n]*$/', '', $html ?? '');
return $html;
}
/**
* Allows requesting a view update on specific tree nodes.
* Similar to {@link getsubtree()}, but doesn't enforce loading
* all children with the node. Useful to refresh views after
* state modifications, e.g. saving a form.
*
* @param HTTPRequest $request
* @return HTTPResponse
*/
public function updatetreenodes($request)
{
$data = [];
$ids = explode(',', $request->getVar('ids') ?? '');
foreach ($ids as $id) {
if ($id === "") {
continue; // $id may be a blank string, which is invalid and should be skipped over
}
$record = $this->getRecord($id);
if (!$record) {
continue; // In case a page is no longer available
}
// Create marking set with sole marked root
$markingSet = MarkedSet::create($record);
$markingSet->setMarkingFilterFunction(function () {
return false;
});
$markingSet->markUnexpanded($record);
// Find the next & previous nodes, for proper positioning (Sort isn't good enough - it's not a raw offset)
// TODO: These methods should really be in hierarchy - for a start it assumes Sort exists
$prev = null;
$className = $this->config()->get('tree_class');
$next = DataObject::get($className)
->filter('ParentID', $record->ParentID)
->filter('Sort:GreaterThan', $record->Sort)
->first();
if (!$next) {
$prev = DataObject::get($className)
->filter('ParentID', $record->ParentID)
->filter('Sort:LessThan', $record->Sort)
->reverse()
->first();
}
// Render using single node template
$html = $markingSet->renderChildren(
[ self::class . '_TreeNode', 'type' => 'Includes'],
$this->getTreeNodeCustomisations()
);
$data[$id] = [
'html' => $html,
'ParentID' => $record->ParentID,
'NextID' => $next ? $next->ID : null,
'PrevID' => $prev ? $prev->ID : null
];
}
return $this
->getResponse()
->addHeader('Content-Type', 'application/json')
->setBody(json_encode($data));
}
/**
* Update the position and parent of a tree node.
* Only saves the node if changes were made.
*
* Required data:
* - 'ID': The moved node
* - 'ParentID': New parent relation of the moved node (0 for root)
* - 'SiblingIDs': Array of all sibling nodes to the moved node (incl. the node itself).
* In case of a 'ParentID' change, relates to the new siblings under the new parent.
*
* @param HTTPRequest $request
* @return HTTPResponse JSON string with a
* @throws HTTPResponse_Exception
*/
public function savetreenode($request)
{
if (!SecurityToken::inst()->checkRequest($request)) {
return $this->httpError(400);
}
if (!$this->CanOrganiseSitetree()) {
return $this->httpError(
403,
_t(
__CLASS__.'.CANT_REORGANISE',
"You do not have permission to rearange the site tree. Your change was not saved."
)
);
}
$className = $this->config()->get('tree_class');
$id = $request->requestVar('ID');
$parentID = $request->requestVar('ParentID');
if (!is_numeric($id) || !is_numeric($parentID)) {
return $this->httpError(400);
}
// Check record exists in the DB
/** @var SiteTree $node */
$node = DataObject::get_by_id($className, $id);
if (!$node) {
return $this->httpError(
500,
_t(
__CLASS__.'.PLEASESAVE',
"Please Save Page: This page could not be updated because it hasn't been saved yet."
)
);
}
// Check top level permissions
$root = $node->getParentType();
if (($parentID == '0' || $root == 'root') && !SiteConfig::current_site_config()->canCreateTopLevel()) {
return $this->httpError(
403,
_t(
__CLASS__.'.CANT_REORGANISE',
"You do not have permission to alter Top level pages. Your change was not saved."
)
);
}
$siblingIDs = $request->requestVar('SiblingIDs');
$statusUpdates = ['modified'=>[]];
if (!$node->canEdit()) {
return Security::permissionFailure($this);
}
// Update hierarchy (only if ParentID changed)
if ($node->ParentID != $parentID) {
$node->ParentID = (int)$parentID;
$node->write();
$statusUpdates['modified'][$node->ID] = [
'TreeTitle' => $node->TreeTitle
];
// Update all dependent pages
$virtualPages = VirtualPage::get()->filter("CopyContentFromID", $node->ID);
foreach ($virtualPages as $virtualPage) {
$statusUpdates['modified'][$virtualPage->ID] = [
'TreeTitle' => $virtualPage->TreeTitle
];
}
$this->getResponse()->addHeader(
'X-Status',
rawurlencode(_t(__CLASS__.'.REORGANISATIONSUCCESSFUL', 'Reorganised the site tree successfully.') ?? '')
);
}
// Update sorting
if (is_array($siblingIDs)) {
$counter = 0;
foreach ($siblingIDs as $id) {
if ($id == $node->ID) {
$node->Sort = ++$counter;
$node->write();
$statusUpdates['modified'][$node->ID] = [
'TreeTitle' => $node->TreeTitle
];
} elseif (is_numeric($id)) {
// Nodes that weren't "actually moved" shouldn't be registered as
// having been edited; do a direct SQL update instead
++$counter;
$table = DataObject::getSchema()->baseDataTable($className);
DB::prepared_query(
"UPDATE \"$table\" SET \"Sort\" = ? WHERE \"ID\" = ?",
[$counter, $id]
);
}
}
$this->getResponse()->addHeader(
'X-Status',
rawurlencode(_t(__CLASS__.'.REORGANISATIONSUCCESSFUL', 'Reorganised the site tree successfully.') ?? '')
);
}
return $this
->getResponse()
->addHeader('Content-Type', 'application/json')
->setBody(json_encode($statusUpdates));
}
/**
* Whether the current member has the permission to reorganise SiteTree objects.
* @return bool
*/
public function CanOrganiseSitetree()
{
return Permission::check('SITETREE_REORGANISE');
}
/**
* @return boolean
*/
public function TreeIsFiltered()
{
$query = $this->getRequest()->getVar('q');
return !empty($query);
}
public function ExtraTreeTools()
{
$html = '';
$this->extend('updateExtraTreeTools', $html);
return $html;
}
/**
* This provides information required to generate the search form
* and can be modified on extensions through updateSearchContext
*
* @return \SilverStripe\ORM\Search\SearchContext
*/
public function getSearchContext()
{
$context = SiteTree::singleton()->getDefaultSearchContext();
$this->extend('updateSearchContext', $context);
return $context;
}
/**
* Returns the search form schema for the current model
*
* @return string
*/
public function getSearchFieldSchema()
{
$schemaUrl = $this->Link('schema/SearchForm');
$context = $this->getSearchContext();
$params = $this->getRequest()->requestVar('q') ?: [];
$context->setSearchParams($params);
$placeholder = _t('SilverStripe\\CMS\\Search\\SearchForm.FILTERLABELTEXT', 'Search') . ' "' .
SiteTree::singleton()->i18n_plural_name() . '"';
$searchParams = $context->getSearchParams();
$searchParams = array_combine(array_map(function ($key) {
return 'Search__' . $key;
}, array_keys($searchParams ?? [])), $searchParams ?? []);
$schema = [
'formSchemaUrl' => $schemaUrl,
'name' => 'Term',
'placeholder' => $placeholder,
'filters' => $searchParams ?: new \stdClass // stdClass maps to empty json object '{}'
];
return json_encode($schema);
}
/**
* Returns a Form for page searching for use in templates.
*
* Can be modified from a decorator by a 'updateSearchForm' method
*
* @return Form
*/
public function getSearchForm()
{
// Create the fields
$dateFrom = DateField::create(
'Search__LastEditedFrom',
_t('SilverStripe\\CMS\\Search\\SearchForm.FILTERDATEFROM', 'From')
)->setLocale(Security::getCurrentUser()->Locale);
$dateTo = DateField::create(
'Search__LastEditedTo',
_t('SilverStripe\\CMS\\Search\\SearchForm.FILTERDATETO', 'To')
)->setLocale(Security::getCurrentUser()->Locale);
$filters = CMSSiteTreeFilter::get_all_filters();
// Remove 'All pages' as we set that to empty/default value
unset($filters[CMSSiteTreeFilter_Search::class]);
$pageFilter = DropdownField::create(
'Search__FilterClass',
_t('SilverStripe\\CMS\\Controllers\\CMSMain.PAGES', 'Page status'),
$filters
);
$pageFilter->setEmptyString(_t('SilverStripe\\CMS\\Controllers\\CMSMain.PAGESALLOPT', 'All pages'));
$pageClasses = DropdownField::create(
'Search__ClassName',
_t('SilverStripe\\CMS\\Controllers\\CMSMain.PAGETYPEOPT', 'Page type', 'Dropdown for limiting search to a page type'),
$this->getPageTypes()
);
$pageClasses->setEmptyString(_t('SilverStripe\\CMS\\Controllers\\CMSMain.PAGETYPEANYOPT', 'Any'));
// Group the Datefields
$dateGroup = FieldGroup::create(
_t('SilverStripe\\CMS\\Search\\SearchForm.PAGEFILTERDATEHEADING', 'Last edited'),
[$dateFrom, $dateTo]
)->setName('Search__LastEdited')
->addExtraClass('fieldgroup--fill-width');
// Create the Field list
$fields = new FieldList(
$pageFilter,
$pageClasses,
$dateGroup
);
// Create the form
/** @skipUpgrade */
$form = Form::create(
$this,
'SearchForm',
$fields,
new FieldList()
);
$form->addExtraClass('cms-search-form');
$form->setFormMethod('GET');
$form->setFormAction(CMSMain::singleton()->Link());
$form->disableSecurityToken();
$form->unsetValidator();
// Load the form with previously sent search data