Completed
Push — master ( 0fbdad...a03f6b )
by Daniel
16:02
created

code/Controllers/CMSPageAddController.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace SilverStripe\CMS\Controllers;
4
5
use SilverStripe\CMS\Model\SiteTree;
6
use SilverStripe\Control\Controller;
7
use SilverStripe\Control\Session;
8
use SilverStripe\Control\HTTPResponse;
9
use SilverStripe\Forms\FieldList;
10
use SilverStripe\Forms\Form;
11
use SilverStripe\Forms\FormAction;
12
use SilverStripe\Forms\LiteralField;
13
use SilverStripe\Forms\OptionsetField;
14
use SilverStripe\Forms\SelectionGroup;
15
use SilverStripe\Forms\SelectionGroup_Item;
16
use SilverStripe\Forms\TreeDropdownField;
17
use SilverStripe\ORM\DataObject;
18
use SilverStripe\ORM\FieldType\DBField;
19
use SilverStripe\ORM\ValidationResult;
20
use SilverStripe\Security\Member;
21
use SilverStripe\Security\Security;
22
23
class CMSPageAddController extends CMSPageEditController
24
{
25
26
    private static $url_segment = 'pages/add';
27
    private static $url_rule = '/$Action/$ID/$OtherID';
28
    private static $url_priority = 42;
29
    private static $menu_title = 'Add page';
30
    private static $required_permission_codes = 'CMS_ACCESS_CMSMain';
31
32
    private static $allowed_actions = array(
33
        'AddForm',
34
        'doAdd',
35
        'doCancel'
36
    );
37
38
    /**
39
     * @return Form
40
     */
41
    public function AddForm()
42
    {
43
        $pageTypes = array();
44
        foreach ($this->PageTypes() as $type) {
45
            $html = sprintf(
46
                '<span class="page-icon class-%s"></span><span class="title">%s</span><span class="form__field-description">%s</span>',
47
                $type->getField('ClassName'),
48
                $type->getField('AddAction'),
49
                $type->getField('Description')
50
            );
51
            $pageTypes[$type->getField('ClassName')] = DBField::create_field('HTMLFragment', $html);
52
        }
53
        // Ensure generic page type shows on top
54
        if (isset($pageTypes['Page'])) {
55
            $pageTitle = $pageTypes['Page'];
56
            $pageTypes = array_merge(array('Page' => $pageTitle), $pageTypes);
57
        }
58
59
        $numericLabelTmpl = '<span class="step-label"><span class="flyout">Step %d. </span><span class="title">%s</span></span>';
60
61
        $topTitle = _t('SilverStripe\\CMS\\Controllers\\CMSPageAddController.ParentMode_top', 'Top level');
62
        $childTitle = _t('SilverStripe\\CMS\\Controllers\\CMSPageAddController.ParentMode_child', 'Under another page');
63
64
        $fields = new FieldList(
65
            $parentModeField = new SelectionGroup(
66
                "ParentModeField",
67
                array(
68
                    new SelectionGroup_Item(
69
                        "top",
70
                        null,
71
                        $topTitle
72
                    ),
73
                    new SelectionGroup_Item(
74
                        'child',
75
                        $parentField = new TreeDropdownField(
76
                            "ParentID",
77
                            "",
78
                            'SilverStripe\\CMS\\Model\\SiteTree',
79
                            'ID',
80
                            'TreeTitle'
81
                        ),
82
                        $childTitle
83
                    )
84
                )
85
            ),
86
            new LiteralField(
87
                'RestrictedNote',
88
                sprintf(
89
                    '<p class="message notice message-restricted">%s</p>',
90
                    _t(
91
                        'SilverStripe\\CMS\\Controllers\\CMSMain.AddPageRestriction',
92
                        'Note: Some page types are not allowed for this selection'
93
                    )
94
                )
95
            ),
96
            $typeField = new OptionsetField(
97
                "PageType",
98
                DBField::create_field(
99
                    'HTMLFragment',
100
                    sprintf($numericLabelTmpl, 2, _t('SilverStripe\\CMS\\Controllers\\CMSMain.ChoosePageType', 'Choose page type'))
101
                ),
102
                $pageTypes,
103
                'Page'
104
            )
105
        );
106
107
        $parentModeField->setTitle(DBField::create_field(
108
            'HTMLFragment',
109
            sprintf($numericLabelTmpl, 1, _t('SilverStripe\\CMS\\Controllers\\CMSMain.ChoosePageParentMode', 'Choose where to create this page'))
110
        ));
111
112
        $parentField->setSearchFunction(function ($sourceObject, $labelField, $search) {
113
            return DataObject::get($sourceObject)
114
                ->filterAny([
115
                    'MenuTitle:PartialMatch' => $search,
116
                    'Title:PartialMatch' => $search,
117
                ]);
118
        });
119
120
        // TODO Re-enable search once it allows for HTML title display,
121
        // see http://open.silverstripe.org/ticket/7455
122
        // $parentField->setShowSearch(true);
123
124
        $parentModeField->addExtraClass('parent-mode');
125
126
        // CMSMain->currentPageID() automatically sets the homepage,
127
        // which we need to counteract in the default selection (which should default to root, ID=0)
128
        if ($parentID = $this->getRequest()->getVar('ParentID')) {
129
            $parentModeField->setValue('child');
130
            $parentField->setValue((int)$parentID);
131
        } else {
132
            $parentModeField->setValue('top');
133
        }
134
135
        $actions = new FieldList(
136
            FormAction::create("doAdd", _t('SilverStripe\\CMS\\Controllers\\CMSMain.Create', "Create"))
137
                ->addExtraClass('btn-primary font-icon-plus-circled')
138
                ->setUseButtonTag(true),
139
            FormAction::create("doCancel", _t('SilverStripe\\CMS\\Controllers\\CMSMain.Cancel', "Cancel"))
140
                ->addExtraClass('btn-secondary')
141
                ->setUseButtonTag(true)
142
        );
143
144
        $this->extend('updatePageOptions', $fields);
145
146
        $negotiator = $this->getResponseNegotiator();
147
        $form = Form::create(
148
            $this,
149
            "AddForm",
150
            $fields,
151
            $actions
152
        )->setHTMLID('Form_AddForm')->setStrictFormMethodCheck(false);
153
        $form->setAttribute('data-hints', $this->SiteTreeHints());
154
        $form->setAttribute('data-childfilter', $this->Link('childfilter'));
155 View Code Duplication
        $form->setValidationResponseCallback(function (ValidationResult $errors) use ($negotiator, $form) {
156
            $request = $this->getRequest();
157
            if ($request->isAjax() && $negotiator) {
158
                $result = $form->forTemplate();
159
                return $negotiator->respond($request, array(
160
                    'CurrentForm' => function () use ($result) {
161
                        return $result;
162
                    }
163
                ));
164
            }
165
            return null;
166
        });
167
        $form->addExtraClass('flexbox-area-grow fill-height cms-add-form cms-content cms-edit-form ' . $this->BaseCSSClasses());
168
        $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
169
170
        return $form;
171
    }
172
173
    /**
174
     * @param array $data
175
     * @param Form $form
176
     * @return HTTPResponse
177
     */
178
    public function doAdd($data, $form)
179
    {
180
        $className = isset($data['PageType']) ? $data['PageType'] : "Page";
181
        $parentID = isset($data['ParentID']) ? (int)$data['ParentID'] : 0;
182
183
        if (!$parentID && isset($data['Parent'])) {
184
            $page = SiteTree::get_by_link($data['Parent']);
185
            if ($page) {
186
                $parentID = $page->ID;
187
            }
188
        }
189
190
        if (is_numeric($parentID) && $parentID > 0) {
191
            $parentObj = SiteTree::get()->byID($parentID);
192
        } else {
193
            $parentObj = null;
194
        }
195
196
        if (!$parentObj || !$parentObj->ID) {
197
            $parentID = 0;
198
        }
199
200
        if (!singleton($className)->canCreate(Security::getCurrentUser(), array('Parent' => $parentObj))) {
201
            return Security::permissionFailure($this);
202
        }
203
204
        $record = $this->getNewItem("new-$className-$parentID", false);
205
        $this->extend('updateDoAdd', $record, $form);
206
        $record->write();
207
208
        $editController = CMSPageEditController::singleton();
209
        $editController->setRequest($this->getRequest());
210
        $editController->setCurrentPageID($record->ID);
211
212
        $session = $this->getRequest()->getSession();
213
        $session->set(
214
            "FormInfo.Form_EditForm.formError.message",
215
            _t('SilverStripe\\CMS\\Controllers\\CMSMain.PageAdded', 'Successfully created page')
216
        );
217
        $session->set("FormInfo.Form_EditForm.formError.type", 'good');
218
219
        return $this->redirect(Controller::join_links($editController->Link('show'), $record->ID));
220
    }
221
222
    public function doCancel($data, $form)
0 ignored issues
show
The parameter $data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
The parameter $form is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
223
    {
224
        return $this->redirect(CMSMain::singleton()->Link());
225
    }
226
}
227