Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like CMSMain often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use CMSMain, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
76 | class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionProvider { |
||
77 | |||
78 | private static $url_segment = 'pages'; |
||
|
|||
79 | |||
80 | private static $url_rule = '/$Action/$ID/$OtherID'; |
||
81 | |||
82 | // Maintain a lower priority than other administration sections |
||
83 | // so that Director does not think they are actions of CMSMain |
||
84 | private static $url_priority = 39; |
||
85 | |||
86 | private static $menu_title = 'Edit Page'; |
||
87 | |||
88 | private static $menu_icon_class = 'font-icon-sitemap'; |
||
89 | |||
90 | private static $menu_priority = 10; |
||
91 | |||
92 | private static $tree_class = SiteTree::class; |
||
93 | |||
94 | private static $subitem_class = Member::class; |
||
95 | |||
96 | private static $session_namespace = 'SilverStripe\\CMS\\Controllers\\CMSMain'; |
||
97 | |||
98 | private static $required_permission_codes = 'CMS_ACCESS_CMSMain'; |
||
99 | |||
100 | /** |
||
101 | * Amount of results showing on a single page. |
||
102 | * |
||
103 | * @config |
||
104 | * @var int |
||
105 | */ |
||
106 | private static $page_length = 15; |
||
107 | |||
108 | private static $allowed_actions = array( |
||
109 | 'archive', |
||
110 | 'deleteitems', |
||
111 | 'DeleteItemsForm', |
||
112 | 'dialog', |
||
113 | 'duplicate', |
||
114 | 'duplicatewithchildren', |
||
115 | 'publishall', |
||
116 | 'publishitems', |
||
117 | 'PublishItemsForm', |
||
118 | 'submit', |
||
119 | 'EditForm', |
||
120 | 'SearchForm', |
||
121 | 'SiteTreeAsUL', |
||
122 | 'getshowdeletedsubtree', |
||
123 | 'batchactions', |
||
124 | 'treeview', |
||
125 | 'listview', |
||
126 | 'ListViewForm', |
||
127 | 'childfilter', |
||
128 | ); |
||
129 | |||
130 | private static $casting = array( |
||
131 | 'TreeIsFiltered' => 'Boolean', |
||
132 | 'AddForm' => 'HTMLFragment', |
||
133 | 'LinkPages' => 'Text', |
||
134 | 'Link' => 'Text', |
||
135 | 'ListViewForm' => 'HTMLFragment', |
||
136 | 'ExtraTreeTools' => 'HTMLFragment', |
||
137 | 'PageList' => 'HTMLFragment', |
||
138 | 'PageListSidebar' => 'HTMLFragment', |
||
139 | 'SiteTreeHints' => 'HTMLFragment', |
||
140 | 'SecurityID' => 'Text', |
||
141 | 'SiteTreeAsUL' => 'HTMLFragment', |
||
142 | ); |
||
143 | |||
144 | public function init() { |
||
145 | // set reading lang |
||
146 | if(SiteTree::has_extension('Translatable') && !$this->getRequest()->isAjax()) { |
||
147 | Translatable::choose_site_locale(array_keys(Translatable::get_existing_content_languages('SilverStripe\\CMS\\Model\\SiteTree'))); |
||
148 | } |
||
149 | |||
150 | parent::init(); |
||
151 | |||
152 | Requirements::javascript(CMS_DIR . '/client/dist/js/bundle.js'); |
||
153 | Requirements::javascript(CMS_DIR . '/client/dist/js/SilverStripeNavigator.js'); |
||
154 | Requirements::css(CMS_DIR . '/client/dist/styles/bundle.css'); |
||
155 | Requirements::customCSS($this->generatePageIconsCss()); |
||
156 | Requirements::add_i18n_javascript(CMS_DIR . '/client/lang', false, true); |
||
157 | |||
158 | CMSBatchActionHandler::register('restore', CMSBatchAction_Restore::class); |
||
159 | CMSBatchActionHandler::register('archive', CMSBatchAction_Archive::class); |
||
160 | CMSBatchActionHandler::register('unpublish', CMSBatchAction_Unpublish::class); |
||
161 | CMSBatchActionHandler::register('publish', CMSBatchAction_Publish::class); |
||
162 | } |
||
163 | |||
164 | public function index($request) { |
||
165 | // In case we're not showing a specific record, explicitly remove any session state, |
||
166 | // to avoid it being highlighted in the tree, and causing an edit form to show. |
||
167 | if(!$request->param('Action')) { |
||
168 | $this->setCurrentPageID(null); |
||
169 | } |
||
170 | |||
171 | return parent::index($request); |
||
172 | } |
||
173 | |||
174 | public function getResponseNegotiator() { |
||
175 | $negotiator = parent::getResponseNegotiator(); |
||
176 | |||
177 | // ListViewForm |
||
178 | $negotiator->setCallback('ListViewForm', function() { |
||
179 | return $this->ListViewForm()->forTemplate(); |
||
180 | }); |
||
181 | |||
182 | // PageList view |
||
183 | $negotiator->setCallback('Content-PageList', function () { |
||
184 | return $this->PageList()->forTemplate(); |
||
185 | }); |
||
186 | |||
187 | // PageList view for edit controller |
||
188 | $negotiator->setCallback('Content-PageList-Sidebar', function() { |
||
189 | return $this->PageListSidebar()->forTemplate(); |
||
190 | }); |
||
191 | |||
192 | return $negotiator; |
||
193 | } |
||
194 | |||
195 | /** |
||
196 | * Get pages listing area |
||
197 | * |
||
198 | * @return DBHTMLText |
||
199 | */ |
||
200 | public function PageList() { |
||
201 | return $this->renderWith($this->getTemplatesWithSuffix('_PageList')); |
||
202 | } |
||
203 | |||
204 | /** |
||
205 | * Page list view for edit-form |
||
206 | * |
||
207 | * @return DBHTMLText |
||
208 | */ |
||
209 | public function PageListSidebar() { |
||
210 | return $this->renderWith($this->getTemplatesWithSuffix('_PageList_Sidebar')); |
||
211 | } |
||
212 | |||
213 | /** |
||
214 | * If this is set to true, the "switchView" context in the |
||
215 | * template is shown, with links to the staging and publish site. |
||
216 | * |
||
217 | * @return boolean |
||
218 | */ |
||
219 | public function ShowSwitchView() { |
||
220 | return true; |
||
221 | } |
||
222 | |||
223 | /** |
||
224 | * Overloads the LeftAndMain::ShowView. Allows to pass a page as a parameter, so we are able |
||
225 | * to switch view also for archived versions. |
||
226 | * |
||
227 | * @param SiteTree $page |
||
228 | * @return array |
||
229 | */ |
||
230 | public function SwitchView($page = null) { |
||
231 | if(!$page) { |
||
232 | $page = $this->currentPage(); |
||
233 | } |
||
234 | |||
235 | if($page) { |
||
236 | $nav = SilverStripeNavigator::get_for_record($page); |
||
237 | return $nav['items']; |
||
238 | } |
||
239 | } |
||
240 | |||
241 | //------------------------------------------------------------------------------------------// |
||
242 | // Main controllers |
||
243 | |||
244 | //------------------------------------------------------------------------------------------// |
||
245 | // Main UI components |
||
246 | |||
247 | /** |
||
248 | * Override {@link LeftAndMain} Link to allow blank URL segment for CMSMain. |
||
249 | * |
||
250 | * @param string|null $action Action to link to. |
||
251 | * @return string |
||
252 | */ |
||
253 | public function Link($action = null) { |
||
254 | $link = Controller::join_links( |
||
255 | AdminRootController::admin_url(), |
||
256 | $this->stat('url_segment'), // in case we want to change the segment |
||
257 | '/', // trailing slash needed if $action is null! |
||
258 | "$action" |
||
259 | ); |
||
260 | $this->extend('updateLink', $link); |
||
261 | return $link; |
||
262 | } |
||
263 | |||
264 | public function LinkPages() { |
||
265 | return CMSPagesController::singleton()->Link(); |
||
266 | } |
||
267 | |||
268 | public function LinkPagesWithSearch() { |
||
269 | return $this->LinkWithSearch($this->LinkPages()); |
||
270 | } |
||
271 | |||
272 | /** |
||
273 | * Get link to tree view |
||
274 | * |
||
275 | * @return string |
||
276 | */ |
||
277 | public function LinkTreeView() { |
||
278 | // Tree view is just default link to main pages section (no /treeview suffix) |
||
279 | return $this->LinkWithSearch(CMSMain::singleton()->Link()); |
||
280 | } |
||
281 | |||
282 | /** |
||
283 | * Get link to list view |
||
284 | * |
||
285 | * @return string |
||
286 | */ |
||
287 | public function LinkListView() { |
||
288 | // Note : Force redirect to top level page controller |
||
289 | return $this->LinkWithSearch(CMSMain::singleton()->Link('listview')); |
||
290 | } |
||
291 | |||
292 | View Code Duplication | public function LinkPageEdit($id = null) { |
|
293 | if(!$id) { |
||
294 | $id = $this->currentPageID(); |
||
295 | } |
||
296 | return $this->LinkWithSearch( |
||
297 | Controller::join_links(CMSPageEditController::singleton()->Link('show'), $id) |
||
298 | ); |
||
299 | } |
||
300 | |||
301 | View Code Duplication | public function LinkPageSettings() { |
|
302 | if($id = $this->currentPageID()) { |
||
303 | return $this->LinkWithSearch( |
||
304 | Controller::join_links(CMSPageSettingsController::singleton()->Link('show'), $id) |
||
305 | ); |
||
306 | } else { |
||
307 | return null; |
||
308 | } |
||
309 | } |
||
310 | |||
311 | View Code Duplication | public function LinkPageHistory() { |
|
312 | if($id = $this->currentPageID()) { |
||
313 | return $this->LinkWithSearch( |
||
314 | Controller::join_links(CMSPageHistoryController::singleton()->Link('show'), $id) |
||
315 | ); |
||
316 | } else { |
||
317 | return null; |
||
318 | } |
||
319 | } |
||
320 | |||
321 | public function LinkWithSearch($link) { |
||
322 | // Whitelist to avoid side effects |
||
323 | $params = array( |
||
324 | 'q' => (array)$this->getRequest()->getVar('q'), |
||
325 | 'ParentID' => $this->getRequest()->getVar('ParentID') |
||
326 | ); |
||
327 | $link = Controller::join_links( |
||
328 | $link, |
||
329 | array_filter(array_values($params)) ? '?' . http_build_query($params) : null |
||
330 | ); |
||
331 | $this->extend('updateLinkWithSearch', $link); |
||
332 | return $link; |
||
333 | } |
||
334 | |||
335 | public function LinkPageAdd($extra = null, $placeholders = null) { |
||
336 | $link = CMSPageAddController::singleton()->Link(); |
||
337 | $this->extend('updateLinkPageAdd', $link); |
||
338 | |||
339 | if($extra) { |
||
340 | $link = Controller::join_links ($link, $extra); |
||
341 | } |
||
342 | |||
343 | if($placeholders) { |
||
344 | $link .= (strpos($link, '?') === false ? "?$placeholders" : "&$placeholders"); |
||
345 | } |
||
346 | |||
347 | return $link; |
||
348 | } |
||
349 | |||
350 | /** |
||
351 | * @return string |
||
352 | */ |
||
353 | public function LinkPreview() { |
||
354 | $record = $this->getRecord($this->currentPageID()); |
||
355 | $baseLink = Director::absoluteBaseURL(); |
||
356 | if ($record && $record instanceof SiteTree) { |
||
357 | // if we are an external redirector don't show a link |
||
358 | if ($record instanceof RedirectorPage && $record->RedirectionType == 'External') { |
||
359 | $baseLink = false; |
||
360 | } |
||
361 | else { |
||
362 | $baseLink = $record->Link('?stage=Stage'); |
||
363 | } |
||
364 | } |
||
365 | return $baseLink; |
||
366 | } |
||
367 | |||
368 | /** |
||
369 | * Return the entire site tree as a nested set of ULs |
||
370 | */ |
||
371 | public function SiteTreeAsUL() { |
||
372 | // Pre-cache sitetree version numbers for querying efficiency |
||
373 | Versioned::prepopulate_versionnumber_cache(SiteTree::class, "Stage"); |
||
374 | Versioned::prepopulate_versionnumber_cache(SiteTree::class, "Live"); |
||
375 | $html = $this->getSiteTreeFor($this->stat('tree_class')); |
||
376 | |||
377 | $this->extend('updateSiteTreeAsUL', $html); |
||
378 | |||
379 | return $html; |
||
380 | } |
||
381 | |||
382 | /** |
||
383 | * @return boolean |
||
384 | */ |
||
385 | public function TreeIsFiltered() { |
||
386 | $query = $this->getRequest()->getVar('q'); |
||
387 | |||
388 | if (!$query || (count($query) === 1 && isset($query['FilterClass']) && $query['FilterClass'] === 'SilverStripe\\CMS\\Controllers\\CMSSiteTreeFilter_Search')) { |
||
389 | return false; |
||
390 | } |
||
391 | |||
392 | return true; |
||
393 | } |
||
394 | |||
395 | public function ExtraTreeTools() { |
||
396 | $html = ''; |
||
397 | $this->extend('updateExtraTreeTools', $html); |
||
398 | return $html; |
||
399 | } |
||
400 | |||
401 | /** |
||
402 | * Returns a Form for page searching for use in templates. |
||
403 | * |
||
404 | * Can be modified from a decorator by a 'updateSearchForm' method |
||
405 | * |
||
406 | * @return Form |
||
407 | */ |
||
408 | public function SearchForm() { |
||
409 | // Create the fields |
||
410 | $content = new TextField('q[Term]', _t('CMSSearch.FILTERLABELTEXT', 'Search')); |
||
411 | $dateFrom = new DateField( |
||
412 | 'q[LastEditedFrom]', |
||
413 | _t('CMSSearch.FILTERDATEFROM', 'From') |
||
414 | ); |
||
415 | $dateFrom->setConfig('showcalendar', true); |
||
416 | $dateTo = new DateField( |
||
417 | 'q[LastEditedTo]', |
||
418 | _t('CMSSearch.FILTERDATETO', 'To') |
||
419 | ); |
||
420 | $dateTo->setConfig('showcalendar', true); |
||
421 | $pageFilter = new DropdownField( |
||
422 | 'q[FilterClass]', |
||
423 | _t('CMSMain.PAGES', 'Page status'), |
||
424 | CMSSiteTreeFilter::get_all_filters() |
||
425 | ); |
||
426 | $pageClasses = new DropdownField( |
||
427 | 'q[ClassName]', |
||
428 | _t('CMSMain.PAGETYPEOPT', 'Page type', 'Dropdown for limiting search to a page type'), |
||
429 | $this->getPageTypes() |
||
430 | ); |
||
431 | $pageClasses->setEmptyString(_t('CMSMain.PAGETYPEANYOPT','Any')); |
||
432 | |||
433 | // Group the Datefields |
||
434 | $dateGroup = new FieldGroup( |
||
435 | $dateFrom, |
||
436 | $dateTo |
||
437 | ); |
||
438 | $dateGroup->setTitle(_t('CMSSearch.PAGEFILTERDATEHEADING', 'Last edited')); |
||
439 | |||
440 | // view mode |
||
441 | $viewMode = HiddenField::create('view', false, $this->ViewState()); |
||
442 | |||
443 | // Create the Field list |
||
444 | $fields = new FieldList( |
||
445 | $content, |
||
446 | $pageFilter, |
||
447 | $pageClasses, |
||
448 | $dateGroup, |
||
449 | $viewMode |
||
450 | ); |
||
451 | |||
452 | // Create the Search and Reset action |
||
453 | $actions = new FieldList( |
||
454 | FormAction::create('doSearch', _t('CMSMain_left_ss.APPLY_FILTER', 'Search')) |
||
455 | ->addExtraClass('btn btn-primary'), |
||
456 | ResetFormAction::create('clear', _t('CMSMain_left_ss.CLEAR_FILTER', 'Clear')) |
||
457 | ->addExtraClass('btn btn-secondary') |
||
458 | ); |
||
459 | |||
460 | // Use <button> to allow full jQuery UI styling on the all of the Actions |
||
461 | /** @var FormAction $action */ |
||
462 | foreach($actions->dataFields() as $action) { |
||
463 | /** @var FormAction $action */ |
||
464 | $action->setUseButtonTag(true); |
||
465 | } |
||
466 | |||
467 | // Create the form |
||
468 | /** @skipUpgrade */ |
||
469 | $form = Form::create($this, 'SearchForm', $fields, $actions) |
||
470 | ->addExtraClass('cms-search-form') |
||
471 | ->setFormMethod('GET') |
||
472 | ->setFormAction($this->Link()) |
||
473 | ->disableSecurityToken() |
||
474 | ->unsetValidator(); |
||
475 | |||
476 | // Load the form with previously sent search data |
||
477 | $form->loadDataFrom($this->getRequest()->getVars()); |
||
478 | |||
479 | // Allow decorators to modify the form |
||
480 | $this->extend('updateSearchForm', $form); |
||
481 | |||
482 | return $form; |
||
483 | } |
||
484 | |||
485 | /** |
||
486 | * Returns a sorted array suitable for a dropdown with pagetypes and their translated name |
||
487 | * |
||
488 | * @return array |
||
489 | */ |
||
490 | protected function getPageTypes() { |
||
491 | $pageTypes = array(); |
||
492 | foreach(SiteTree::page_type_classes() as $pageTypeClass) { |
||
493 | $pageTypes[$pageTypeClass] = SiteTree::singleton($pageTypeClass)->i18n_singular_name(); |
||
494 | } |
||
495 | asort($pageTypes); |
||
496 | return $pageTypes; |
||
497 | } |
||
498 | |||
499 | public function doSearch($data, $form) { |
||
500 | return $this->getsubtree($this->getRequest()); |
||
501 | } |
||
502 | |||
503 | /** |
||
504 | * @param bool $unlinked |
||
505 | * @return ArrayList |
||
506 | */ |
||
507 | public function Breadcrumbs($unlinked = false) { |
||
508 | $items = parent::Breadcrumbs($unlinked); |
||
509 | |||
510 | if($items->count() > 1) { |
||
511 | // Specific to the SiteTree admin section, we never show the cms section and current |
||
512 | // page in the same breadcrumbs block. |
||
513 | $items->shift(); |
||
514 | } |
||
515 | |||
516 | return $items; |
||
517 | } |
||
518 | |||
519 | /** |
||
520 | * Create serialized JSON string with site tree hints data to be injected into |
||
521 | * 'data-hints' attribute of root node of jsTree. |
||
522 | * |
||
523 | * @return string Serialized JSON |
||
524 | */ |
||
525 | public function SiteTreeHints() { |
||
526 | $classes = SiteTree::page_type_classes(); |
||
527 | |||
528 | $cacheCanCreate = array(); |
||
529 | foreach($classes as $class) $cacheCanCreate[$class] = singleton($class)->canCreate(); |
||
530 | |||
531 | // Generate basic cache key. Too complex to encompass all variations |
||
532 | $cache = Cache::factory('CMSMain_SiteTreeHints'); |
||
533 | $cacheKey = md5(implode('_', array(Member::currentUserID(), implode(',', $cacheCanCreate), implode(',', $classes)))); |
||
534 | if($this->getRequest()->getVar('flush')) { |
||
535 | $cache->clean(Zend_Cache::CLEANING_MODE_ALL); |
||
536 | } |
||
537 | $json = $cache->load($cacheKey); |
||
538 | if(!$json) { |
||
539 | $def['Root'] = array(); |
||
540 | $def['Root']['disallowedChildren'] = array(); |
||
541 | |||
542 | // Contains all possible classes to support UI controls listing them all, |
||
543 | // such as the "add page here" context menu. |
||
544 | $def['All'] = array(); |
||
545 | |||
546 | // Identify disallows and set globals |
||
547 | foreach($classes as $class) { |
||
548 | $obj = singleton($class); |
||
549 | if($obj instanceof HiddenClass) continue; |
||
550 | |||
551 | // Name item |
||
552 | $def['All'][$class] = array( |
||
553 | 'title' => $obj->i18n_singular_name() |
||
554 | ); |
||
555 | |||
556 | // Check if can be created at the root |
||
557 | $needsPerm = $obj->stat('need_permission'); |
||
558 | if( |
||
559 | !$obj->stat('can_be_root') |
||
560 | || (!array_key_exists($class, $cacheCanCreate) || !$cacheCanCreate[$class]) |
||
561 | || ($needsPerm && !$this->can($needsPerm)) |
||
562 | ) { |
||
563 | $def['Root']['disallowedChildren'][] = $class; |
||
564 | } |
||
565 | |||
566 | // Hint data specific to the class |
||
567 | $def[$class] = array(); |
||
568 | |||
569 | $defaultChild = $obj->defaultChild(); |
||
570 | if($defaultChild !== 'Page' && $defaultChild !== null) { |
||
571 | $def[$class]['defaultChild'] = $defaultChild; |
||
572 | } |
||
573 | |||
574 | $defaultParent = $obj->defaultParent(); |
||
575 | if ($defaultParent !== 1 && $defaultParent !== null) { |
||
576 | $def[$class]['defaultParent'] = $defaultParent; |
||
577 | } |
||
578 | } |
||
579 | |||
580 | $this->extend('updateSiteTreeHints', $def); |
||
581 | |||
582 | $json = Convert::raw2json($def); |
||
583 | $cache->save($json, $cacheKey); |
||
584 | } |
||
585 | return $json; |
||
586 | } |
||
587 | |||
588 | /** |
||
589 | * Populates an array of classes in the CMS |
||
590 | * which allows the user to change the page type. |
||
591 | * |
||
592 | * @return SS_List |
||
593 | */ |
||
594 | public function PageTypes() { |
||
595 | $classes = SiteTree::page_type_classes(); |
||
596 | |||
597 | $result = new ArrayList(); |
||
598 | |||
599 | foreach($classes as $class) { |
||
600 | $instance = singleton($class); |
||
601 | |||
602 | if($instance instanceof HiddenClass) { |
||
603 | continue; |
||
604 | } |
||
605 | |||
606 | // skip this type if it is restricted |
||
607 | if($instance->stat('need_permission') && !$this->can(singleton($class)->stat('need_permission'))) { |
||
608 | continue; |
||
609 | } |
||
610 | |||
611 | $addAction = $instance->i18n_singular_name(); |
||
612 | |||
613 | // Get description (convert 'Page' to 'SiteTree' for correct localization lookups) |
||
614 | $i18nClass = ($class == 'Page') ? 'SilverStripe\\CMS\\Model\\SiteTree' : $class; |
||
615 | $description = _t($i18nClass . '.DESCRIPTION'); |
||
616 | |||
617 | if(!$description) { |
||
618 | $description = $instance->uninherited('description'); |
||
619 | } |
||
620 | |||
621 | if($class == 'Page' && !$description) { |
||
622 | $description = SiteTree::singleton()->uninherited('description'); |
||
623 | } |
||
624 | |||
625 | $result->push(new ArrayData(array( |
||
626 | 'ClassName' => $class, |
||
627 | 'AddAction' => $addAction, |
||
628 | 'Description' => $description, |
||
629 | // TODO Sprite support |
||
630 | 'IconURL' => $instance->stat('icon'), |
||
631 | 'Title' => singleton($class)->i18n_singular_name(), |
||
632 | ))); |
||
633 | } |
||
634 | |||
635 | $result = $result->sort('AddAction'); |
||
636 | |||
637 | return $result; |
||
638 | } |
||
639 | |||
640 | /** |
||
641 | * Get a database record to be managed by the CMS. |
||
642 | * |
||
643 | * @param int $id Record ID |
||
644 | * @param int $versionID optional Version id of the given record |
||
645 | * @return SiteTree |
||
646 | */ |
||
647 | public function getRecord($id, $versionID = null) { |
||
648 | $treeClass = $this->stat('tree_class'); |
||
649 | |||
650 | if($id instanceof $treeClass) { |
||
651 | return $id; |
||
652 | } |
||
653 | else if($id && is_numeric($id)) { |
||
654 | $currentStage = Versioned::get_reading_mode(); |
||
655 | |||
656 | if($this->getRequest()->getVar('Version')) { |
||
657 | $versionID = (int) $this->getRequest()->getVar('Version'); |
||
658 | } |
||
659 | |||
660 | if($versionID) { |
||
661 | $record = Versioned::get_version($treeClass, $id, $versionID); |
||
662 | } else { |
||
663 | $record = DataObject::get_by_id($treeClass, $id); |
||
664 | } |
||
665 | |||
666 | // Then, try getting a record from the live site |
||
667 | if(!$record) { |
||
668 | // $record = Versioned::get_one_by_stage($treeClass, "Live", "\"$treeClass\".\"ID\" = $id"); |
||
669 | Versioned::set_stage(Versioned::LIVE); |
||
670 | singleton($treeClass)->flushCache(); |
||
671 | |||
672 | $record = DataObject::get_by_id($treeClass, $id); |
||
673 | } |
||
674 | |||
675 | // Then, try getting a deleted record |
||
676 | if(!$record) { |
||
677 | $record = Versioned::get_latest_version($treeClass, $id); |
||
678 | } |
||
679 | |||
680 | // Don't open a page from a different locale |
||
681 | /** The record's Locale is saved in database in 2.4, and not related with Session, |
||
682 | * we should not check their locale matches the Translatable::get_current_locale, |
||
683 | * here as long as we all the HTTPRequest is init with right locale. |
||
684 | * This bit breaks the all FileIFrameField functions if the field is used in CMS |
||
685 | * and its relevent ajax calles, like loading the tree dropdown for TreeSelectorField. |
||
686 | */ |
||
687 | /* if($record && SiteTree::has_extension('Translatable') && $record->Locale && $record->Locale != Translatable::get_current_locale()) { |
||
688 | $record = null; |
||
689 | }*/ |
||
690 | |||
691 | // Set the reading mode back to what it was. |
||
692 | Versioned::set_reading_mode($currentStage); |
||
693 | |||
694 | return $record; |
||
695 | |||
696 | } else if(substr($id,0,3) == 'new') { |
||
697 | return $this->getNewItem($id); |
||
698 | } |
||
699 | } |
||
700 | |||
701 | /** |
||
702 | * @param int $id |
||
703 | * @param FieldList $fields |
||
704 | * @return Form |
||
705 | */ |
||
706 | public function getEditForm($id = null, $fields = null) { |
||
707 | if(!$id) $id = $this->currentPageID(); |
||
708 | $form = parent::getEditForm($id, $fields); |
||
709 | |||
710 | // TODO Duplicate record fetching (see parent implementation) |
||
711 | $record = $this->getRecord($id); |
||
712 | if($record && !$record->canView()) return Security::permissionFailure($this); |
||
713 | |||
714 | if(!$fields) $fields = $form->Fields(); |
||
715 | $actions = $form->Actions(); |
||
716 | |||
717 | if($record) { |
||
718 | $deletedFromStage = !$record->isOnDraft(); |
||
719 | |||
720 | $fields->push($idField = new HiddenField("ID", false, $id)); |
||
721 | // Necessary for different subsites |
||
722 | $fields->push($liveLinkField = new HiddenField("AbsoluteLink", false, $record->AbsoluteLink())); |
||
723 | $fields->push($liveLinkField = new HiddenField("LiveLink")); |
||
724 | $fields->push($stageLinkField = new HiddenField("StageLink")); |
||
725 | $fields->push(new HiddenField("TreeTitle", false, $record->TreeTitle)); |
||
726 | |||
727 | if($record->ID && is_numeric( $record->ID ) ) { |
||
728 | $liveLink = $record->getAbsoluteLiveLink(); |
||
729 | if($liveLink) $liveLinkField->setValue($liveLink); |
||
730 | if(!$deletedFromStage) { |
||
731 | $stageLink = Controller::join_links($record->AbsoluteLink(), '?stage=Stage'); |
||
732 | if($stageLink) $stageLinkField->setValue($stageLink); |
||
733 | } |
||
734 | } |
||
735 | |||
736 | // Added in-line to the form, but plucked into different view by LeftAndMain.Preview.js upon load |
||
737 | /** @skipUpgrade */ |
||
738 | if($record instanceof CMSPreviewable && !$fields->fieldByName('SilverStripeNavigator')) { |
||
739 | $navField = new LiteralField('SilverStripeNavigator', $this->getSilverStripeNavigator()); |
||
740 | $navField->setAllowHTML(true); |
||
741 | $fields->push($navField); |
||
742 | } |
||
743 | |||
744 | // getAllCMSActions can be used to completely redefine the action list |
||
745 | if($record->hasMethod('getAllCMSActions')) { |
||
746 | $actions = $record->getAllCMSActions(); |
||
747 | } else { |
||
748 | $actions = $record->getCMSActions(); |
||
749 | |||
750 | // Find and remove action menus that have no actions. |
||
751 | if ($actions && $actions->count()) { |
||
752 | /** @var TabSet $tabset */ |
||
753 | $tabset = $actions->fieldByName('ActionMenus'); |
||
754 | if ($tabset) { |
||
755 | foreach ($tabset->getChildren() as $tab) { |
||
756 | if (!$tab->getChildren()->count()) { |
||
757 | $tabset->removeByName($tab->getName()); |
||
758 | } |
||
759 | } |
||
760 | } |
||
761 | } |
||
762 | } |
||
763 | |||
764 | // Use <button> to allow full jQuery UI styling |
||
765 | $actionsFlattened = $actions->dataFields(); |
||
766 | if($actionsFlattened) { |
||
767 | /** @var FormAction $action */ |
||
768 | foreach($actionsFlattened as $action) { |
||
769 | $action->setUseButtonTag(true); |
||
770 | } |
||
771 | } |
||
772 | |||
773 | if($record->hasMethod('getCMSValidator')) { |
||
774 | $validator = $record->getCMSValidator(); |
||
775 | } else { |
||
776 | $validator = new RequiredFields(); |
||
777 | } |
||
778 | |||
779 | // TODO Can't merge $FormAttributes in template at the moment |
||
780 | $form->addExtraClass('center ' . $this->BaseCSSClasses()); |
||
781 | // Set validation exemptions for specific actions |
||
782 | $form->setValidationExemptActions(array('restore', 'revert', 'deletefromlive', 'delete', 'unpublish', 'rollback', 'doRollback')); |
||
783 | |||
784 | // Announce the capability so the frontend can decide whether to allow preview or not. |
||
785 | if ($record instanceof CMSPreviewable) { |
||
786 | $form->addExtraClass('cms-previewable'); |
||
787 | } |
||
788 | $form->addExtraClass('fill-height flexbox-area-grow'); |
||
789 | |||
790 | if(!$record->canEdit() || $deletedFromStage) { |
||
791 | $readonlyFields = $form->Fields()->makeReadonly(); |
||
792 | $form->setFields($readonlyFields); |
||
793 | } |
||
794 | |||
795 | $form->Fields()->setForm($form); |
||
796 | |||
797 | $this->extend('updateEditForm', $form); |
||
798 | return $form; |
||
799 | } else if($id) { |
||
800 | $form = Form::create( $this, "EditForm", new FieldList( |
||
801 | new LabelField('PageDoesntExistLabel',_t('CMSMain.PAGENOTEXISTS',"This page doesn't exist"))), new FieldList() |
||
802 | )->setHTMLID('Form_EditForm'); |
||
803 | return $form; |
||
804 | } |
||
805 | } |
||
806 | |||
807 | /** |
||
808 | * @param HTTPRequest $request |
||
809 | * @return string HTML |
||
810 | */ |
||
811 | public function treeview($request) { |
||
812 | return $this->getResponseNegotiator()->respond($request); |
||
813 | } |
||
814 | |||
815 | /** |
||
816 | * @param HTTPRequest $request |
||
817 | * @return string HTML |
||
818 | */ |
||
819 | public function listview($request) { |
||
820 | return $this->getResponseNegotiator()->respond($request); |
||
821 | } |
||
822 | |||
823 | /** |
||
824 | * @return string |
||
825 | */ |
||
826 | public function ViewState() { |
||
827 | $mode = $this->getRequest()->requestVar('view') |
||
828 | ?: $this->getRequest()->param('Action'); |
||
829 | switch($mode) { |
||
830 | case 'listview': |
||
831 | case 'treeview': |
||
832 | return $mode; |
||
833 | default: |
||
834 | return 'treeview'; |
||
835 | } |
||
836 | } |
||
837 | |||
838 | /** |
||
839 | * Callback to request the list of page types allowed under a given page instance. |
||
840 | * Provides a slower but more precise response over SiteTreeHints |
||
841 | * |
||
842 | * @param HTTPRequest $request |
||
843 | * @return HTTPResponse |
||
844 | */ |
||
845 | public function childfilter($request) { |
||
846 | // Check valid parent specified |
||
847 | $parentID = $request->requestVar('ParentID'); |
||
848 | $parent = SiteTree::get()->byID($parentID); |
||
849 | if(!$parent || !$parent->exists()) return $this->httpError(404); |
||
850 | |||
851 | // Build hints specific to this class |
||
852 | // Identify disallows and set globals |
||
853 | $classes = SiteTree::page_type_classes(); |
||
854 | $disallowedChildren = array(); |
||
855 | foreach($classes as $class) { |
||
856 | $obj = singleton($class); |
||
857 | if($obj instanceof HiddenClass) continue; |
||
858 | |||
859 | if(!$obj->canCreate(null, array('Parent' => $parent))) { |
||
860 | $disallowedChildren[] = $class; |
||
861 | } |
||
862 | } |
||
863 | |||
864 | $this->extend('updateChildFilter', $disallowedChildren, $parentID); |
||
865 | return $this |
||
866 | ->getResponse() |
||
867 | ->addHeader('Content-Type', 'application/json; charset=utf-8') |
||
868 | ->setBody(Convert::raw2json($disallowedChildren)); |
||
869 | } |
||
870 | |||
871 | /** |
||
872 | * Safely reconstruct a selected filter from a given set of query parameters |
||
873 | * |
||
874 | * @param array $params Query parameters to use |
||
875 | * @return CMSSiteTreeFilter The filter class, or null if none present |
||
876 | * @throws InvalidArgumentException if invalid filter class is passed. |
||
877 | */ |
||
878 | protected function getQueryFilter($params) { |
||
879 | if(empty($params['FilterClass'])) return null; |
||
880 | $filterClass = $params['FilterClass']; |
||
881 | if(!is_subclass_of($filterClass, 'SilverStripe\\CMS\\Controllers\\CMSSiteTreeFilter')) { |
||
882 | throw new InvalidArgumentException("Invalid filter class passed: {$filterClass}"); |
||
883 | } |
||
884 | return $filterClass::create($params); |
||
885 | } |
||
886 | |||
887 | /** |
||
888 | * Returns the pages meet a certain criteria as {@see CMSSiteTreeFilter} or the subpages of a parent page |
||
889 | * defaulting to no filter and show all pages in first level. |
||
890 | * Doubles as search results, if any search parameters are set through {@link SearchForm()}. |
||
891 | * |
||
892 | * @param array $params Search filter criteria |
||
893 | * @param int $parentID Optional parent node to filter on (can't be combined with other search criteria) |
||
894 | * @return SS_List |
||
895 | * @throws InvalidArgumentException if invalid filter class is passed. |
||
896 | */ |
||
897 | public function getList($params = array(), $parentID = 0) { |
||
898 | if($filter = $this->getQueryFilter($params)) { |
||
899 | return $filter->getFilteredPages(); |
||
900 | } else { |
||
901 | $list = DataList::create($this->stat('tree_class')); |
||
902 | $parentID = is_numeric($parentID) ? $parentID : 0; |
||
903 | return $list->filter("ParentID", $parentID); |
||
904 | } |
||
905 | } |
||
906 | |||
907 | /** |
||
908 | * @return Form |
||
909 | */ |
||
910 | public function ListViewForm() { |
||
911 | $params = $this->getRequest()->requestVar('q'); |
||
912 | $list = $this->getList($params, $parentID = $this->getRequest()->requestVar('ParentID')); |
||
913 | $gridFieldConfig = GridFieldConfig::create()->addComponents( |
||
914 | new GridFieldSortableHeader(), |
||
915 | new GridFieldDataColumns(), |
||
916 | new GridFieldPaginator(self::config()->page_length) |
||
917 | ); |
||
918 | if($parentID){ |
||
919 | $linkSpec = $this->Link(); |
||
920 | $linkSpec = $linkSpec . (strstr($linkSpec, '?') ? '&' : '?') . 'ParentID=%d&view=listview'; |
||
921 | $gridFieldConfig->addComponent( |
||
922 | GridFieldLevelup::create($parentID) |
||
923 | ->setLinkSpec($linkSpec) |
||
924 | ->setAttributes(array('data-pjax' => 'ListViewForm,Breadcrumbs')) |
||
925 | ); |
||
926 | } |
||
927 | $gridField = new GridField('Page','Pages', $list, $gridFieldConfig); |
||
928 | /** @var GridFieldDataColumns $columns */ |
||
929 | $columns = $gridField->getConfig()->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldDataColumns'); |
||
930 | |||
931 | // Don't allow navigating into children nodes on filtered lists |
||
932 | $fields = array( |
||
933 | 'getTreeTitle' => _t('SiteTree.PAGETITLE', 'Page Title'), |
||
934 | 'singular_name' => _t('SiteTree.PAGETYPE'), |
||
935 | 'LastEdited' => _t('SiteTree.LASTUPDATED', 'Last Updated'), |
||
936 | ); |
||
937 | /** @var GridFieldSortableHeader $sortableHeader */ |
||
938 | $sortableHeader = $gridField->getConfig()->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldSortableHeader'); |
||
939 | $sortableHeader->setFieldSorting(array('getTreeTitle' => 'Title')); |
||
940 | $gridField->getState()->ParentID = $parentID; |
||
941 | |||
942 | if(!$params) { |
||
943 | $fields = array_merge(array('listChildrenLink' => ''), $fields); |
||
944 | } |
||
945 | |||
946 | $columns->setDisplayFields($fields); |
||
947 | $columns->setFieldCasting(array( |
||
948 | 'Created' => 'DBDatetime->Ago', |
||
949 | 'LastEdited' => 'DBDatetime->FormatFromSettings', |
||
950 | 'getTreeTitle' => 'HTMLFragment' |
||
951 | )); |
||
952 | |||
953 | $controller = $this; |
||
954 | $columns->setFieldFormatting(array( |
||
955 | 'listChildrenLink' => function($value, &$item) use($controller) { |
||
956 | /** @var SiteTree $item */ |
||
957 | $num = $item ? $item->numChildren() : null; |
||
958 | if($num) { |
||
959 | return sprintf( |
||
960 | '<a class="btn btn-secondary btn--no-text btn--icon-large font-icon-right-dir cms-panel-link list-children-link" data-pjax-target="ListViewForm,Breadcrumbs" href="%s"><span class="sr-only">%s child pages</span></a>', |
||
961 | Controller::join_links( |
||
962 | $controller->Link(), |
||
963 | sprintf("?ParentID=%d&view=listview", (int)$item->ID) |
||
964 | ), |
||
965 | $num |
||
966 | ); |
||
967 | } |
||
968 | }, |
||
969 | 'getTreeTitle' => function($value, &$item) use($controller) { |
||
970 | return sprintf( |
||
971 | '<a class="action-detail" href="%s">%s</a>', |
||
972 | Controller::join_links( |
||
973 | CMSPageEditController::singleton()->Link('show'), |
||
974 | (int)$item->ID |
||
975 | ), |
||
976 | $item->TreeTitle // returns HTML, does its own escaping |
||
977 | ); |
||
978 | } |
||
979 | )); |
||
980 | |||
981 | $negotiator = $this->getResponseNegotiator(); |
||
982 | $listview = Form::create( |
||
983 | $this, |
||
984 | 'ListViewForm', |
||
985 | new FieldList($gridField), |
||
986 | new FieldList() |
||
987 | )->setHTMLID('Form_ListViewForm'); |
||
988 | $listview->setAttribute('data-pjax-fragment', 'ListViewForm'); |
||
989 | View Code Duplication | $listview->setValidationResponseCallback(function(ValidationResult $errors) use ($negotiator, $listview) { |
|
990 | $request = $this->getRequest(); |
||
991 | if($request->isAjax() && $negotiator) { |
||
992 | $result = $listview->forTemplate(); |
||
993 | return $negotiator->respond($request, array( |
||
994 | 'CurrentForm' => function() use($result) { |
||
995 | return $result; |
||
996 | } |
||
997 | )); |
||
998 | } |
||
999 | }); |
||
1000 | |||
1001 | $this->extend('updateListView', $listview); |
||
1002 | |||
1003 | $listview->disableSecurityToken(); |
||
1004 | return $listview; |
||
1005 | } |
||
1006 | |||
1007 | public function currentPageID() { |
||
1014 | |||
1015 | //------------------------------------------------------------------------------------------// |
||
1016 | // Data saving handlers |
||
1017 | |||
1018 | /** |
||
1019 | * Save and Publish page handler |
||
1020 | * |
||
1021 | * @param array $data |
||
1022 | * @param Form $form |
||
1023 | * @return HTTPResponse |
||
1024 | * @throws HTTPResponse_Exception |
||
1025 | */ |
||
1026 | public function save($data, $form) { |
||
1092 | |||
1093 | /** |
||
1094 | * @uses LeftAndMainExtension->augmentNewSiteTreeItem() |
||
1095 | * |
||
1096 | * @param int|string $id |
||
1097 | * @param bool $setID |
||
1098 | * @return mixed|DataObject |
||
1099 | * @throws HTTPResponse_Exception |
||
1100 | */ |
||
1101 | public function getNewItem($id, $setID = true) { |
||
1148 | |||
1149 | /** |
||
1150 | * Actually perform the publication step |
||
1151 | * |
||
1152 | * @param Versioned|DataObject $record |
||
1153 | * @return mixed |
||
1154 | */ |
||
1155 | public function performPublish($record) { |
||
1162 | |||
1163 | /** |
||
1164 | * Reverts a page by publishing it to live. |
||
1165 | * Use {@link restorepage()} if you want to restore a page |
||
1166 | * which was deleted from draft without publishing. |
||
1167 | * |
||
1168 | * @uses SiteTree->doRevertToLive() |
||
1169 | * |
||
1170 | * @param array $data |
||
1171 | * @param Form $form |
||
1172 | * @return HTTPResponse |
||
1173 | * @throws HTTPResponse_Exception |
||
1174 | */ |
||
1175 | public function revert($data, $form) { |
||
1214 | |||
1215 | /** |
||
1216 | * Delete the current page from draft stage. |
||
1217 | * |
||
1218 | * @see deletefromlive() |
||
1219 | * |
||
1220 | * @param array $data |
||
1221 | * @param Form $form |
||
1222 | * @return HTTPResponse |
||
1223 | * @throws HTTPResponse_Exception |
||
1224 | */ |
||
1225 | View Code Duplication | public function delete($data, $form) { |
|
1246 | |||
1247 | /** |
||
1248 | * Delete this page from both live and stage |
||
1249 | * |
||
1250 | * @param array $data |
||
1251 | * @param Form $form |
||
1252 | * @return HTTPResponse |
||
1253 | * @throws HTTPResponse_Exception |
||
1254 | */ |
||
1255 | View Code Duplication | public function archive($data, $form) { |
|
1277 | |||
1278 | public function publish($data, $form) { |
||
1283 | |||
1284 | public function unpublish($data, $form) { |
||
1305 | |||
1306 | /** |
||
1307 | * @return HTTPResponse |
||
1308 | */ |
||
1309 | public function rollback() { |
||
1315 | |||
1316 | /** |
||
1317 | * Rolls a site back to a given version ID |
||
1318 | * |
||
1319 | * @param array $data |
||
1320 | * @param Form $form |
||
1321 | * @return HTTPResponse |
||
1322 | */ |
||
1323 | public function doRollback($data, $form) { |
||
1361 | |||
1362 | /** |
||
1363 | * Batch Actions Handler |
||
1364 | */ |
||
1365 | public function batchactions() { |
||
1368 | |||
1369 | public function BatchActionParameters() { |
||
1390 | /** |
||
1391 | * Returns a list of batch actions |
||
1392 | */ |
||
1393 | public function BatchActionList() { |
||
1396 | |||
1397 | public function publishall($request) { |
||
1398 | if(!Permission::check('ADMIN')) return Security::permissionFailure($this); |
||
1399 | |||
1400 | increase_time_limit_to(); |
||
1401 | increase_memory_limit_to(); |
||
1402 | |||
1403 | $response = ""; |
||
1404 | |||
1405 | if(isset($this->requestParams['confirm'])) { |
||
1406 | // Protect against CSRF on destructive action |
||
1407 | if(!SecurityToken::inst()->checkRequest($request)) return $this->httpError(400); |
||
1408 | |||
1409 | $start = 0; |
||
1410 | $pages = SiteTree::get()->limit("$start,30"); |
||
1411 | $count = 0; |
||
1412 | while($pages) { |
||
1413 | /** @var SiteTree $page */ |
||
1414 | foreach($pages as $page) { |
||
1415 | if($page && !$page->canPublish()) { |
||
1416 | return Security::permissionFailure($this); |
||
1417 | } |
||
1418 | |||
1419 | $page->publishRecursive(); |
||
1420 | $page->destroy(); |
||
1421 | unset($page); |
||
1422 | $count++; |
||
1423 | $response .= "<li>$count</li>"; |
||
1424 | } |
||
1425 | if($pages->count() > 29) { |
||
1426 | $start += 30; |
||
1427 | $pages = SiteTree::get()->limit("$start,30"); |
||
1428 | } else { |
||
1429 | break; |
||
1430 | } |
||
1431 | } |
||
1432 | $response .= _t('CMSMain.PUBPAGES',"Done: Published {count} pages", array('count' => $count)); |
||
1457 | |||
1458 | /** |
||
1459 | * Restore a completely deleted page from the SiteTree_versions table. |
||
1460 | * |
||
1461 | * @param array $data |
||
1462 | * @param Form $form |
||
1463 | * @return HTTPResponse |
||
1464 | */ |
||
1465 | public function restore($data, $form) { |
||
1490 | |||
1491 | public function duplicate($request) { |
||
1529 | |||
1530 | public function duplicatewithchildren($request) { |
||
1562 | |||
1563 | public function providePermissions() { |
||
1577 | |||
1578 | } |
||
1579 |