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 |
||
75 | class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionProvider { |
||
76 | |||
77 | private static $url_segment = 'pages'; |
||
|
|||
78 | |||
79 | private static $url_rule = '/$Action/$ID/$OtherID'; |
||
80 | |||
81 | // Maintain a lower priority than other administration sections |
||
82 | // so that Director does not think they are actions of CMSMain |
||
83 | private static $url_priority = 39; |
||
84 | |||
85 | private static $menu_title = 'Edit Page'; |
||
86 | |||
87 | private static $menu_priority = 10; |
||
88 | |||
89 | private static $tree_class = "SilverStripe\\CMS\\Model\\SiteTree"; |
||
90 | |||
91 | private static $subitem_class = "SilverStripe\\Security\\Member"; |
||
92 | |||
93 | private static $session_namespace = 'SilverStripe\\CMS\\Controllers\\CMSMain'; |
||
94 | |||
95 | private static $required_permission_codes = 'CMS_ACCESS_CMSMain'; |
||
96 | |||
97 | /** |
||
98 | * Amount of results showing on a single page. |
||
99 | * |
||
100 | * @config |
||
101 | * @var int |
||
102 | */ |
||
103 | private static $page_length = 15; |
||
104 | |||
105 | private static $allowed_actions = array( |
||
106 | 'deleteitems', |
||
107 | 'DeleteItemsForm', |
||
108 | 'dialog', |
||
109 | 'duplicate', |
||
110 | 'duplicatewithchildren', |
||
111 | 'publishall', |
||
112 | 'publishitems', |
||
113 | 'PublishItemsForm', |
||
114 | 'submit', |
||
115 | 'EditForm', |
||
116 | 'SearchForm', |
||
117 | 'SiteTreeAsUL', |
||
118 | 'getshowdeletedsubtree', |
||
119 | 'batchactions', |
||
120 | 'treeview', |
||
121 | 'listview', |
||
122 | 'ListViewForm', |
||
123 | 'childfilter', |
||
124 | ); |
||
125 | |||
126 | private static $casting = array( |
||
127 | 'TreeIsFiltered' => 'Boolean', |
||
128 | 'AddForm' => 'HTMLFragment', |
||
129 | 'LinkPages' => 'Text', |
||
130 | 'Link' => 'Text', |
||
131 | 'ListViewForm' => 'HTMLFragment', |
||
132 | 'ExtraTreeTools' => 'HTMLFragment', |
||
133 | 'SiteTreeHints' => 'HTMLFragment', |
||
134 | 'SecurityID' => 'Text', |
||
135 | 'SiteTreeAsUL' => 'HTMLFragment', |
||
136 | ); |
||
137 | |||
138 | public function init() { |
||
139 | // set reading lang |
||
140 | if(SiteTree::has_extension('Translatable') && !$this->getRequest()->isAjax()) { |
||
141 | Translatable::choose_site_locale(array_keys(Translatable::get_existing_content_languages('SilverStripe\\CMS\\Model\\SiteTree'))); |
||
142 | } |
||
143 | |||
144 | parent::init(); |
||
145 | |||
146 | Requirements::javascript(CMS_DIR . '/client/dist/js/bundle.js'); |
||
147 | Requirements::javascript(CMS_DIR . '/client/dist/js/SilverStripeNavigator.js'); |
||
148 | Requirements::css(CMS_DIR . '/client/dist/styles/bundle.css'); |
||
149 | Requirements::customCSS($this->generatePageIconsCss()); |
||
150 | Requirements::add_i18n_javascript(CMS_DIR . '/client/lang', false, true); |
||
151 | |||
152 | CMSBatchActionHandler::register('restore', CMSBatchAction_Restore::class); |
||
153 | CMSBatchActionHandler::register('delete', CMSBatchAction_Delete::class); |
||
154 | CMSBatchActionHandler::register('unpublish', CMSBatchAction_Unpublish::class); |
||
155 | CMSBatchActionHandler::register('publish', CMSBatchAction_Publish::class); |
||
156 | } |
||
157 | |||
158 | public function index($request) { |
||
159 | // In case we're not showing a specific record, explicitly remove any session state, |
||
160 | // to avoid it being highlighted in the tree, and causing an edit form to show. |
||
161 | if(!$request->param('Action')) { |
||
162 | $this->setCurrentPageID(null); |
||
163 | } |
||
164 | |||
165 | return parent::index($request); |
||
166 | } |
||
167 | |||
168 | public function getResponseNegotiator() { |
||
169 | $negotiator = parent::getResponseNegotiator(); |
||
170 | $controller = $this; |
||
171 | $negotiator->setCallback('ListViewForm', function() use($controller) { |
||
172 | return $controller->ListViewForm()->forTemplate(); |
||
173 | }); |
||
174 | return $negotiator; |
||
175 | } |
||
176 | |||
177 | /** |
||
178 | * If this is set to true, the "switchView" context in the |
||
179 | * template is shown, with links to the staging and publish site. |
||
180 | * |
||
181 | * @return boolean |
||
182 | */ |
||
183 | public function ShowSwitchView() { |
||
184 | return true; |
||
185 | } |
||
186 | |||
187 | /** |
||
188 | * Overloads the LeftAndMain::ShowView. Allows to pass a page as a parameter, so we are able |
||
189 | * to switch view also for archived versions. |
||
190 | * |
||
191 | * @param SiteTree $page |
||
192 | * @return array |
||
193 | */ |
||
194 | public function SwitchView($page = null) { |
||
195 | if(!$page) { |
||
196 | $page = $this->currentPage(); |
||
197 | } |
||
198 | |||
199 | if($page) { |
||
200 | $nav = SilverStripeNavigator::get_for_record($page); |
||
201 | return $nav['items']; |
||
202 | } |
||
203 | } |
||
204 | |||
205 | //------------------------------------------------------------------------------------------// |
||
206 | // Main controllers |
||
207 | |||
208 | //------------------------------------------------------------------------------------------// |
||
209 | // Main UI components |
||
210 | |||
211 | /** |
||
212 | * Override {@link LeftAndMain} Link to allow blank URL segment for CMSMain. |
||
213 | * |
||
214 | * @param string|null $action Action to link to. |
||
215 | * @return string |
||
216 | */ |
||
217 | public function Link($action = null) { |
||
218 | $link = Controller::join_links( |
||
219 | AdminRootController::admin_url(), |
||
220 | $this->stat('url_segment'), // in case we want to change the segment |
||
221 | '/', // trailing slash needed if $action is null! |
||
222 | "$action" |
||
223 | ); |
||
224 | $this->extend('updateLink', $link); |
||
225 | return $link; |
||
226 | } |
||
227 | |||
228 | public function LinkPages() { |
||
229 | return CMSPagesController::singleton()->Link(); |
||
230 | } |
||
231 | |||
232 | public function LinkPagesWithSearch() { |
||
233 | return $this->LinkWithSearch($this->LinkPages()); |
||
234 | } |
||
235 | |||
236 | public function LinkTreeView() { |
||
237 | return $this->LinkWithSearch($this->Link('treeview')); |
||
238 | } |
||
239 | |||
240 | public function LinkListView() { |
||
241 | return $this->LinkWithSearch($this->Link('listview')); |
||
242 | } |
||
243 | |||
244 | public function LinkGalleryView() { |
||
245 | return $this->LinkWithSearch($this->Link('galleryview')); |
||
246 | } |
||
247 | |||
248 | View Code Duplication | public function LinkPageEdit($id = null) { |
|
249 | if(!$id) { |
||
250 | $id = $this->currentPageID(); |
||
251 | } |
||
252 | return $this->LinkWithSearch( |
||
253 | Controller::join_links(CMSPageEditController::singleton()->Link('show'), $id) |
||
254 | ); |
||
255 | } |
||
256 | |||
257 | View Code Duplication | public function LinkPageSettings() { |
|
258 | if($id = $this->currentPageID()) { |
||
259 | return $this->LinkWithSearch( |
||
260 | Controller::join_links(CMSPageSettingsController::singleton()->Link('show'), $id) |
||
261 | ); |
||
262 | } else { |
||
263 | return null; |
||
264 | } |
||
265 | } |
||
266 | |||
267 | View Code Duplication | public function LinkPageHistory() { |
|
268 | if($id = $this->currentPageID()) { |
||
269 | return $this->LinkWithSearch( |
||
270 | Controller::join_links(CMSPageHistoryController::singleton()->Link('show'), $id) |
||
271 | ); |
||
272 | } else { |
||
273 | return null; |
||
274 | } |
||
275 | } |
||
276 | |||
277 | public function LinkWithSearch($link) { |
||
278 | // Whitelist to avoid side effects |
||
279 | $params = array( |
||
280 | 'q' => (array)$this->getRequest()->getVar('q'), |
||
281 | 'ParentID' => $this->getRequest()->getVar('ParentID') |
||
282 | ); |
||
283 | $link = Controller::join_links( |
||
284 | $link, |
||
285 | array_filter(array_values($params)) ? '?' . http_build_query($params) : null |
||
286 | ); |
||
287 | $this->extend('updateLinkWithSearch', $link); |
||
288 | return $link; |
||
289 | } |
||
290 | |||
291 | public function LinkPageAdd($extra = null, $placeholders = null) { |
||
292 | $link = CMSPageAddController::singleton()->Link(); |
||
293 | $this->extend('updateLinkPageAdd', $link); |
||
294 | |||
295 | if($extra) { |
||
296 | $link = Controller::join_links ($link, $extra); |
||
297 | } |
||
298 | |||
299 | if($placeholders) { |
||
300 | $link .= (strpos($link, '?') === false ? "?$placeholders" : "&$placeholders"); |
||
301 | } |
||
302 | |||
303 | return $link; |
||
304 | } |
||
305 | |||
306 | /** |
||
307 | * @return string |
||
308 | */ |
||
309 | public function LinkPreview() { |
||
310 | $record = $this->getRecord($this->currentPageID()); |
||
311 | $baseLink = Director::absoluteBaseURL(); |
||
312 | if ($record && $record instanceof Page) { |
||
313 | // if we are an external redirector don't show a link |
||
314 | if ($record instanceof RedirectorPage && $record->RedirectionType == 'External') { |
||
315 | $baseLink = false; |
||
316 | } |
||
317 | else { |
||
318 | $baseLink = $record->Link('?stage=Stage'); |
||
319 | } |
||
320 | } |
||
321 | return $baseLink; |
||
322 | } |
||
323 | |||
324 | /** |
||
325 | * Return the entire site tree as a nested set of ULs |
||
326 | */ |
||
327 | public function SiteTreeAsUL() { |
||
328 | // Pre-cache sitetree version numbers for querying efficiency |
||
329 | Versioned::prepopulate_versionnumber_cache("SilverStripe\\CMS\\Model\\SiteTree", "Stage"); |
||
330 | Versioned::prepopulate_versionnumber_cache("SilverStripe\\CMS\\Model\\SiteTree", "Live"); |
||
331 | $html = $this->getSiteTreeFor($this->stat('tree_class')); |
||
332 | |||
333 | $this->extend('updateSiteTreeAsUL', $html); |
||
334 | |||
335 | return $html; |
||
336 | } |
||
337 | |||
338 | /** |
||
339 | * @return boolean |
||
340 | */ |
||
341 | public function TreeIsFiltered() { |
||
342 | $query = $this->getRequest()->getVar('q'); |
||
343 | |||
344 | if (!$query || (count($query) === 1 && isset($query['FilterClass']) && $query['FilterClass'] === 'SilverStripe\\CMS\\Controllers\\CMSSiteTreeFilter_Search')) { |
||
345 | return false; |
||
346 | } |
||
347 | |||
348 | return true; |
||
349 | } |
||
350 | |||
351 | public function ExtraTreeTools() { |
||
352 | $html = ''; |
||
353 | $this->extend('updateExtraTreeTools', $html); |
||
354 | return $html; |
||
355 | } |
||
356 | |||
357 | /** |
||
358 | * Returns a Form for page searching for use in templates. |
||
359 | * |
||
360 | * Can be modified from a decorator by a 'updateSearchForm' method |
||
361 | * |
||
362 | * @return Form |
||
363 | */ |
||
364 | public function SearchForm() { |
||
365 | // Create the fields |
||
366 | $content = new TextField('q[Term]', _t('CMSSearch.FILTERLABELTEXT', 'Search')); |
||
367 | $dateFrom = new DateField( |
||
368 | 'q[LastEditedFrom]', |
||
369 | _t('CMSSearch.FILTERDATEFROM', 'From') |
||
370 | ); |
||
371 | $dateFrom->setConfig('showcalendar', true); |
||
372 | $dateTo = new DateField( |
||
373 | 'q[LastEditedTo]', |
||
374 | _t('CMSSearch.FILTERDATETO', 'To') |
||
375 | ); |
||
376 | $dateTo->setConfig('showcalendar', true); |
||
377 | $pageFilter = new DropdownField( |
||
378 | 'q[FilterClass]', |
||
379 | _t('CMSMain.PAGES', 'Page status'), |
||
380 | CMSSiteTreeFilter::get_all_filters() |
||
381 | ); |
||
382 | $pageClasses = new DropdownField( |
||
383 | 'q[ClassName]', |
||
384 | _t('CMSMain.PAGETYPEOPT', 'Page type', 'Dropdown for limiting search to a page type'), |
||
385 | $this->getPageTypes() |
||
386 | ); |
||
387 | $pageClasses->setEmptyString(_t('CMSMain.PAGETYPEANYOPT','Any')); |
||
388 | |||
389 | // Group the Datefields |
||
390 | $dateGroup = new FieldGroup( |
||
391 | $dateFrom, |
||
392 | $dateTo |
||
393 | ); |
||
394 | $dateGroup->setTitle(_t('CMSSearch.PAGEFILTERDATEHEADING', 'Last edited')); |
||
395 | |||
396 | // Create the Field list |
||
397 | $fields = new FieldList( |
||
398 | $content, |
||
399 | $pageFilter, |
||
400 | $pageClasses, |
||
401 | $dateGroup |
||
402 | ); |
||
403 | |||
404 | // Create the Search and Reset action |
||
405 | $actions = new FieldList( |
||
406 | FormAction::create('doSearch', _t('CMSMain_left_ss.APPLY_FILTER', 'Search')) |
||
407 | ->addExtraClass('ss-ui-action-constructive'), |
||
408 | ResetFormAction::create('clear', _t('CMSMain_left_ss.CLEAR_FILTER', 'Clear')) |
||
409 | ); |
||
410 | |||
411 | // Use <button> to allow full jQuery UI styling on the all of the Actions |
||
412 | /** @var FormAction $action */ |
||
413 | foreach($actions->dataFields() as $action) { |
||
414 | /** @var FormAction $action */ |
||
415 | $action->setUseButtonTag(true); |
||
416 | } |
||
417 | |||
418 | // Create the form |
||
419 | /** @skipUpgrade */ |
||
420 | $form = Form::create($this, 'SearchForm', $fields, $actions) |
||
421 | ->addExtraClass('cms-search-form') |
||
422 | ->setFormMethod('GET') |
||
423 | ->setFormAction($this->Link()) |
||
424 | ->disableSecurityToken() |
||
425 | ->unsetValidator(); |
||
426 | |||
427 | // Load the form with previously sent search data |
||
428 | $form->loadDataFrom($this->getRequest()->getVars()); |
||
429 | |||
430 | // Allow decorators to modify the form |
||
431 | $this->extend('updateSearchForm', $form); |
||
432 | |||
433 | return $form; |
||
434 | } |
||
435 | |||
436 | /** |
||
437 | * Returns a sorted array suitable for a dropdown with pagetypes and their translated name |
||
438 | * |
||
439 | * @return array |
||
440 | */ |
||
441 | protected function getPageTypes() { |
||
442 | $pageTypes = array(); |
||
443 | foreach(SiteTree::page_type_classes() as $pageTypeClass) { |
||
444 | $pageTypes[$pageTypeClass] = SiteTree::singleton($pageTypeClass)->i18n_singular_name(); |
||
445 | } |
||
446 | asort($pageTypes); |
||
447 | return $pageTypes; |
||
448 | } |
||
449 | |||
450 | public function doSearch($data, $form) { |
||
451 | return $this->getsubtree($this->getRequest()); |
||
452 | } |
||
453 | |||
454 | /** |
||
455 | * @param bool $unlinked |
||
456 | * @return ArrayList |
||
457 | */ |
||
458 | public function Breadcrumbs($unlinked = false) { |
||
459 | $items = parent::Breadcrumbs($unlinked); |
||
460 | |||
461 | if($items->count() > 1) { |
||
462 | // Specific to the SiteTree admin section, we never show the cms section and current |
||
463 | // page in the same breadcrumbs block. |
||
464 | $items->shift(); |
||
465 | } |
||
466 | |||
467 | return $items; |
||
468 | } |
||
469 | |||
470 | /** |
||
471 | * Create serialized JSON string with site tree hints data to be injected into |
||
472 | * 'data-hints' attribute of root node of jsTree. |
||
473 | * |
||
474 | * @return string Serialized JSON |
||
475 | */ |
||
476 | public function SiteTreeHints() { |
||
477 | $classes = SiteTree::page_type_classes(); |
||
478 | |||
479 | $cacheCanCreate = array(); |
||
480 | foreach($classes as $class) $cacheCanCreate[$class] = singleton($class)->canCreate(); |
||
481 | |||
482 | // Generate basic cache key. Too complex to encompass all variations |
||
483 | $cache = Cache::factory('CMSMain_SiteTreeHints'); |
||
484 | $cacheKey = md5(implode('_', array(Member::currentUserID(), implode(',', $cacheCanCreate), implode(',', $classes)))); |
||
485 | if($this->getRequest()->getVar('flush')) { |
||
486 | $cache->clean(Zend_Cache::CLEANING_MODE_ALL); |
||
487 | } |
||
488 | $json = $cache->load($cacheKey); |
||
489 | if(!$json) { |
||
490 | $def['Root'] = array(); |
||
491 | $def['Root']['disallowedChildren'] = array(); |
||
492 | |||
493 | // Contains all possible classes to support UI controls listing them all, |
||
494 | // such as the "add page here" context menu. |
||
495 | $def['All'] = array(); |
||
496 | |||
497 | // Identify disallows and set globals |
||
498 | foreach($classes as $class) { |
||
499 | $obj = singleton($class); |
||
500 | if($obj instanceof HiddenClass) continue; |
||
501 | |||
502 | // Name item |
||
503 | $def['All'][$class] = array( |
||
504 | 'title' => $obj->i18n_singular_name() |
||
505 | ); |
||
506 | |||
507 | // Check if can be created at the root |
||
508 | $needsPerm = $obj->stat('need_permission'); |
||
509 | if( |
||
510 | !$obj->stat('can_be_root') |
||
511 | || (!array_key_exists($class, $cacheCanCreate) || !$cacheCanCreate[$class]) |
||
512 | || ($needsPerm && !$this->can($needsPerm)) |
||
513 | ) { |
||
514 | $def['Root']['disallowedChildren'][] = $class; |
||
515 | } |
||
516 | |||
517 | // Hint data specific to the class |
||
518 | $def[$class] = array(); |
||
519 | |||
520 | $defaultChild = $obj->defaultChild(); |
||
521 | if($defaultChild !== 'Page' && $defaultChild !== null) { |
||
522 | $def[$class]['defaultChild'] = $defaultChild; |
||
523 | } |
||
524 | |||
525 | $defaultParent = $obj->defaultParent(); |
||
526 | if ($defaultParent !== 1 && $defaultParent !== null) { |
||
527 | $def[$class]['defaultParent'] = $defaultParent; |
||
528 | } |
||
529 | } |
||
530 | |||
531 | $this->extend('updateSiteTreeHints', $def); |
||
532 | |||
533 | $json = Convert::raw2json($def); |
||
534 | $cache->save($json, $cacheKey); |
||
535 | } |
||
536 | return $json; |
||
537 | } |
||
538 | |||
539 | /** |
||
540 | * Populates an array of classes in the CMS |
||
541 | * which allows the user to change the page type. |
||
542 | * |
||
543 | * @return SS_List |
||
544 | */ |
||
545 | public function PageTypes() { |
||
546 | $classes = SiteTree::page_type_classes(); |
||
547 | |||
548 | $result = new ArrayList(); |
||
549 | |||
550 | foreach($classes as $class) { |
||
551 | $instance = singleton($class); |
||
552 | |||
553 | if($instance instanceof HiddenClass) { |
||
554 | continue; |
||
555 | } |
||
556 | |||
557 | // skip this type if it is restricted |
||
558 | if($instance->stat('need_permission') && !$this->can(singleton($class)->stat('need_permission'))) { |
||
559 | continue; |
||
560 | } |
||
561 | |||
562 | $addAction = $instance->i18n_singular_name(); |
||
563 | |||
564 | // Get description (convert 'Page' to 'SiteTree' for correct localization lookups) |
||
565 | $i18nClass = ($class == 'Page') ? 'SilverStripe\\CMS\\Model\\SiteTree' : $class; |
||
566 | $description = _t($i18nClass . '.DESCRIPTION'); |
||
567 | |||
568 | if(!$description) { |
||
569 | $description = $instance->uninherited('description'); |
||
570 | } |
||
571 | |||
572 | if($class == 'Page' && !$description) { |
||
573 | $description = SiteTree::singleton()->uninherited('description'); |
||
574 | } |
||
575 | |||
576 | $result->push(new ArrayData(array( |
||
577 | 'ClassName' => $class, |
||
578 | 'AddAction' => $addAction, |
||
579 | 'Description' => $description, |
||
580 | // TODO Sprite support |
||
581 | 'IconURL' => $instance->stat('icon'), |
||
582 | 'Title' => singleton($class)->i18n_singular_name(), |
||
583 | ))); |
||
584 | } |
||
585 | |||
586 | $result = $result->sort('AddAction'); |
||
587 | |||
588 | return $result; |
||
589 | } |
||
590 | |||
591 | /** |
||
592 | * Get a database record to be managed by the CMS. |
||
593 | * |
||
594 | * @param int $id Record ID |
||
595 | * @param int $versionID optional Version id of the given record |
||
596 | * @return SiteTree |
||
597 | */ |
||
598 | public function getRecord($id, $versionID = null) { |
||
599 | $treeClass = $this->stat('tree_class'); |
||
600 | |||
601 | if($id instanceof $treeClass) { |
||
602 | return $id; |
||
603 | } |
||
604 | else if($id && is_numeric($id)) { |
||
605 | $currentStage = Versioned::get_reading_mode(); |
||
606 | |||
607 | if($this->getRequest()->getVar('Version')) { |
||
608 | $versionID = (int) $this->getRequest()->getVar('Version'); |
||
609 | } |
||
610 | |||
611 | if($versionID) { |
||
612 | $record = Versioned::get_version($treeClass, $id, $versionID); |
||
613 | } else { |
||
614 | $record = DataObject::get_by_id($treeClass, $id); |
||
615 | } |
||
616 | |||
617 | // Then, try getting a record from the live site |
||
618 | if(!$record) { |
||
619 | // $record = Versioned::get_one_by_stage($treeClass, "Live", "\"$treeClass\".\"ID\" = $id"); |
||
620 | Versioned::set_stage(Versioned::LIVE); |
||
621 | singleton($treeClass)->flushCache(); |
||
622 | |||
623 | $record = DataObject::get_by_id($treeClass, $id); |
||
624 | } |
||
625 | |||
626 | // Then, try getting a deleted record |
||
627 | if(!$record) { |
||
628 | $record = Versioned::get_latest_version($treeClass, $id); |
||
629 | } |
||
630 | |||
631 | // Don't open a page from a different locale |
||
632 | /** The record's Locale is saved in database in 2.4, and not related with Session, |
||
633 | * we should not check their locale matches the Translatable::get_current_locale, |
||
634 | * here as long as we all the HTTPRequest is init with right locale. |
||
635 | * This bit breaks the all FileIFrameField functions if the field is used in CMS |
||
636 | * and its relevent ajax calles, like loading the tree dropdown for TreeSelectorField. |
||
637 | */ |
||
638 | /* if($record && SiteTree::has_extension('Translatable') && $record->Locale && $record->Locale != Translatable::get_current_locale()) { |
||
639 | $record = null; |
||
640 | }*/ |
||
641 | |||
642 | // Set the reading mode back to what it was. |
||
643 | Versioned::set_reading_mode($currentStage); |
||
644 | |||
645 | return $record; |
||
646 | |||
647 | } else if(substr($id,0,3) == 'new') { |
||
648 | return $this->getNewItem($id); |
||
649 | } |
||
650 | } |
||
651 | |||
652 | /** |
||
653 | * @param int $id |
||
654 | * @param FieldList $fields |
||
655 | * @return Form |
||
656 | */ |
||
657 | public function getEditForm($id = null, $fields = null) { |
||
658 | if(!$id) $id = $this->currentPageID(); |
||
659 | $form = parent::getEditForm($id, $fields); |
||
660 | |||
661 | // TODO Duplicate record fetching (see parent implementation) |
||
662 | $record = $this->getRecord($id); |
||
663 | if($record && !$record->canView()) return Security::permissionFailure($this); |
||
664 | |||
665 | if(!$fields) $fields = $form->Fields(); |
||
666 | $actions = $form->Actions(); |
||
667 | |||
668 | if($record) { |
||
669 | $deletedFromStage = !$record->isOnDraft(); |
||
670 | |||
671 | $fields->push($idField = new HiddenField("ID", false, $id)); |
||
672 | // Necessary for different subsites |
||
673 | $fields->push($liveLinkField = new HiddenField("AbsoluteLink", false, $record->AbsoluteLink())); |
||
674 | $fields->push($liveLinkField = new HiddenField("LiveLink")); |
||
675 | $fields->push($stageLinkField = new HiddenField("StageLink")); |
||
676 | $fields->push(new HiddenField("TreeTitle", false, $record->TreeTitle)); |
||
677 | |||
678 | if($record->ID && is_numeric( $record->ID ) ) { |
||
679 | $liveLink = $record->getAbsoluteLiveLink(); |
||
680 | if($liveLink) $liveLinkField->setValue($liveLink); |
||
681 | if(!$deletedFromStage) { |
||
682 | $stageLink = Controller::join_links($record->AbsoluteLink(), '?stage=Stage'); |
||
683 | if($stageLink) $stageLinkField->setValue($stageLink); |
||
684 | } |
||
685 | } |
||
686 | |||
687 | // Added in-line to the form, but plucked into different view by LeftAndMain.Preview.js upon load |
||
688 | /** @skipUpgrade */ |
||
689 | if($record instanceof CMSPreviewable && !$fields->fieldByName('SilverStripeNavigator')) { |
||
690 | $navField = new LiteralField('SilverStripeNavigator', $this->getSilverStripeNavigator()); |
||
691 | $navField->setAllowHTML(true); |
||
692 | $fields->push($navField); |
||
693 | } |
||
694 | |||
695 | // getAllCMSActions can be used to completely redefine the action list |
||
696 | if($record->hasMethod('getAllCMSActions')) { |
||
697 | $actions = $record->getAllCMSActions(); |
||
698 | } else { |
||
699 | $actions = $record->getCMSActions(); |
||
700 | |||
701 | // Find and remove action menus that have no actions. |
||
702 | if ($actions && $actions->count()) { |
||
703 | /** @var TabSet $tabset */ |
||
704 | $tabset = $actions->fieldByName('ActionMenus'); |
||
705 | if ($tabset) { |
||
706 | foreach ($tabset->getChildren() as $tab) { |
||
707 | if (!$tab->getChildren()->count()) { |
||
708 | $tabset->removeByName($tab->getName()); |
||
709 | } |
||
710 | } |
||
711 | } |
||
712 | } |
||
713 | } |
||
714 | |||
715 | // Use <button> to allow full jQuery UI styling |
||
716 | $actionsFlattened = $actions->dataFields(); |
||
717 | if($actionsFlattened) { |
||
718 | /** @var FormAction $action */ |
||
719 | foreach($actionsFlattened as $action) { |
||
720 | $action->setUseButtonTag(true); |
||
721 | } |
||
722 | } |
||
723 | |||
724 | if($record->hasMethod('getCMSValidator')) { |
||
725 | $validator = $record->getCMSValidator(); |
||
726 | } else { |
||
727 | $validator = new RequiredFields(); |
||
728 | } |
||
729 | |||
730 | // TODO Can't merge $FormAttributes in template at the moment |
||
731 | $form->addExtraClass('center ' . $this->BaseCSSClasses()); |
||
732 | // Set validation exemptions for specific actions |
||
733 | $form->setValidationExemptActions(array('restore', 'revert', 'deletefromlive', 'delete', 'unpublish', 'rollback', 'doRollback')); |
||
734 | |||
735 | // Announce the capability so the frontend can decide whether to allow preview or not. |
||
736 | if ($record instanceof CMSPreviewable) { |
||
737 | $form->addExtraClass('cms-previewable'); |
||
738 | } |
||
739 | $form->addExtraClass('fill-height flexbox-area-grow'); |
||
740 | |||
741 | if(!$record->canEdit() || $deletedFromStage) { |
||
742 | $readonlyFields = $form->Fields()->makeReadonly(); |
||
743 | $form->setFields($readonlyFields); |
||
744 | } |
||
745 | |||
746 | $form->Fields()->setForm($form); |
||
747 | |||
748 | $this->extend('updateEditForm', $form); |
||
749 | return $form; |
||
750 | } else if($id) { |
||
751 | $form = Form::create( $this, "EditForm", new FieldList( |
||
752 | new LabelField('PageDoesntExistLabel',_t('CMSMain.PAGENOTEXISTS',"This page doesn't exist"))), new FieldList() |
||
753 | )->setHTMLID('Form_EditForm'); |
||
754 | return $form; |
||
755 | } |
||
756 | } |
||
757 | |||
758 | /** |
||
759 | * @param HTTPRequest $request |
||
760 | * @return string HTML |
||
761 | */ |
||
762 | public function treeview($request) { |
||
765 | |||
766 | /** |
||
767 | * @param HTTPRequest $request |
||
768 | * @return string HTML |
||
769 | */ |
||
770 | public function listview($request) { |
||
773 | |||
774 | /** |
||
775 | * Callback to request the list of page types allowed under a given page instance. |
||
776 | * Provides a slower but more precise response over SiteTreeHints |
||
777 | * |
||
778 | * @param HTTPRequest $request |
||
779 | * @return HTTPResponse |
||
780 | */ |
||
781 | public function childfilter($request) { |
||
806 | |||
807 | /** |
||
808 | * Safely reconstruct a selected filter from a given set of query parameters |
||
809 | * |
||
810 | * @param array $params Query parameters to use |
||
811 | * @return CMSSiteTreeFilter The filter class, or null if none present |
||
812 | * @throws InvalidArgumentException if invalid filter class is passed. |
||
813 | */ |
||
814 | protected function getQueryFilter($params) { |
||
815 | if(empty($params['FilterClass'])) return null; |
||
816 | $filterClass = $params['FilterClass']; |
||
817 | if(!is_subclass_of($filterClass, 'SilverStripe\\CMS\\Controllers\\CMSSiteTreeFilter')) { |
||
818 | throw new InvalidArgumentException("Invalid filter class passed: {$filterClass}"); |
||
819 | } |
||
820 | return $filterClass::create($params); |
||
821 | } |
||
822 | |||
823 | /** |
||
824 | * Returns the pages meet a certain criteria as {@see CMSSiteTreeFilter} or the subpages of a parent page |
||
825 | * defaulting to no filter and show all pages in first level. |
||
826 | * Doubles as search results, if any search parameters are set through {@link SearchForm()}. |
||
827 | * |
||
828 | * @param array $params Search filter criteria |
||
829 | * @param int $parentID Optional parent node to filter on (can't be combined with other search criteria) |
||
830 | * @return SS_List |
||
831 | * @throws InvalidArgumentException if invalid filter class is passed. |
||
832 | */ |
||
833 | public function getList($params = array(), $parentID = 0) { |
||
842 | |||
843 | /** |
||
844 | * @return Form |
||
845 | */ |
||
846 | public function ListViewForm() { |
||
847 | $params = $this->getRequest()->requestVar('q'); |
||
848 | $list = $this->getList($params, $parentID = $this->getRequest()->requestVar('ParentID')); |
||
849 | $gridFieldConfig = GridFieldConfig::create()->addComponents( |
||
850 | new GridFieldSortableHeader(), |
||
851 | new GridFieldDataColumns(), |
||
852 | new GridFieldPaginator(self::config()->page_length) |
||
853 | ); |
||
854 | if($parentID){ |
||
855 | $linkSpec = $this->Link(); |
||
856 | $linkSpec = $linkSpec . (strstr($linkSpec, '?') ? '&' : '?') . 'ParentID=%d&view=list'; |
||
857 | $gridFieldConfig->addComponent( |
||
858 | GridFieldLevelup::create($parentID) |
||
859 | ->setLinkSpec($linkSpec) |
||
860 | ->setAttributes(array('data-pjax' => 'ListViewForm,Breadcrumbs')) |
||
861 | ); |
||
862 | } |
||
863 | $gridField = new GridField('Page','Pages', $list, $gridFieldConfig); |
||
864 | /** @var GridFieldDataColumns $columns */ |
||
865 | $columns = $gridField->getConfig()->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldDataColumns'); |
||
866 | |||
867 | // Don't allow navigating into children nodes on filtered lists |
||
868 | $fields = array( |
||
869 | 'getTreeTitle' => _t('SiteTree.PAGETITLE', 'Page Title'), |
||
870 | 'singular_name' => _t('SiteTree.PAGETYPE'), |
||
871 | 'LastEdited' => _t('SiteTree.LASTUPDATED', 'Last Updated'), |
||
944 | |||
945 | public function currentPageID() { |
||
952 | |||
953 | //------------------------------------------------------------------------------------------// |
||
954 | // Data saving handlers |
||
955 | |||
956 | /** |
||
957 | * Save and Publish page handler |
||
958 | * |
||
959 | * @param array $data |
||
960 | * @param Form $form |
||
961 | * @return HTTPResponse |
||
962 | * @throws HTTPResponse_Exception |
||
963 | */ |
||
964 | public function save($data, $form) { |
||
1030 | |||
1031 | /** |
||
1032 | * @uses LeftAndMainExtension->augmentNewSiteTreeItem() |
||
1033 | * |
||
1034 | * @param int|string $id |
||
1035 | * @param bool $setID |
||
1036 | * @return mixed|DataObject |
||
1037 | * @throws HTTPResponse_Exception |
||
1038 | */ |
||
1039 | public function getNewItem($id, $setID = true) { |
||
1086 | |||
1087 | /** |
||
1088 | * Actually perform the publication step |
||
1089 | * |
||
1090 | * @param Versioned|DataObject $record |
||
1091 | * @return mixed |
||
1092 | */ |
||
1093 | public function performPublish($record) { |
||
1100 | |||
1101 | /** |
||
1102 | * Reverts a page by publishing it to live. |
||
1103 | * Use {@link restorepage()} if you want to restore a page |
||
1104 | * which was deleted from draft without publishing. |
||
1105 | * |
||
1106 | * @uses SiteTree->doRevertToLive() |
||
1107 | * |
||
1108 | * @param array $data |
||
1109 | * @param Form $form |
||
1110 | * @return HTTPResponse |
||
1111 | * @throws HTTPResponse_Exception |
||
1112 | */ |
||
1113 | public function revert($data, $form) { |
||
1152 | |||
1153 | /** |
||
1154 | * Deletes the current record from all stages and archives it |
||
1155 | * |
||
1156 | * @see deletefromlive() |
||
1157 | * |
||
1158 | * @param array $data |
||
1159 | * @param Form $form |
||
1160 | * @return HTTPResponse |
||
1161 | * @throws HTTPResponse_Exception |
||
1162 | */ |
||
1163 | public function delete($data, $form) { |
||
1189 | |||
1190 | public function publish($data, $form) { |
||
1195 | |||
1196 | public function unpublish($data, $form) { |
||
1217 | |||
1218 | /** |
||
1219 | * @return HTTPResponse |
||
1220 | */ |
||
1221 | public function rollback() { |
||
1227 | |||
1228 | /** |
||
1229 | * Rolls a site back to a given version ID |
||
1230 | * |
||
1231 | * @param array $data |
||
1232 | * @param Form $form |
||
1233 | * @return HTTPResponse |
||
1234 | */ |
||
1235 | public function doRollback($data, $form) { |
||
1273 | |||
1274 | /** |
||
1275 | * Batch Actions Handler |
||
1276 | */ |
||
1277 | public function batchactions() { |
||
1280 | |||
1281 | public function BatchActionParameters() { |
||
1302 | /** |
||
1303 | * Returns a list of batch actions |
||
1304 | */ |
||
1305 | public function BatchActionList() { |
||
1308 | |||
1309 | public function publishall($request) { |
||
1365 | |||
1366 | /** |
||
1367 | * Restore a completely deleted page from the SiteTree_versions table. |
||
1368 | * |
||
1369 | * @param array $data |
||
1370 | * @param Form $form |
||
1371 | * @return HTTPResponse |
||
1372 | */ |
||
1373 | public function restore($data, $form) { |
||
1398 | |||
1399 | public function duplicate($request) { |
||
1437 | |||
1438 | public function duplicatewithchildren($request) { |
||
1470 | |||
1471 | public function providePermissions() { |
||
1485 | |||
1486 | } |
||
1487 |