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 |
||
12 | class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionProvider { |
||
13 | |||
14 | private static $url_segment = 'pages'; |
||
|
|||
15 | |||
16 | private static $url_rule = '/$Action/$ID/$OtherID'; |
||
17 | |||
18 | // Maintain a lower priority than other administration sections |
||
19 | // so that Director does not think they are actions of CMSMain |
||
20 | private static $url_priority = 39; |
||
21 | |||
22 | private static $menu_title = 'Edit Page'; |
||
23 | |||
24 | private static $menu_priority = 10; |
||
25 | |||
26 | private static $tree_class = "SiteTree"; |
||
27 | |||
28 | private static $subitem_class = "Member"; |
||
29 | |||
30 | /** |
||
31 | * Amount of results showing on a single page. |
||
32 | * |
||
33 | * @config |
||
34 | * @var int |
||
35 | */ |
||
36 | private static $page_length = 15; |
||
37 | |||
38 | private static $allowed_actions = array( |
||
39 | 'archive', |
||
40 | 'buildbrokenlinks', |
||
41 | 'deleteitems', |
||
42 | 'DeleteItemsForm', |
||
43 | 'dialog', |
||
44 | 'duplicate', |
||
45 | 'duplicatewithchildren', |
||
46 | 'publishall', |
||
47 | 'publishitems', |
||
48 | 'PublishItemsForm', |
||
49 | 'submit', |
||
50 | 'EditForm', |
||
51 | 'SearchForm', |
||
52 | 'SiteTreeAsUL', |
||
53 | 'getshowdeletedsubtree', |
||
54 | 'batchactions', |
||
55 | 'treeview', |
||
56 | 'listview', |
||
57 | 'ListViewForm', |
||
58 | 'childfilter', |
||
59 | ); |
||
60 | |||
61 | /** |
||
62 | * Enable legacy batch actions. |
||
63 | * @deprecated since version 4.0 |
||
64 | * @var array |
||
65 | * @config |
||
66 | */ |
||
67 | private static $enabled_legacy_actions = array(); |
||
68 | |||
69 | public function init() { |
||
70 | // set reading lang |
||
71 | if(SiteTree::has_extension('Translatable') && !$this->getRequest()->isAjax()) { |
||
72 | Translatable::choose_site_locale(array_keys(Translatable::get_existing_content_languages('SiteTree'))); |
||
73 | } |
||
74 | |||
75 | parent::init(); |
||
76 | |||
77 | Requirements::css(CMS_DIR . '/css/screen.css'); |
||
78 | Requirements::customCSS($this->generatePageIconsCss()); |
||
79 | Requirements::add_i18n_javascript(CMS_DIR . '/javascript/lang', false, true); |
||
80 | Requirements::javascript(CMS_DIR . '/javascript/dist/bundle-lib.js', [ |
||
81 | 'provides' => [ |
||
82 | CMS_DIR . '/javascript/dist/CMSMain.AddForm.js', |
||
83 | CMS_DIR . '/javascript/dist/CMSMain.EditForm.js', |
||
84 | CMS_DIR . '/javascript/dist/CMSMain.js', |
||
85 | CMS_DIR . '/javascript/dist/CMSMain.Tree.js', |
||
86 | CMS_DIR . '/javascript/dist/CMSPageHistoryController.js', |
||
87 | CMS_DIR . '/javascript/dist/RedirectorPage.js', |
||
88 | CMS_DIR . '/javascript/dist/SilverStripeNavigator.js', |
||
89 | CMS_DIR . '/javascript/dist/SiteTreeURLSegmentField.js' |
||
90 | ] |
||
91 | ]); |
||
92 | |||
93 | CMSBatchActionHandler::register('publish', 'CMSBatchAction_Publish'); |
||
94 | CMSBatchActionHandler::register('unpublish', 'CMSBatchAction_Unpublish'); |
||
95 | |||
96 | |||
97 | // Check legacy actions |
||
98 | $legacy = $this->config()->enabled_legacy_actions; |
||
99 | |||
100 | // Delete from live is unnecessary since we have unpublish which does the same thing |
||
101 | if(in_array('CMSBatchAction_DeleteFromLive', $legacy)) { |
||
102 | Deprecation::notice('4.0', 'Delete From Live is deprecated. Use Un-publish instead'); |
||
103 | CMSBatchActionHandler::register('deletefromlive', 'CMSBatchAction_DeleteFromLive'); |
||
104 | } |
||
105 | |||
106 | // Delete action |
||
107 | if(in_array('CMSBatchAction_Delete', $legacy)) { |
||
108 | Deprecation::notice('4.0', 'Delete from Stage is deprecated. Use Archive instead.'); |
||
109 | CMSBatchActionHandler::register('delete', 'CMSBatchAction_Delete'); |
||
110 | } else { |
||
111 | CMSBatchActionHandler::register('archive', 'CMSBatchAction_Archive'); |
||
112 | CMSBatchActionHandler::register('restore', 'CMSBatchAction_Restore'); |
||
113 | } |
||
114 | } |
||
115 | |||
116 | public function index($request) { |
||
117 | // In case we're not showing a specific record, explicitly remove any session state, |
||
118 | // to avoid it being highlighted in the tree, and causing an edit form to show. |
||
119 | if(!$request->param('Action')) $this->setCurrentPageId(null); |
||
120 | |||
121 | return parent::index($request); |
||
122 | } |
||
123 | |||
124 | public function getResponseNegotiator() { |
||
125 | $negotiator = parent::getResponseNegotiator(); |
||
126 | $controller = $this; |
||
127 | $negotiator->setCallback('ListViewForm', function() use(&$controller) { |
||
128 | return $controller->ListViewForm()->forTemplate(); |
||
129 | }); |
||
130 | return $negotiator; |
||
131 | } |
||
132 | |||
133 | /** |
||
134 | * If this is set to true, the "switchView" context in the |
||
135 | * template is shown, with links to the staging and publish site. |
||
136 | * |
||
137 | * @return boolean |
||
138 | */ |
||
139 | public function ShowSwitchView() { |
||
140 | return true; |
||
141 | } |
||
142 | |||
143 | /** |
||
144 | * Overloads the LeftAndMain::ShowView. Allows to pass a page as a parameter, so we are able |
||
145 | * to switch view also for archived versions. |
||
146 | */ |
||
147 | public function SwitchView($page = null) { |
||
148 | if(!$page) { |
||
149 | $page = $this->currentPage(); |
||
150 | } |
||
151 | |||
152 | if($page) { |
||
153 | $nav = SilverStripeNavigator::get_for_record($page); |
||
154 | return $nav['items']; |
||
155 | } |
||
156 | } |
||
157 | |||
158 | //------------------------------------------------------------------------------------------// |
||
159 | // Main controllers |
||
160 | |||
161 | //------------------------------------------------------------------------------------------// |
||
162 | // Main UI components |
||
163 | |||
164 | /** |
||
165 | * Override {@link LeftAndMain} Link to allow blank URL segment for CMSMain. |
||
166 | * |
||
167 | * @param string|null $action Action to link to. |
||
168 | * @return string |
||
169 | */ |
||
170 | public function Link($action = null) { |
||
171 | $link = Controller::join_links( |
||
172 | $this->stat('url_base', true), |
||
173 | $this->stat('url_segment', true), // in case we want to change the segment |
||
174 | '/', // trailing slash needed if $action is null! |
||
175 | "$action" |
||
176 | ); |
||
177 | $this->extend('updateLink', $link); |
||
178 | return $link; |
||
179 | } |
||
180 | |||
181 | public function LinkPages() { |
||
182 | return singleton('CMSPagesController')->Link(); |
||
183 | } |
||
184 | |||
185 | public function LinkPagesWithSearch() { |
||
186 | return $this->LinkWithSearch($this->LinkPages()); |
||
187 | } |
||
188 | |||
189 | public function LinkTreeView() { |
||
190 | return $this->LinkWithSearch(singleton('CMSMain')->Link('treeview')); |
||
191 | } |
||
192 | |||
193 | public function LinkListView() { |
||
194 | return $this->LinkWithSearch(singleton('CMSMain')->Link('listview')); |
||
195 | } |
||
196 | |||
197 | public function LinkGalleryView() { |
||
198 | return $this->LinkWithSearch(singleton('CMSMain')->Link('galleryview')); |
||
199 | } |
||
200 | |||
201 | public function LinkPageEdit($id = null) { |
||
202 | if(!$id) $id = $this->currentPageID(); |
||
203 | return $this->LinkWithSearch( |
||
204 | Controller::join_links(singleton('CMSPageEditController')->Link('show'), $id) |
||
205 | ); |
||
206 | } |
||
207 | |||
208 | View Code Duplication | public function LinkPageSettings() { |
|
209 | if($id = $this->currentPageID()) { |
||
210 | return $this->LinkWithSearch( |
||
211 | Controller::join_links(singleton('CMSPageSettingsController')->Link('show'), $id) |
||
212 | ); |
||
213 | } |
||
214 | } |
||
215 | |||
216 | View Code Duplication | public function LinkPageHistory() { |
|
217 | if($id = $this->currentPageID()) { |
||
218 | return $this->LinkWithSearch( |
||
219 | Controller::join_links(singleton('CMSPageHistoryController')->Link('show'), $id) |
||
220 | ); |
||
221 | } |
||
222 | } |
||
223 | |||
224 | public function LinkWithSearch($link) { |
||
225 | // Whitelist to avoid side effects |
||
226 | $params = array( |
||
227 | 'q' => (array)$this->getRequest()->getVar('q'), |
||
228 | 'ParentID' => $this->getRequest()->getVar('ParentID') |
||
229 | ); |
||
230 | $link = Controller::join_links( |
||
231 | $link, |
||
232 | array_filter(array_values($params)) ? '?' . http_build_query($params) : null |
||
233 | ); |
||
234 | $this->extend('updateLinkWithSearch', $link); |
||
235 | return $link; |
||
236 | } |
||
237 | |||
238 | public function LinkPageAdd($extra = null, $placeholders = null) { |
||
239 | $link = singleton("CMSPageAddController")->Link(); |
||
240 | $this->extend('updateLinkPageAdd', $link); |
||
241 | |||
242 | if($extra) { |
||
243 | $link = Controller::join_links ($link, $extra); |
||
244 | } |
||
245 | |||
246 | if($placeholders) { |
||
247 | $link .= (strpos($link, '?') === false ? "?$placeholders" : "&$placeholders"); |
||
248 | } |
||
249 | |||
250 | return $link; |
||
251 | } |
||
252 | |||
253 | /** |
||
254 | * @return string |
||
255 | */ |
||
256 | public function LinkPreview() { |
||
257 | $record = $this->getRecord($this->currentPageID()); |
||
258 | $baseLink = Director::absoluteBaseURL(); |
||
259 | if ($record && $record instanceof Page) { |
||
260 | // if we are an external redirector don't show a link |
||
261 | if ($record instanceof RedirectorPage && $record->RedirectionType == 'External') { |
||
262 | $baseLink = false; |
||
263 | } |
||
264 | else { |
||
265 | $baseLink = $record->Link('?stage=Stage'); |
||
266 | } |
||
267 | } |
||
268 | return $baseLink; |
||
269 | } |
||
270 | |||
271 | /** |
||
272 | * Return the entire site tree as a nested set of ULs |
||
273 | */ |
||
274 | public function SiteTreeAsUL() { |
||
275 | // Pre-cache sitetree version numbers for querying efficiency |
||
276 | Versioned::prepopulate_versionnumber_cache("SiteTree", "Stage"); |
||
277 | Versioned::prepopulate_versionnumber_cache("SiteTree", "Live"); |
||
278 | $html = $this->getSiteTreeFor($this->stat('tree_class')); |
||
279 | |||
280 | $this->extend('updateSiteTreeAsUL', $html); |
||
281 | |||
282 | return $html; |
||
283 | } |
||
284 | |||
285 | /** |
||
286 | * @return boolean |
||
287 | */ |
||
288 | public function TreeIsFiltered() { |
||
289 | $query = $this->getRequest()->getVar('q'); |
||
290 | |||
291 | if (!$query || (count($query) === 1 && isset($query['FilterClass']) && $query['FilterClass'] === 'CMSSiteTreeFilter_Search')) { |
||
292 | return false; |
||
293 | } |
||
294 | |||
295 | return true; |
||
296 | } |
||
297 | |||
298 | public function ExtraTreeTools() { |
||
299 | $html = ''; |
||
300 | $this->extend('updateExtraTreeTools', $html); |
||
301 | return $html; |
||
302 | } |
||
303 | |||
304 | /** |
||
305 | * Returns a Form for page searching for use in templates. |
||
306 | * |
||
307 | * Can be modified from a decorator by a 'updateSearchForm' method |
||
308 | * |
||
309 | * @return Form |
||
310 | */ |
||
311 | public function SearchForm() { |
||
312 | // Create the fields |
||
313 | $content = new TextField('q[Term]', _t('CMSSearch.FILTERLABELTEXT', 'Search')); |
||
314 | $dateHeader = new HeaderField('q[Date]', _t('CMSSearch.PAGEFILTERDATEHEADING', 'Last edited'), 4); |
||
315 | $dateFrom = new DateField( |
||
316 | 'q[LastEditedFrom]', |
||
317 | _t('CMSSearch.FILTERDATEFROM', 'From') |
||
318 | ); |
||
319 | $dateFrom->setConfig('showcalendar', true); |
||
320 | $dateTo = new DateField( |
||
321 | 'q[LastEditedTo]', |
||
322 | _t('CMSSearch.FILTERDATETO', 'To') |
||
323 | ); |
||
324 | $dateTo->setConfig('showcalendar', true); |
||
325 | $pageFilter = new DropdownField( |
||
326 | 'q[FilterClass]', |
||
327 | _t('CMSMain.PAGES', 'Page status'), |
||
328 | CMSSiteTreeFilter::get_all_filters() |
||
329 | ); |
||
330 | $pageClasses = new DropdownField( |
||
331 | 'q[ClassName]', |
||
332 | _t('CMSMain.PAGETYPEOPT', 'Page type', 'Dropdown for limiting search to a page type'), |
||
333 | $this->getPageTypes() |
||
334 | ); |
||
335 | $pageClasses->setEmptyString(_t('CMSMain.PAGETYPEANYOPT','Any')); |
||
336 | |||
337 | // Group the Datefields |
||
338 | $dateGroup = new FieldGroup( |
||
339 | $dateHeader, |
||
340 | $dateFrom, |
||
341 | $dateTo |
||
342 | ); |
||
343 | $dateGroup->setFieldHolderTemplate('FieldGroup_DefaultFieldHolder')->addExtraClass('stacked'); |
||
344 | |||
345 | // Create the Field list |
||
346 | $fields = new FieldList( |
||
347 | $content, |
||
348 | $dateGroup, |
||
349 | $pageFilter, |
||
350 | $pageClasses |
||
351 | ); |
||
352 | |||
353 | // Create the Search and Reset action |
||
354 | $actions = new FieldList( |
||
355 | FormAction::create('doSearch', _t('CMSMain_left_ss.APPLY_FILTER', 'Search')) |
||
356 | ->addExtraClass('ss-ui-action-constructive'), |
||
357 | Object::create('ResetFormAction', 'clear', _t('CMSMain_left_ss.CLEAR_FILTER', 'Clear')) |
||
358 | ); |
||
359 | |||
360 | // Use <button> to allow full jQuery UI styling on the all of the Actions |
||
361 | foreach($actions->dataFields() as $action) { |
||
362 | $action->setUseButtonTag(true); |
||
363 | } |
||
364 | |||
365 | // Create the form |
||
366 | $form = Form::create($this, 'SearchForm', $fields, $actions) |
||
367 | ->addExtraClass('cms-search-form') |
||
368 | ->setFormMethod('GET') |
||
369 | ->setFormAction($this->Link()) |
||
370 | ->disableSecurityToken() |
||
371 | ->unsetValidator(); |
||
372 | |||
373 | // Load the form with previously sent search data |
||
374 | $form->loadDataFrom($this->getRequest()->getVars()); |
||
375 | |||
376 | // Allow decorators to modify the form |
||
377 | $this->extend('updateSearchForm', $form); |
||
378 | |||
379 | return $form; |
||
380 | } |
||
381 | |||
382 | /** |
||
383 | * Returns a sorted array suitable for a dropdown with pagetypes and their translated name |
||
384 | * |
||
385 | * @return array |
||
386 | */ |
||
387 | protected function getPageTypes() { |
||
388 | $pageTypes = array(); |
||
389 | foreach(SiteTree::page_type_classes() as $pageTypeClass) { |
||
390 | $pageTypes[$pageTypeClass] = _t($pageTypeClass.'.SINGULARNAME', $pageTypeClass); |
||
391 | } |
||
392 | asort($pageTypes); |
||
393 | return $pageTypes; |
||
394 | } |
||
395 | |||
396 | public function doSearch($data, $form) { |
||
397 | return $this->getsubtree($this->getRequest()); |
||
398 | } |
||
399 | |||
400 | /** |
||
401 | * @param bool $unlinked |
||
402 | * @return ArrayList |
||
403 | */ |
||
404 | public function Breadcrumbs($unlinked = false) { |
||
405 | $items = parent::Breadcrumbs($unlinked); |
||
406 | |||
407 | if($items->count() > 1) { |
||
408 | // Specific to the SiteTree admin section, we never show the cms section and current |
||
409 | // page in the same breadcrumbs block. |
||
410 | $items->shift(); |
||
411 | } |
||
412 | |||
413 | return $items; |
||
414 | } |
||
415 | |||
416 | /** |
||
417 | * Create serialized JSON string with site tree hints data to be injected into |
||
418 | * 'data-hints' attribute of root node of jsTree. |
||
419 | * |
||
420 | * @return string Serialized JSON |
||
421 | */ |
||
422 | public function SiteTreeHints() { |
||
423 | $json = ''; |
||
424 | $classes = SiteTree::page_type_classes(); |
||
425 | |||
426 | $cacheCanCreate = array(); |
||
427 | foreach($classes as $class) $cacheCanCreate[$class] = singleton($class)->canCreate(); |
||
428 | |||
429 | // Generate basic cache key. Too complex to encompass all variations |
||
430 | $cache = SS_Cache::factory('CMSMain_SiteTreeHints'); |
||
431 | $cacheKey = md5(implode('_', array(Member::currentUserID(), implode(',', $cacheCanCreate), implode(',', $classes)))); |
||
432 | if($this->getRequest()->getVar('flush')) $cache->clean(Zend_Cache::CLEANING_MODE_ALL); |
||
433 | $json = $cache->load($cacheKey); |
||
434 | if(!$json) { |
||
435 | $def['Root'] = array(); |
||
436 | $def['Root']['disallowedChildren'] = array(); |
||
437 | |||
438 | // Contains all possible classes to support UI controls listing them all, |
||
439 | // such as the "add page here" context menu. |
||
440 | $def['All'] = array(); |
||
441 | |||
442 | // Identify disallows and set globals |
||
443 | foreach($classes as $class) { |
||
444 | $obj = singleton($class); |
||
445 | if($obj instanceof HiddenClass) continue; |
||
446 | |||
447 | // Name item |
||
448 | $def['All'][$class] = array( |
||
449 | 'title' => $obj->i18n_singular_name() |
||
450 | ); |
||
451 | |||
452 | // Check if can be created at the root |
||
453 | $needsPerm = $obj->stat('need_permission'); |
||
454 | if( |
||
455 | !$obj->stat('can_be_root') |
||
456 | || (!array_key_exists($class, $cacheCanCreate) || !$cacheCanCreate[$class]) |
||
457 | || ($needsPerm && !$this->can($needsPerm)) |
||
458 | ) { |
||
459 | $def['Root']['disallowedChildren'][] = $class; |
||
460 | } |
||
461 | |||
462 | // Hint data specific to the class |
||
463 | $def[$class] = array(); |
||
464 | |||
465 | $defaultChild = $obj->defaultChild(); |
||
466 | if($defaultChild !== 'Page' && $defaultChild !== null) { |
||
467 | $def[$class]['defaultChild'] = $defaultChild; |
||
468 | } |
||
469 | |||
470 | $defaultParent = $obj->defaultParent(); |
||
471 | if ($defaultParent !== 1 && $defaultParent !== null) { |
||
472 | $def[$class]['defaultParent'] = $defaultParent; |
||
473 | } |
||
474 | } |
||
475 | |||
476 | $this->extend('updateSiteTreeHints', $def); |
||
477 | |||
478 | $json = Convert::raw2json($def); |
||
479 | $cache->save($json, $cacheKey); |
||
480 | } |
||
481 | return $json; |
||
482 | } |
||
483 | |||
484 | /** |
||
485 | * Populates an array of classes in the CMS |
||
486 | * which allows the user to change the page type. |
||
487 | * |
||
488 | * @return SS_List |
||
489 | */ |
||
490 | public function PageTypes() { |
||
491 | $classes = SiteTree::page_type_classes(); |
||
492 | |||
493 | $result = new ArrayList(); |
||
494 | |||
495 | foreach($classes as $class) { |
||
496 | $instance = singleton($class); |
||
497 | |||
498 | if($instance instanceof HiddenClass) continue; |
||
499 | |||
500 | // skip this type if it is restricted |
||
501 | if($instance->stat('need_permission') && !$this->can(singleton($class)->stat('need_permission'))) continue; |
||
502 | |||
503 | $addAction = $instance->i18n_singular_name(); |
||
504 | |||
505 | // Get description (convert 'Page' to 'SiteTree' for correct localization lookups) |
||
506 | $description = _t((($class == 'Page') ? 'SiteTree' : $class) . '.DESCRIPTION'); |
||
507 | |||
508 | if(!$description) { |
||
509 | $description = $instance->uninherited('description'); |
||
510 | } |
||
511 | |||
512 | if($class == 'Page' && !$description) { |
||
513 | $description = singleton('SiteTree')->uninherited('description'); |
||
514 | } |
||
515 | |||
516 | $result->push(new ArrayData(array( |
||
517 | 'ClassName' => $class, |
||
518 | 'AddAction' => $addAction, |
||
519 | 'Description' => $description, |
||
520 | // TODO Sprite support |
||
521 | 'IconURL' => $instance->stat('icon'), |
||
522 | 'Title' => singleton($class)->i18n_singular_name(), |
||
523 | ))); |
||
524 | } |
||
525 | |||
526 | $result = $result->sort('AddAction'); |
||
527 | |||
528 | return $result; |
||
529 | } |
||
530 | |||
531 | /** |
||
532 | * Get a database record to be managed by the CMS. |
||
533 | * |
||
534 | * @param int $id Record ID |
||
535 | * @param int $versionID optional Version id of the given record |
||
536 | * @return SiteTree |
||
537 | */ |
||
538 | public function getRecord($id, $versionID = null) { |
||
539 | $treeClass = $this->stat('tree_class'); |
||
540 | |||
541 | if($id instanceof $treeClass) { |
||
542 | return $id; |
||
543 | } |
||
544 | else if($id && is_numeric($id)) { |
||
545 | if($this->getRequest()->getVar('Version')) { |
||
546 | $versionID = (int) $this->getRequest()->getVar('Version'); |
||
547 | } |
||
548 | |||
549 | if($versionID) { |
||
550 | $record = Versioned::get_version($treeClass, $id, $versionID); |
||
551 | } else { |
||
552 | $record = DataObject::get_by_id($treeClass, $id); |
||
553 | } |
||
554 | |||
555 | // Then, try getting a record from the live site |
||
556 | if(!$record) { |
||
557 | // $record = Versioned::get_one_by_stage($treeClass, "Live", "\"$treeClass\".\"ID\" = $id"); |
||
558 | Versioned::reading_stage('Live'); |
||
559 | singleton($treeClass)->flushCache(); |
||
560 | |||
561 | $record = DataObject::get_by_id($treeClass, $id); |
||
562 | if($record) Versioned::set_reading_mode(''); |
||
563 | } |
||
564 | |||
565 | // Then, try getting a deleted record |
||
566 | if(!$record) { |
||
567 | $record = Versioned::get_latest_version($treeClass, $id); |
||
568 | } |
||
569 | |||
570 | // Don't open a page from a different locale |
||
571 | /** The record's Locale is saved in database in 2.4, and not related with Session, |
||
572 | * we should not check their locale matches the Translatable::get_current_locale, |
||
573 | * here as long as we all the HTTPRequest is init with right locale. |
||
574 | * This bit breaks the all FileIFrameField functions if the field is used in CMS |
||
575 | * and its relevent ajax calles, like loading the tree dropdown for TreeSelectorField. |
||
576 | */ |
||
577 | /* if($record && SiteTree::has_extension('Translatable') && $record->Locale && $record->Locale != Translatable::get_current_locale()) { |
||
578 | $record = null; |
||
579 | }*/ |
||
580 | |||
581 | return $record; |
||
582 | |||
583 | } else if(substr($id,0,3) == 'new') { |
||
584 | return $this->getNewItem($id); |
||
585 | } |
||
586 | } |
||
587 | |||
588 | /** |
||
589 | * @param int $id |
||
590 | * @param FieldList $fields |
||
591 | * @return Form |
||
592 | */ |
||
593 | public function getEditForm($id = null, $fields = null) { |
||
594 | if(!$id) $id = $this->currentPageID(); |
||
595 | $form = parent::getEditForm($id); |
||
596 | |||
597 | // TODO Duplicate record fetching (see parent implementation) |
||
598 | $record = $this->getRecord($id); |
||
599 | if($record && !$record->canView()) return Security::permissionFailure($this); |
||
600 | |||
601 | if(!$fields) $fields = $form->Fields(); |
||
602 | $actions = $form->Actions(); |
||
603 | |||
604 | if($record) { |
||
605 | $deletedFromStage = $record->getIsDeletedFromStage(); |
||
606 | |||
607 | $fields->push($idField = new HiddenField("ID", false, $id)); |
||
608 | // Necessary for different subsites |
||
609 | $fields->push($liveLinkField = new HiddenField("AbsoluteLink", false, $record->AbsoluteLink())); |
||
610 | $fields->push($liveLinkField = new HiddenField("LiveLink")); |
||
611 | $fields->push($stageLinkField = new HiddenField("StageLink")); |
||
612 | $fields->push(new HiddenField("TreeTitle", false, $record->TreeTitle)); |
||
613 | |||
614 | if($record->ID && is_numeric( $record->ID ) ) { |
||
615 | $liveLink = $record->getAbsoluteLiveLink(); |
||
616 | if($liveLink) $liveLinkField->setValue($liveLink); |
||
617 | if(!$deletedFromStage) { |
||
618 | $stageLink = Controller::join_links($record->AbsoluteLink(), '?stage=Stage'); |
||
619 | if($stageLink) $stageLinkField->setValue($stageLink); |
||
620 | } |
||
621 | } |
||
622 | |||
623 | // Added in-line to the form, but plucked into different view by LeftAndMain.Preview.js upon load |
||
624 | if(in_array('CMSPreviewable', class_implements($record)) && !$fields->fieldByName('SilverStripeNavigator')) { |
||
625 | $navField = new LiteralField('SilverStripeNavigator', $this->getSilverStripeNavigator()); |
||
626 | $navField->setAllowHTML(true); |
||
627 | $fields->push($navField); |
||
628 | } |
||
629 | |||
630 | // getAllCMSActions can be used to completely redefine the action list |
||
631 | if($record->hasMethod('getAllCMSActions')) { |
||
632 | $actions = $record->getAllCMSActions(); |
||
633 | } else { |
||
634 | $actions = $record->getCMSActions(); |
||
635 | |||
636 | // Find and remove action menus that have no actions. |
||
637 | if ($actions && $actions->Count()) { |
||
638 | $tabset = $actions->fieldByName('ActionMenus'); |
||
639 | if ($tabset) { |
||
640 | foreach ($tabset->getChildren() as $tab) { |
||
641 | if (!$tab->getChildren()->count()) { |
||
642 | $tabset->removeByName($tab->getName()); |
||
643 | } |
||
644 | } |
||
645 | } |
||
646 | } |
||
647 | } |
||
648 | |||
649 | // Use <button> to allow full jQuery UI styling |
||
650 | $actionsFlattened = $actions->dataFields(); |
||
651 | if($actionsFlattened) foreach($actionsFlattened as $action) $action->setUseButtonTag(true); |
||
652 | |||
653 | if($record->hasMethod('getCMSValidator')) { |
||
654 | $validator = $record->getCMSValidator(); |
||
655 | } else { |
||
656 | $validator = new RequiredFields(); |
||
657 | } |
||
658 | |||
659 | // TODO Can't merge $FormAttributes in template at the moment |
||
660 | $form->addExtraClass('center ' . $this->BaseCSSClasses()); |
||
661 | // Set validation exemptions for specific actions |
||
662 | $form->setValidationExemptActions(array('restore', 'revert', 'deletefromlive', 'delete', 'unpublish', 'rollback', 'doRollback')); |
||
663 | |||
664 | // Announce the capability so the frontend can decide whether to allow preview or not. |
||
665 | if(in_array('CMSPreviewable', class_implements($record))) { |
||
666 | $form->addExtraClass('cms-previewable'); |
||
667 | } |
||
668 | |||
669 | if(!$record->canEdit() || $deletedFromStage) { |
||
670 | $readonlyFields = $form->Fields()->makeReadonly(); |
||
671 | $form->setFields($readonlyFields); |
||
672 | } |
||
673 | |||
674 | $this->extend('updateEditForm', $form); |
||
675 | return $form; |
||
676 | } else if($id) { |
||
677 | $form = Form::create( $this, "EditForm", new FieldList( |
||
678 | new LabelField('PageDoesntExistLabel',_t('CMSMain.PAGENOTEXISTS',"This page doesn't exist"))), new FieldList() |
||
679 | )->setHTMLID('Form_EditForm'); |
||
680 | return $form; |
||
681 | } |
||
682 | } |
||
683 | |||
684 | /** |
||
685 | * @param SS_HTTPRequest $request |
||
686 | * @return string HTML |
||
687 | */ |
||
688 | public function treeview($request) { |
||
689 | return $this->renderWith($this->getTemplatesWithSuffix('_TreeView')); |
||
690 | } |
||
691 | |||
692 | /** |
||
693 | * @param SS_HTTPRequest $request |
||
694 | * @return string HTML |
||
695 | */ |
||
696 | public function listview($request) { |
||
697 | return $this->renderWith($this->getTemplatesWithSuffix('_ListView')); |
||
698 | } |
||
699 | |||
700 | /** |
||
701 | * Callback to request the list of page types allowed under a given page instance. |
||
702 | * Provides a slower but more precise response over SiteTreeHints |
||
703 | * |
||
704 | * @param SS_HTTPRequest $request |
||
705 | * @return SS_HTTPResponse |
||
706 | */ |
||
707 | public function childfilter($request) { |
||
708 | // Check valid parent specified |
||
709 | $parentID = $request->requestVar('ParentID'); |
||
710 | $parent = SiteTree::get()->byID($parentID); |
||
711 | if(!$parent || !$parent->exists()) return $this->httpError(404); |
||
712 | |||
713 | // Build hints specific to this class |
||
714 | // Identify disallows and set globals |
||
715 | $classes = SiteTree::page_type_classes(); |
||
716 | $disallowedChildren = array(); |
||
717 | foreach($classes as $class) { |
||
718 | $obj = singleton($class); |
||
719 | if($obj instanceof HiddenClass) continue; |
||
720 | |||
721 | if(!$obj->canCreate(null, array('Parent' => $parent))) { |
||
722 | $disallowedChildren[] = $class; |
||
723 | } |
||
724 | } |
||
725 | |||
726 | $this->extend('updateChildFilter', $disallowedChildren, $parentID); |
||
727 | return $this |
||
728 | ->getResponse() |
||
729 | ->addHeader('Content-Type', 'application/json; charset=utf-8') |
||
730 | ->setBody(Convert::raw2json($disallowedChildren)); |
||
731 | } |
||
732 | |||
733 | /** |
||
734 | * Safely reconstruct a selected filter from a given set of query parameters |
||
735 | * |
||
736 | * @param array $params Query parameters to use |
||
737 | * @return CMSSiteTreeFilter The filter class, or null if none present |
||
738 | * @throws InvalidArgumentException if invalid filter class is passed. |
||
739 | */ |
||
740 | protected function getQueryFilter($params) { |
||
741 | if(empty($params['FilterClass'])) return null; |
||
742 | $filterClass = $params['FilterClass']; |
||
743 | if(!is_subclass_of($filterClass, 'CMSSiteTreeFilter')) { |
||
744 | throw new InvalidArgumentException("Invalid filter class passed: {$filterClass}"); |
||
745 | } |
||
746 | return $filterClass::create($params); |
||
747 | } |
||
748 | |||
749 | /** |
||
750 | * Returns the pages meet a certain criteria as {@see CMSSiteTreeFilter} or the subpages of a parent page |
||
751 | * defaulting to no filter and show all pages in first level. |
||
752 | * Doubles as search results, if any search parameters are set through {@link SearchForm()}. |
||
753 | * |
||
754 | * @param array $params Search filter criteria |
||
755 | * @param int $parentID Optional parent node to filter on (can't be combined with other search criteria) |
||
756 | * @return SS_List |
||
757 | * @throws InvalidArgumentException if invalid filter class is passed. |
||
758 | */ |
||
759 | public function getList($params = array(), $parentID = 0) { |
||
760 | if($filter = $this->getQueryFilter($params)) { |
||
761 | return $filter->getFilteredPages(); |
||
762 | } else { |
||
763 | $list = DataList::create($this->stat('tree_class')); |
||
764 | $parentID = is_numeric($parentID) ? $parentID : 0; |
||
765 | return $list->filter("ParentID", $parentID); |
||
766 | } |
||
767 | } |
||
768 | |||
769 | public function ListViewForm() { |
||
770 | $params = $this->getRequest()->requestVar('q'); |
||
771 | $list = $this->getList($params, $parentID = $this->getRequest()->requestVar('ParentID')); |
||
772 | $gridFieldConfig = GridFieldConfig::create()->addComponents( |
||
773 | new GridFieldSortableHeader(), |
||
774 | new GridFieldDataColumns(), |
||
775 | new GridFieldPaginator(self::config()->page_length) |
||
776 | ); |
||
777 | if($parentID){ |
||
778 | $gridFieldConfig->addComponent( |
||
779 | GridFieldLevelup::create($parentID) |
||
780 | ->setLinkSpec('?ParentID=%d&view=list') |
||
781 | ->setAttributes(array('data-pjax' => 'ListViewForm,Breadcrumbs')) |
||
782 | ); |
||
783 | } |
||
784 | $gridField = new GridField('Page','Pages', $list, $gridFieldConfig); |
||
785 | $columns = $gridField->getConfig()->getComponentByType('GridFieldDataColumns'); |
||
786 | |||
787 | // Don't allow navigating into children nodes on filtered lists |
||
788 | $fields = array( |
||
789 | 'getTreeTitle' => _t('SiteTree.PAGETITLE', 'Page Title'), |
||
790 | 'singular_name' => _t('SiteTree.PAGETYPE'), |
||
791 | 'LastEdited' => _t('SiteTree.LASTUPDATED', 'Last Updated'), |
||
792 | ); |
||
793 | $gridField->getConfig()->getComponentByType('GridFieldSortableHeader')->setFieldSorting(array('getTreeTitle' => 'Title')); |
||
794 | $gridField->getState()->ParentID = $parentID; |
||
795 | |||
796 | if(!$params) { |
||
797 | $fields = array_merge(array('listChildrenLink' => ''), $fields); |
||
798 | } |
||
799 | |||
800 | $columns->setDisplayFields($fields); |
||
801 | $columns->setFieldCasting(array( |
||
802 | 'Created' => 'SS_Datetime->Ago', |
||
803 | 'LastEdited' => 'SS_Datetime->FormatFromSettings', |
||
804 | 'getTreeTitle' => 'HTMLText' |
||
805 | )); |
||
806 | |||
807 | $controller = $this; |
||
808 | $columns->setFieldFormatting(array( |
||
809 | 'listChildrenLink' => function($value, &$item) use($controller) { |
||
810 | $num = $item ? $item->numChildren() : null; |
||
811 | if($num) { |
||
812 | return sprintf( |
||
813 | '<a class="cms-panel-link list-children-link" data-pjax-target="ListViewForm,Breadcrumbs" href="%s">%s</a>', |
||
814 | Controller::join_links( |
||
815 | $controller->Link(), |
||
816 | sprintf("?ParentID=%d&view=list", (int)$item->ID) |
||
817 | ), |
||
818 | $num |
||
819 | ); |
||
820 | } |
||
821 | }, |
||
822 | 'getTreeTitle' => function($value, &$item) use($controller) { |
||
823 | return sprintf( |
||
824 | '<a class="action-detail" href="%s">%s</a>', |
||
825 | Controller::join_links( |
||
826 | singleton('CMSPageEditController')->Link('show'), |
||
827 | (int)$item->ID |
||
828 | ), |
||
829 | $item->TreeTitle // returns HTML, does its own escaping |
||
830 | ); |
||
831 | } |
||
832 | )); |
||
833 | |||
834 | $negotiator = $this->getResponseNegotiator(); |
||
835 | $listview = Form::create( |
||
836 | $this, |
||
837 | 'ListViewForm', |
||
838 | new FieldList($gridField), |
||
839 | new FieldList() |
||
840 | )->setHTMLID('Form_ListViewForm'); |
||
841 | $listview->setAttribute('data-pjax-fragment', 'ListViewForm'); |
||
842 | View Code Duplication | $listview->setValidationResponseCallback(function() use ($negotiator, $listview) { |
|
843 | $request = $this->getRequest(); |
||
844 | if($request->isAjax() && $negotiator) { |
||
845 | $listview->setupFormErrors(); |
||
846 | $result = $listview->forTemplate(); |
||
847 | |||
848 | return $negotiator->respond($request, array( |
||
849 | 'CurrentForm' => function() use($result) { |
||
850 | return $result; |
||
851 | } |
||
852 | )); |
||
853 | } |
||
854 | }); |
||
855 | |||
856 | $this->extend('updateListView', $listview); |
||
857 | |||
858 | $listview->disableSecurityToken(); |
||
859 | return $listview; |
||
860 | } |
||
861 | |||
862 | public function currentPageID() { |
||
863 | $id = parent::currentPageID(); |
||
864 | |||
865 | $this->extend('updateCurrentPageID', $id); |
||
866 | |||
867 | return $id; |
||
868 | } |
||
869 | |||
870 | //------------------------------------------------------------------------------------------// |
||
871 | // Data saving handlers |
||
872 | |||
873 | /** |
||
874 | * Save and Publish page handler |
||
875 | */ |
||
876 | public function save($data, $form) { |
||
877 | $className = $this->stat('tree_class'); |
||
878 | |||
879 | // Existing or new record? |
||
880 | $id = $data['ID']; |
||
881 | if(substr($id,0,3) != 'new') { |
||
882 | $record = DataObject::get_by_id($className, $id); |
||
883 | if($record && !$record->canEdit()) return Security::permissionFailure($this); |
||
884 | if(!$record || !$record->ID) throw new SS_HTTPResponse_Exception("Bad record ID #$id", 404); |
||
885 | } else { |
||
886 | if(!singleton($this->stat('tree_class'))->canCreate()) return Security::permissionFailure($this); |
||
887 | $record = $this->getNewItem($id, false); |
||
888 | } |
||
889 | |||
890 | // TODO Coupling to SiteTree |
||
891 | $record->HasBrokenLink = 0; |
||
892 | $record->HasBrokenFile = 0; |
||
893 | |||
894 | if (!$record->ObsoleteClassName) $record->writeWithoutVersion(); |
||
895 | |||
896 | // Update the class instance if necessary |
||
897 | if(isset($data['ClassName']) && $data['ClassName'] != $record->ClassName) { |
||
898 | $newClassName = $record->ClassName; |
||
899 | // The records originally saved attribute was overwritten by $form->saveInto($record) before. |
||
900 | // This is necessary for newClassInstance() to work as expected, and trigger change detection |
||
901 | // on the ClassName attribute |
||
902 | $record->setClassName($data['ClassName']); |
||
903 | // Replace $record with a new instance |
||
904 | $record = $record->newClassInstance($newClassName); |
||
905 | } |
||
906 | |||
907 | // save form data into record |
||
908 | $form->saveInto($record); |
||
909 | $record->write(); |
||
910 | |||
911 | // If the 'Save & Publish' button was clicked, also publish the page |
||
912 | if (isset($data['publish']) && $data['publish'] == 1) { |
||
913 | $record->doPublish(); |
||
914 | } |
||
915 | |||
916 | return $this->getResponseNegotiator()->respond($this->getRequest()); |
||
917 | } |
||
918 | |||
919 | /** |
||
920 | * @uses LeftAndMainExtension->augmentNewSiteTreeItem() |
||
921 | */ |
||
922 | public function getNewItem($id, $setID = true) { |
||
923 | $parentClass = $this->stat('tree_class'); |
||
924 | list($dummy, $className, $parentID, $suffix) = array_pad(explode('-',$id),4,null); |
||
925 | |||
926 | if(!is_subclass_of($className, $parentClass) && strcasecmp($className, $parentClass) != 0) { |
||
927 | $response = Security::permissionFailure($this); |
||
928 | if (!$response) { |
||
929 | $response = $this->getResponse(); |
||
930 | } |
||
931 | throw new SS_HTTPResponse_Exception($response); |
||
932 | } |
||
933 | |||
934 | $newItem = new $className(); |
||
935 | |||
936 | if( !$suffix ) { |
||
937 | $sessionTag = "NewItems." . $parentID . "." . $className; |
||
938 | if(Session::get($sessionTag)) { |
||
939 | $suffix = '-' . Session::get($sessionTag); |
||
940 | Session::set($sessionTag, Session::get($sessionTag) + 1); |
||
941 | } |
||
942 | else |
||
943 | Session::set($sessionTag, 1); |
||
944 | |||
945 | $id = $id . $suffix; |
||
946 | } |
||
947 | |||
948 | $newItem->Title = _t( |
||
949 | 'CMSMain.NEWPAGE', |
||
950 | "New {pagetype}",'followed by a page type title', |
||
951 | array('pagetype' => singleton($className)->i18n_singular_name()) |
||
952 | ); |
||
953 | $newItem->ClassName = $className; |
||
954 | $newItem->ParentID = $parentID; |
||
955 | |||
956 | // DataObject::fieldExists only checks the current class, not the hierarchy |
||
957 | // This allows the CMS to set the correct sort value |
||
958 | if($newItem->castingHelper('Sort')) { |
||
959 | $newItem->Sort = DB::prepared_query('SELECT MAX("Sort") FROM "SiteTree" WHERE "ParentID" = ?', array($parentID))->value() + 1; |
||
960 | } |
||
961 | |||
962 | if($setID) $newItem->ID = $id; |
||
963 | |||
964 | # Some modules like subsites add extra fields that need to be set when the new item is created |
||
965 | $this->extend('augmentNewSiteTreeItem', $newItem); |
||
966 | |||
967 | return $newItem; |
||
968 | } |
||
969 | |||
970 | /** |
||
971 | * Delete the page from live. This means a page in draft mode might still exist. |
||
972 | * |
||
973 | * @see delete() |
||
974 | */ |
||
975 | public function deletefromlive($data, $form) { |
||
976 | Versioned::reading_stage('Live'); |
||
977 | |||
978 | /** @var SiteTree $record */ |
||
979 | $record = DataObject::get_by_id("SiteTree", $data['ID']); |
||
980 | if($record && !($record->canDelete() && $record->canUnpublish())) { |
||
981 | return Security::permissionFailure($this); |
||
982 | } |
||
983 | |||
984 | $descendantsRemoved = 0; |
||
985 | $recordTitle = $record->Title; |
||
986 | |||
987 | // before deleting the records, get the descendants of this tree |
||
988 | if($record) { |
||
989 | $descendantIDs = $record->getDescendantIDList(); |
||
990 | |||
991 | // then delete them from the live site too |
||
992 | $descendantsRemoved = 0; |
||
993 | foreach( $descendantIDs as $descID ) |
||
994 | /** @var SiteTree $descendant */ |
||
995 | if( $descendant = DataObject::get_by_id('SiteTree', $descID) ) { |
||
996 | $descendant->doUnpublish(); |
||
997 | $descendantsRemoved++; |
||
998 | } |
||
999 | |||
1000 | // delete the record |
||
1001 | $record->doUnpublish(); |
||
1002 | } |
||
1003 | |||
1004 | Versioned::reading_stage('Stage'); |
||
1005 | |||
1006 | if(isset($descendantsRemoved)) { |
||
1007 | $descRemoved = ' ' . _t( |
||
1008 | 'CMSMain.DESCREMOVED', |
||
1009 | 'and {count} descendants', |
||
1010 | array('count' => $descendantsRemoved) |
||
1011 | ); |
||
1012 | } else { |
||
1013 | $descRemoved = ''; |
||
1014 | } |
||
1015 | |||
1016 | $this->getResponse()->addHeader( |
||
1017 | 'X-Status', |
||
1018 | rawurlencode( |
||
1019 | _t( |
||
1020 | 'CMSMain.REMOVED', |
||
1021 | 'Deleted \'{title}\'{description} from live site', |
||
1022 | array('title' => $recordTitle, 'description' => $descRemoved) |
||
1023 | ) |
||
1024 | ) |
||
1025 | ); |
||
1026 | |||
1027 | // Even if the record has been deleted from stage and live, it can be viewed in "archive mode" |
||
1028 | return $this->getResponseNegotiator()->respond($this->getRequest()); |
||
1029 | } |
||
1030 | |||
1031 | /** |
||
1032 | * Actually perform the publication step |
||
1033 | */ |
||
1034 | public function performPublish($record) { |
||
1039 | |||
1040 | /** |
||
1041 | * Reverts a page by publishing it to live. |
||
1042 | * Use {@link restorepage()} if you want to restore a page |
||
1043 | * which was deleted from draft without publishing. |
||
1044 | * |
||
1045 | * @uses SiteTree->doRevertToLive() |
||
1046 | */ |
||
1047 | public function revert($data, $form) { |
||
1077 | |||
1078 | /** |
||
1079 | * Delete the current page from draft stage. |
||
1080 | * @see deletefromlive() |
||
1081 | */ |
||
1082 | public function delete($data, $form) { |
||
1100 | |||
1101 | /** |
||
1102 | * Delete this page from both live and stage |
||
1103 | * |
||
1104 | * @param array $data |
||
1105 | * @param Form $form |
||
1106 | */ |
||
1107 | public function archive($data, $form) { |
||
1128 | |||
1129 | public function publish($data, $form) { |
||
1134 | |||
1135 | public function unpublish($data, $form) { |
||
1136 | $className = $this->stat('tree_class'); |
||
1137 | /** @var SiteTree $record */ |
||
1138 | $record = DataObject::get_by_id($className, $data['ID']); |
||
1156 | |||
1157 | /** |
||
1158 | * @return array |
||
1159 | */ |
||
1160 | public function rollback() { |
||
1166 | |||
1167 | /** |
||
1168 | * Rolls a site back to a given version ID |
||
1169 | * |
||
1170 | * @param array |
||
1171 | * @param Form |
||
1172 | * |
||
1173 | * @return html |
||
1174 | */ |
||
1175 | public function doRollback($data, $form) { |
||
1210 | |||
1211 | /** |
||
1212 | * Batch Actions Handler |
||
1213 | */ |
||
1214 | public function batchactions() { |
||
1217 | |||
1218 | public function BatchActionParameters() { |
||
1238 | /** |
||
1239 | * Returns a list of batch actions |
||
1240 | */ |
||
1241 | public function BatchActionList() { |
||
1244 | |||
1245 | public function buildbrokenlinks($request) { |
||
1280 | |||
1281 | public function publishall($request) { |
||
1334 | |||
1335 | /** |
||
1336 | * Restore a completely deleted page from the SiteTree_versions table. |
||
1337 | */ |
||
1338 | public function restore($data, $form) { |
||
1360 | |||
1361 | public function duplicate($request) { |
||
1398 | |||
1399 | public function duplicatewithchildren($request) { |
||
1430 | |||
1431 | public function providePermissions() { |
||
1445 | |||
1446 | } |
||
1447 |