GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Pull Request — master (#2835)
by
unknown
06:01
created

contentBlueprintsSections::__viewEdit()   F

Complexity

Conditions 33
Paths > 20000

Size

Total Lines 222
Code Lines 143

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 33
eloc 143
c 0
b 0
f 0
nc 57600
nop 0
dl 0
loc 222
rs 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @package content
4
 */
5
6
/**
7
 * This page controls the creation and maintenance of Symphony
8
 * Sections through the Section Index and Section Editor.
9
 */
10
11
class contentBlueprintsSections extends AdministrationPage
12
{
13
    public $_errors = array();
14
15
    public function build(array $context = array())
16
    {
17
        if (isset($context[1])) {
18
            $section_id = $context[1];
19
            $context['associations'] = array(
20
                'parent' => SectionManager::fetchParentAssociations($section_id),
21
                'child' => SectionManager::fetchChildAssociations($section_id)
22
            );
23
        }
24
25
        return parent::build($context);
0 ignored issues
show
Bug introduced by
Are you sure the usage of parent::build($context) targeting AdministrationPage::build() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
26
    }
27
28
    public function __viewIndex()
29
    {
30
        $this->setPageType('table');
31
        $this->setTitle(__('%1$s &ndash; %2$s', array(__('Sections'), __('Symphony'))));
32
        $this->appendSubheading(__('Sections'), Widget::Anchor(__('Create New'), Administration::instance()->getCurrentPageURL().'new/', __('Create a section'), 'create button', null, array('accesskey' => 'c')));
33
34
        $sections = (new SectionManager)->select()->sort('sortorder')->execute()->rows();
35
36
        $aTableHead = array(
37
            array(__('Name'), 'col'),
38
            array(__('Entries'), 'col'),
39
            array(__('Navigation Group'), 'col')
40
        );
41
42
        $aTableBody = array();
43
44
        if (!is_array($sections) || empty($sections)) {
0 ignored issues
show
introduced by
The condition is_array($sections) is always true.
Loading history...
45
            $aTableBody = array(
46
                Widget::TableRow(array(Widget::TableData(__('None found.'), 'inactive', null, count($aTableHead))), 'odd')
47
            );
48
        } else {
49
            foreach ($sections as $s) {
50
                $entry_count = (new EntryManager)
51
                    ->select()
52
                    ->count()
53
                    ->section($s->get('id'))
54
                    ->execute()
55
                    ->variable(0);
56
57
                // Setup each cell
58
                $td1 = Widget::TableData(Widget::Anchor(General::sanitize($s->get('name')), Administration::instance()->getCurrentPageURL() . 'edit/' . $s->get('id') .'/', null, 'content'));
59
                $td1->appendChild(Widget::Label(__('Select Section %s', array(General::sanitize($s->get('name')))), null, 'accessible', null, array(
60
                    'for' => 'section-' . $s->get('id')
61
                )));
62
                $td1->appendChild(Widget::Input('items['.$s->get('id').']', $s->get('modification_date'), 'checkbox', array(
63
                    'id' => 'section-' . $s->get('id')
64
                )));
65
66
                $td2 = Widget::TableData(Widget::Anchor((string)$entry_count, SYMPHONY_URL . '/publish/' . $s->get('handle') . '/'));
0 ignored issues
show
Bug introduced by
The constant SYMPHONY_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
67
                $td3 = Widget::TableData(General::sanitize($s->get('navigation_group')));
68
69
                // Create row
70
                $tr = Widget::TableRow(array($td1, $td2, $td3));
71
72
                if ($s->get('hidden') === 'yes') {
73
                    $tr->setAttribute('class', 'inactive');
74
                }
75
76
                $aTableBody[] = $tr;
77
            }
78
        }
79
80
        $table = Widget::Table(
81
            Widget::TableHead($aTableHead),
82
            null,
83
            Widget::TableBody($aTableBody),
84
            'orderable selectable',
85
            null,
86
            array('role' => 'directory', 'aria-labelledby' => 'symphony-subheading', 'data-interactive' => 'data-interactive')
87
        );
88
89
        $this->Form->appendChild($table);
90
91
        $version = new XMLElement('p', 'Symphony ' . Symphony::Configuration()->get('version', 'symphony'), array(
92
            'id' => 'version'
93
        ));
94
95
        $this->Form->appendChild($version);
96
97
        $tableActions = new XMLElement('div');
98
        $tableActions->setAttribute('class', 'actions');
99
100
        $options = array(
101
            array(null, false, __('With Selected...')),
102
            array('delete', false, __('Delete'), 'confirm', null, array(
103
                'data-message' => __('Are you sure you want to delete the selected sections?')
104
            )),
105
            array('delete-entries', false, __('Delete Entries'), 'confirm', null, array(
106
                'data-message' => __('Are you sure you want to delete all entries in the selected sections?')
107
            ))
108
        );
109
110
        if (is_array($sections) && !empty($sections)) {
111
            $index = 3;
112
            $options[$index] = array('label' => __('Set navigation group'), 'options' => array());
113
114
            $groups = array();
115
116
            foreach ($sections as $s) {
117
                if (in_array($s->get('navigation_group'), $groups)) {
118
                    continue;
119
                }
120
121
                $groups[] = $s->get('navigation_group');
122
123
                $value = 'set-navigation-group-' . urlencode($s->get('navigation_group'));
124
                $options[$index]['options'][] = array($value, false, General::sanitize($s->get('navigation_group')));
125
            }
126
        }
127
128
        /**
129
         * Allows an extension to modify the existing options for this page's
130
         * With Selected menu. If the `$options` parameter is an empty array,
131
         * the 'With Selected' menu will not be rendered.
132
         *
133
         * @delegate AddCustomActions
134
         * @since Symphony 2.3.2
135
         * @param string $context
136
         * '/blueprints/sections/'
137
         * @param array $options
138
         *  An array of arrays, where each child array represents an option
139
         *  in the With Selected menu. Options should follow the same format
140
         *  expected by `Widget::__SelectBuildOption`. Passed by reference.
141
         */
142
        Symphony::ExtensionManager()->notifyMembers('AddCustomActions', '/blueprints/sections/', array(
143
            'options' => &$options
144
        ));
145
146
        if (!empty($options)) {
147
            $tableActions->appendChild(Widget::Apply($options));
148
            $this->Form->appendChild($tableActions);
149
        }
150
    }
151
152
    public function __viewNew()
153
    {
154
        $this->setPageType('form');
155
        $this->setTitle(__('%1$s &ndash; %2$s', array(__('Sections'), __('Symphony'))));
156
        $this->appendSubheading(__('Untitled'));
157
        $this->insertBreadcrumbs(array(
158
            Widget::Anchor(__('Sections'), SYMPHONY_URL . '/blueprints/sections/'),
0 ignored issues
show
Bug introduced by
The constant SYMPHONY_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
159
        ));
160
161
        $types = array();
162
163
        $fields = (isset($_POST['fields']) && is_array($_POST['fields'])) ? $_POST['fields'] : array();
164
        $meta = (isset($_POST['meta']) && is_array($_POST['meta'])) ? $_POST['meta'] : array('name'=>null);
165
166
        $formHasErrors = (is_array($this->_errors) && !empty($this->_errors));
167
168
        if ($formHasErrors) {
169
            $this->pageAlert(
170
                __('An error occurred while processing this form. See below for details.'),
171
                Alert::ERROR
172
            );
173
        }
174
175
        $showEmptyTemplate = (is_array($fields) && !empty($fields) ? false : true);
176
177
        if (!$showEmptyTemplate) {
178
            ksort($fields);
179
        }
180
181
        // Set navigation group, if not already set
182
        if (!isset($meta['navigation_group'])) {
183
            $meta['navigation_group'] = (isset($this->_navigation[0]['name']) ? $this->_navigation[0]['name'] : __('Content'));
184
        }
185
186
        $fieldset = new XMLElement('fieldset');
187
        $fieldset->setAttribute('class', 'settings');
188
        $fieldset->appendChild(new XMLElement('legend', __('Essentials')));
189
190
        $namediv = new XMLElement('div', null, array('class' => 'column'));
191
192
        $label = Widget::Label(__('Name'));
193
        $label->appendChild(Widget::Input('meta[name]', (isset($meta['name']) ? General::sanitize($meta['name']) : null)));
194
195
        if (isset($this->_errors['name'])) {
196
            $namediv->appendChild(Widget::Error($label, $this->_errors['name']));
197
        } else {
198
            $namediv->appendChild($label);
199
        }
200
201
        $fieldset->appendChild($namediv);
202
203
        $div = new XMLElement('div', null, array('class' => 'two columns'));
204
205
        $handlediv = new XMLElement('div', null, array('class' => 'column'));
206
207
        $label = Widget::Label(__('Handle'));
208
        $label->appendChild(Widget::Input('meta[handle]', (isset($meta['handle']) ? General::sanitize($meta['handle']) : null)));
209
210
        if (isset($this->_errors['handle'])) {
211
            $handlediv->appendChild(Widget::Error($label, $this->_errors['handle']));
212
        } else {
213
            $handlediv->appendChild($label);
214
        }
215
216
        $div->appendChild($handlediv);
217
218
        $navgroupdiv = new XMLElement('div', null, array('class' => 'column'));
219
220
        $sections = (new SectionManager)->select()->sort('sortorder')->execute()->rows();
221
        $label = Widget::Label(__('Navigation Group'));
222
        $label->appendChild(Widget::Input('meta[navigation_group]', (isset($meta['navigation_group']) ? General::sanitize($meta['navigation_group']) : null)));
223
224
        if (isset($this->_errors['navigation_group'])) {
225
            $navgroupdiv->appendChild(Widget::Error($label, $this->_errors['navigation_group']));
226
        } else {
227
            $navgroupdiv->appendChild($label);
228
        }
229
230
        if (is_array($sections) && !empty($sections)) {
231
            $ul = new XMLElement('ul', null, array('class' => 'tags singular', 'data-interactive' => 'data-interactive'));
232
            $groups = array();
233
234
            foreach ($sections as $s) {
235
                if (in_array($s->get('navigation_group'), $groups)) {
236
                    continue;
237
                }
238
239
                $ul->appendChild(new XMLElement('li', General::sanitize($s->get('navigation_group'))));
240
                $groups[] = $s->get('navigation_group');
241
            }
242
243
            $navgroupdiv->appendChild($ul);
244
        }
245
246
        $div->appendChild($navgroupdiv);
247
        $fieldset->appendChild($div);
248
        $this->Form->appendChild($fieldset);
249
250
        $this->addSectionOptions($meta);
251
252
        $fieldset = new XMLElement('fieldset');
253
        $fieldset->setAttribute('class', 'settings');
254
255
        $legend = new XMLElement('legend', __('Fields'));
256
        $legend->setAttribute('id', 'fields-legend');
257
        $fieldset->appendChild($legend);
258
259
        $div = new XMLElement('div', null, array('class' => 'frame', 'id' => 'fields-duplicator'));
260
261
        $ol = new XMLElement('ol');
262
        $ol->setAttribute('data-add', __('Add field'));
263
        $ol->setAttribute('data-remove', __('Remove field'));
264
265
        if (!$showEmptyTemplate) {
266
            foreach ($fields as $position => $data) {
267
                if ($input = FieldManager::create($data['type'])) {
268
                    $input->setArray($data);
269
270
                    $wrapper = new XMLElement('li');
271
272
                    $input->set('sortorder', $position);
273
                    $input->displaySettingsPanel($wrapper, (isset($this->_errors[$position]) ? $this->_errors[$position] : null));
274
                    $ol->appendChild($wrapper);
275
                }
276
            }
277
        }
278
279
        foreach (FieldManager::listAll() as $type) {
280
            if ($type = FieldManager::create($type)) {
281
                $types[] = $type;
282
            }
283
        }
284
285
        uasort($types, function($a, $b) {
286
            return strnatcasecmp($a->_name, $b->_name);
287
        });
288
289
        foreach ($types as $type) {
290
            $defaults = array();
291
292
            $type->findDefaults($defaults);
293
            $type->setArray($defaults);
294
295
            $wrapper = new XMLElement('li');
296
            $wrapper->setAttribute('class', 'template field-' . $type->handle() . ($type->mustBeUnique() ? ' unique' : null));
297
            $wrapper->setAttribute('data-type', $type->handle());
298
299
            $type->set('sortorder', '-1');
300
            $type->displaySettingsPanel($wrapper);
301
302
            $ol->appendChild($wrapper);
303
        }
304
305
        $div->appendChild($ol);
306
        $fieldset->appendChild($div);
307
308
        $this->Form->appendChild($fieldset);
309
310
        $div = new XMLElement('div');
311
        $div->setAttribute('class', 'actions');
312
        $div->appendChild(Widget::Input('action[save]', __('Create Section'), 'submit', array('accesskey' => 's')));
313
314
        $this->Form->appendChild($div);
315
    }
316
317
    public function __viewEdit()
318
    {
319
        $section_id = $this->_context[1];
320
        $section = (new SectionManager)->select()->section($section_id)->execute()->next();
321
322
        if (!$section) {
0 ignored issues
show
introduced by
$section is of type Section, thus it always evaluated to true.
Loading history...
323
            Administration::instance()->throwCustomError(
324
                __('The Section, %s, could not be found.', array($section_id)),
325
                __('Unknown Section'),
326
                Page::HTTP_STATUS_NOT_FOUND
327
            );
328
        }
329
330
        $meta = $section->get();
331
        $section_id = $meta['id'];
332
        $types = array();
333
        $canonical_link = '/blueprints/sections/edit/' . $section_id . '/';
334
335
        $formHasErrors = (is_array($this->_errors) && !empty($this->_errors));
336
337
        if ($formHasErrors) {
338
            $this->pageAlert(
339
                __('An error occurred while processing this form. See below for details.'),
340
                Alert::ERROR
341
            );
342
343
            // These alerts are only valid if the form doesn't have errors
344
        } elseif (isset($this->_context[2])) {
345
            $time = Widget::Time();
346
347
            switch ($this->_context[2]) {
348
                case 'saved':
349
                    $message = __('Section updated at %s.', array($time->generate()));
350
                    break;
351
                case 'created':
352
                    $message = __('Section created at %s.', array($time->generate()));
353
            }
354
355
            $this->pageAlert(
356
                $message
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $message does not seem to be defined for all execution paths leading up to this point.
Loading history...
357
                . ' <a href="' . SYMPHONY_URL . '/blueprints/sections/new/" accesskey="c">'
0 ignored issues
show
Bug introduced by
The constant SYMPHONY_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
358
                . __('Create another?')
359
                . '</a> <a href="' . SYMPHONY_URL . '/blueprints/sections/" accesskey="a">'
360
                . __('View all Sections')
361
                . '</a>',
362
                Alert::SUCCESS
363
            );
364
        }
365
366
        if (isset($_POST['fields'])) {
367
            $fields = array();
368
            if (is_array($_POST['fields']) && !empty($_POST['fields'])) {
369
                foreach ($_POST['fields'] as $position => $data) {
370
                    if ($fields[$position] = FieldManager::create($data['type'])) {
371
                        $fields[$position]->setArray($data);
372
                        $fields[$position]->set('sortorder', $position);
373
                    }
374
                }
375
            }
376
            $timestamp = isset($_POST['action']['timestamp'])
377
                ? $_POST['action']['timestamp']
378
                : $section->get('modification_date');
379
        } else {
380
            $fields = (new FieldManager)->select()->section($section_id)->execute()->rows();
381
            $fields = array_values($fields);
382
            $timestamp = $section->get('modification_date');
383
        }
384
385
        if (isset($_POST['meta'])) {
386
            $meta = $_POST['meta'];
387
            if ($meta['name'] == '') {
388
                $meta['name'] = $section->get('name');
389
            }
390
        }
391
392
        $this->setPageType('form');
393
        $this->setTitle(__('%1$s &ndash; %2$s &ndash; %3$s', array(General::sanitize($meta['name']), __('Sections'), __('Symphony'))));
394
        $this->addElementToHead(new XMLElement('link', null, array(
395
            'rel' => 'canonical',
396
            'href' => SYMPHONY_URL . $canonical_link,
397
        )));
398
        $this->appendSubheading(General::sanitize($meta['name']),
399
            Widget::Anchor(__('View Entries'), SYMPHONY_URL . '/publish/' . $section->get('handle') . '/', __('View Section Entries'), 'button')
0 ignored issues
show
Bug introduced by
Are you sure $section->get('handle') of type string|array can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

399
            Widget::Anchor(__('View Entries'), SYMPHONY_URL . '/publish/' . /** @scrutinizer ignore-type */ $section->get('handle') . '/', __('View Section Entries'), 'button')
Loading history...
400
        );
401
        $this->insertBreadcrumbs(array(
402
            Widget::Anchor(__('Sections'), SYMPHONY_URL . '/blueprints/sections/'),
403
        ));
404
405
        $fieldset = new XMLElement('fieldset');
406
        $fieldset->setAttribute('class', 'settings');
407
        $fieldset->appendChild(new XMLElement('legend', __('Essentials')));
408
409
        $namediv = new XMLElement('div', null, array('class' => 'column'));
410
411
        $label = Widget::Label(__('Name'));
412
        $label->appendChild(Widget::Input('meta[name]', (isset($meta['name']) ? General::sanitize($meta['name']) : null)));
413
414
        if (isset($this->_errors['name'])) {
415
            $namediv->appendChild(Widget::Error($label, $this->_errors['name']));
416
        } else {
417
            $namediv->appendChild($label);
418
        }
419
420
        $fieldset->appendChild($namediv);
421
422
        $div = new XMLElement('div', null, array('class' => 'two columns'));
423
424
        $handlediv = new XMLElement('div', null, array('class' => 'column'));
425
426
        $label = Widget::Label(__('Handle'));
427
        $label->appendChild(Widget::Input('meta[handle]', (isset($meta['handle']) ? General::sanitize($meta['handle']) : null)));
428
429
        if (isset($this->_errors['handle'])) {
430
            $handlediv->appendChild(Widget::Error($label, $this->_errors['handle']));
431
        } else {
432
            $handlediv->appendChild($label);
433
        }
434
435
        $div->appendChild($handlediv);
436
437
        $navgroupdiv = new XMLElement('div', null, array('class' => 'column'));
438
439
        $sections = (new SectionManager)->select()->sort('sortorder')->execute()->rows();
440
        $label = Widget::Label(__('Navigation Group'));
441
        $label->appendChild(Widget::Input('meta[navigation_group]', General::sanitize($meta['navigation_group'])));
442
443
        if (isset($this->_errors['navigation_group'])) {
444
            $navgroupdiv->appendChild(Widget::Error($label, $this->_errors['navigation_group']));
445
        } else {
446
            $navgroupdiv->appendChild($label);
447
        }
448
449
        if (is_array($sections) && !empty($sections)) {
450
            $ul = new XMLElement('ul', null, array('class' => 'tags singular', 'data-interactive' => 'data-interactive'));
451
            $groups = array();
452
453
            foreach ($sections as $s) {
454
                if (in_array($s->get('navigation_group'), $groups)) {
455
                    continue;
456
                }
457
458
                $ul->appendChild(new XMLElement('li', General::sanitize($s->get('navigation_group'))));
459
                $groups[] = $s->get('navigation_group');
460
            }
461
462
            $navgroupdiv->appendChild($ul);
463
        }
464
465
        $div->appendChild($navgroupdiv);
466
        $fieldset->appendChild($div);
467
        $this->Form->appendChild($fieldset);
468
469
        $this->addSectionOptions($meta);
470
471
        $fieldset = new XMLElement('fieldset');
472
        $fieldset->setAttribute('class', 'settings');
473
474
        $legend = new XMLElement('legend', __('Fields'));
475
        $legend->setAttribute('id', 'fields-legend');
476
        $fieldset->appendChild($legend);
477
478
        $div = new XMLElement('div', null, array('class' => 'frame', 'id' => 'fields-duplicator'));
479
480
        $ol = new XMLElement('ol');
481
        $ol->setAttribute('data-add', __('Add field'));
482
        $ol->setAttribute('data-remove', __('Remove field'));
483
484
        if (is_array($fields) && !empty($fields)) {
485
            foreach ($fields as $position => $field) {
486
                $wrapper = new XMLElement('li', null, array('class' => 'field-' . $field->handle() . ($field->mustBeUnique() ? ' unique' : null)));
487
                $wrapper->setAttribute('data-type', $field->handle());
488
489
                $field->set('sortorder', $position);
490
                $field->displaySettingsPanel($wrapper, (isset($this->_errors[$position]) ? $this->_errors[$position] : null));
491
                $ol->appendChild($wrapper);
492
            }
493
        }
494
495
        foreach (FieldManager::listAll() as $type) {
496
            if ($type = FieldManager::create($type)) {
497
                array_push($types, $type);
498
            }
499
        }
500
501
        uasort($types, function($a, $b) {
502
            return strnatcasecmp($a->_name, $b->_name);
503
        });
504
505
        foreach ($types as $type) {
506
            $defaults = array();
507
508
            $type->findDefaults($defaults);
509
            $type->setArray($defaults);
510
511
            $wrapper = new XMLElement('li');
512
513
            $wrapper->setAttribute('class', 'template field-' . $type->handle() . ($type->mustBeUnique() ? ' unique' : null));
514
            $wrapper->setAttribute('data-type', $type->handle());
515
516
            $type->set('sortorder', '-1');
517
            $type->displaySettingsPanel($wrapper);
518
519
            $ol->appendChild($wrapper);
520
        }
521
522
        $div->appendChild($ol);
523
        $fieldset->appendChild($div);
524
525
        $this->Form->appendChild($fieldset);
526
527
        $div = new XMLElement('div');
528
        $div->setAttribute('class', 'actions');
529
        $div->appendChild(Widget::Input('action[save]', __('Save Changes'), 'submit', array('accesskey' => 's')));
530
531
        $button = new XMLElement('button', __('Delete'));
532
        $button->setAttributeArray(array('name' => 'action[delete]', 'class' => 'button confirm delete', 'title' => __('Delete this section'), 'type' => 'submit', 'accesskey' => 'd', 'data-message' => __('Are you sure you want to delete this section?')));
533
        $div->appendChild($button);
534
535
        $div->appendChild(Widget::Input('action[timestamp]', $timestamp, 'hidden'));
536
        $div->appendChild(Widget::Input('action[ignore-timestamp]', 'yes', 'checkbox', array('class' => 'irrelevant')));
537
538
        $this->Form->appendChild($div);
539
    }
540
541
    public function __actionIndex()
542
    {
543
        $checked = (is_array($_POST['items'])) ? array_keys($_POST['items']) : null;
544
545
        if (is_array($checked) && !empty($checked)) {
546
            /**
547
             * Extensions can listen for any custom actions that were added
548
             * through `AddCustomPreferenceFieldsets` or `AddCustomActions`
549
             * delegates.
550
             *
551
             * @delegate CustomActions
552
             * @since Symphony 2.3.2
553
             * @param string $context
554
             *  '/blueprints/sections/'
555
             * @param array $checked
556
             *  An array of the selected rows. The value is usually the ID of the
557
             *  the associated object.
558
             */
559
            Symphony::ExtensionManager()->notifyMembers('CustomActions', '/blueprints/sections/', array(
560
                'checked' => $checked
561
            ));
562
563
            if ($_POST['with-selected'] == 'delete') {
564
                /**
565
                 * Just prior to calling the Section Manager's delete function
566
                 *
567
                 * @delegate SectionPreDelete
568
                 * @since Symphony 2.2
569
                 * @param string $context
570
                 * '/blueprints/sections/'
571
                 * @param array $section_ids
572
                 *  An array of Section ID's passed by reference
573
                 */
574
                Symphony::ExtensionManager()->notifyMembers('SectionPreDelete', '/blueprints/sections/', array('section_ids' => &$checked));
575
576
                foreach ($checked as $section_id) {
577
                    SectionManager::delete($section_id);
578
                }
579
580
                redirect(SYMPHONY_URL . '/blueprints/sections/');
0 ignored issues
show
Bug introduced by
The constant SYMPHONY_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
581
            } elseif ($_POST['with-selected'] == 'delete-entries') {
582
                foreach ($checked as $section_id) {
583
                    $entries = (new EntryManager)
584
                        ->select()
585
                        ->section($section_id)
586
                        ->disableDefaultSort()
587
                        ->execute()
588
                        ->rows();
589
590
                    $entry_ids = array();
591
592
                    foreach ($entries as $entry) {
593
                        $entry_ids[] = $entry['id'];
594
                    }
595
596
                    /**
597
                     * Prior to deletion of entries.
598
                     *
599
                     * @delegate Delete
600
                     * @param string $context
601
                     * '/publish/'
602
                     * @param array $entry_id
603
                     *  An array of Entry ID's that are about to be deleted, passed by reference
604
                     */
605
                    Symphony::ExtensionManager()->notifyMembers('Delete', '/publish/', array('entry_id' => &$entry_ids));
606
607
                    EntryManager::delete($entry_ids, $section_id);
608
                }
609
610
                redirect(SYMPHONY_URL . '/blueprints/sections/');
611
            } elseif (preg_match('/^set-navigation-group-/', $_POST['with-selected'])) {
612
                $navigation_group = preg_replace('/^set-navigation-group-/', null, $_POST['with-selected']);
613
614
                foreach ($checked as $section_id) {
615
                    SectionManager::edit($section_id, array(
616
                        'navigation_group' => urldecode($navigation_group),
617
                        'modification_author_id' => Symphony::Author()->get('id'),
618
                    ));
619
                }
620
621
                redirect(SYMPHONY_URL . '/blueprints/sections/');
622
            }
623
        }
624
    }
625
626
    public function __actionNew()
627
    {
628
        if (is_array($_POST['action']) && array_key_exists('save', $_POST['action'])) {
629
            $canProceed = true;
630
            $edit = ($this->_context[0] == "edit");
631
            $this->_errors = array();
632
633
            $fields = isset($_POST['fields']) ? $_POST['fields'] : array();
634
            $meta = $_POST['meta'];
635
636
            if ($edit) {
637
                $section_id = $this->_context[1];
638
                $existing_section = (new SectionManager)->select()->section($section_id)->execute()->next();
639
                $canProceed = $this->validateTimestamp($section_id, true);
640
                if (!$canProceed) {
641
                    $this->addTimestampValidationPageAlert($this->_errors['timestamp'], $existing_section, 'save');
642
                }
643
            }
644
645
            // Check handle to ensure it is unique
646
            $meta['handle'] = $_POST['meta']['handle'] = Lang::createHandle((isset($meta['handle']) && !empty($meta['handle']))
647
                ? $meta['handle']
648
                : $meta['name']);
649
650
            // Check to ensure all the required section fields are filled
651
            if (!isset($meta['name']) || strlen(trim($meta['name'])) == 0) {
652
                $this->_errors['name'] = __('This is a required field.');
653
                $canProceed = false;
654
655
                // Check for duplicate section handle during edit
656
            } elseif ($edit) {
657
                $s = SectionManager::fetchIDFromHandle(Lang::createHandle($meta['handle']));
658
659
                if (
660
                    $meta['handle'] !== $existing_section->get('handle')
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $existing_section does not seem to be defined for all execution paths leading up to this point.
Loading history...
661
                    && $s !== 0 && $s !== $section_id
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $section_id does not seem to be defined for all execution paths leading up to this point.
Loading history...
662
                ) {
663
                    $this->_errors['handle'] = __('A Section with the handle %s already exists', array('<code>' . $meta['handle'] . '</code>'));
664
                    $canProceed = false;
665
                }
666
667
                // Existing section during creation
668
            } elseif (SectionManager::fetchIDFromHandle(Lang::createHandle($meta['handle'])) !== 0) {
669
                $this->_errors['handle'] = __('A Section with the handle %s already exists', array('<code>' . $meta['handle'] . '</code>'));
670
                $canProceed = false;
671
            }
672
673
            // Check to ensure all the required section fields are filled
674
            if (!isset($meta['navigation_group']) || strlen(trim($meta['navigation_group'])) == 0) {
675
                $this->_errors['navigation_group'] = __('This is a required field.');
676
                $canProceed = false;
677
            }
678
679
            // Basic custom field checking
680
            if (is_array($fields) && !empty($fields)) {
681
                // Check for duplicate CF names
682
                if ($canProceed) {
683
                    $name_list = array();
684
685
                    foreach ($fields as $position => $data) {
686
                        if (trim($data['element_name']) == '') {
687
                            $data['element_name'] = $fields[$position]['element_name'] = $_POST['fields'][$position]['element_name'] = Lang::createHandle($data['label'], 255, '-', false, true, array('@^[\d-]+@i' => ''));
688
                        }
689
690
                        if (trim($data['element_name']) != '' && in_array($data['element_name'], $name_list)) {
691
                            $this->_errors[$position] = array('element_name' => __('A field with this handle already exists. All handle must be unique.'));
692
                            $canProceed = false;
693
                            break;
694
                        }
695
696
                        $name_list[] = $data['element_name'];
697
                    }
698
                }
699
700
                if ($canProceed) {
701
                    $unique = array();
702
703
                    foreach ($fields as $position => $data) {
704
                        $field = FieldManager::create($data['type']);
705
                        $field->setFromPOST($data);
706
707
                        if (isset($existing_section)) {
708
                            $field->set('parent_section', $existing_section->get('id'));
709
                        }
710
711
                        if ($field->mustBeUnique() && !in_array($field->get('type'), $unique)) {
712
                            $unique[] = $field->get('type');
713
                        } elseif ($field->mustBeUnique() && in_array($field->get('type'), $unique)) {
714
                            // Warning. cannot have 2 of this field!
715
                            $canProceed = false;
716
                            $this->_errors[$position] = array('label' => __('There is already a field of type %s. There can only be one per section.', array('<code>' . $field->handle() . '</code>')));
717
                        }
718
719
                        $errors = array();
720
721
                        if (Field::__OK__ != $field->checkFields($errors, false) && !empty($errors)) {
722
                            $this->_errors[$position] = $errors;
723
                            $canProceed = false;
724
                        }
725
                    }
726
                }
727
            }
728
729
            if ($canProceed) {
730
                // If we are creating a new Section
731
                if (!$edit) {
732
                    $meta['sortorder'] = SectionManager::fetchNextSortOrder();
733
734
                    /**
735
                     * Just prior to saving the Section settings. Use with caution as
736
                     * there is no additional processing to ensure that Field's or Section's
737
                     * are unique.
738
                     *
739
                     * @delegate SectionPreCreate
740
                     * @since Symphony 2.2
741
                     * @param string $context
742
                     * '/blueprints/sections/'
743
                     * @param array $meta
744
                     *  The section's settings, passed by reference
745
                     * @param array $fields
746
                     *  An associative array of the fields that will be saved to this
747
                     *  section with the key being the position in the Section Editor
748
                     *  and the value being a Field object, passed by reference
749
                     */
750
                    Symphony::ExtensionManager()->notifyMembers('SectionPreCreate', '/blueprints/sections/', array('meta' => &$meta, 'fields' => &$fields));
751
752
                    $meta['author_id'] = Symphony::Author()->get('id');
753
                    $meta['modification_author_id'] = $meta['author_id'];
754
755
                    if (!$section_id = SectionManager::add($meta)) {
756
                        $this->pageAlert(__('An unknown database occurred while attempting to create the section.'), Alert::ERROR);
757
                    }
758
759
                    // We are editing a Section
760
                } else {
761
762
                    /**
763
                     * Just prior to updating the Section settings. Use with caution as
764
                     * there is no additional processing to ensure that Field's or Section's
765
                     * are unique.
766
                     *
767
                     * @delegate SectionPreEdit
768
                     * @since Symphony 2.2
769
                     * @param string $context
770
                     * '/blueprints/sections/'
771
                     * @param integer $section_id
772
                     *  The Section ID that is about to be edited.
773
                     * @param array $meta
774
                     *  The section's settings, passed by reference
775
                     * @param array $fields
776
                     *  An associative array of the fields that will be saved to this
777
                     *  section with the key being the position in the Section Editor
778
                     *  and the value being a Field object, passed by reference
779
                     */
780
                    Symphony::ExtensionManager()->notifyMembers('SectionPreEdit', '/blueprints/sections/', array('section_id' => $section_id, 'meta' => &$meta, 'fields' => &$fields));
781
782
                    $meta['modification_author_id'] = Symphony::Author()->get('id');
783
784
                    if (!SectionManager::edit($section_id, $meta)) {
785
                        $canProceed = false;
786
                        $this->pageAlert(__('An unknown database occurred while attempting to create the section.'), Alert::ERROR);
787
                    }
788
                }
789
790
                if ($section_id && $canProceed) {
791
                    if ($edit) {
792
                        // Delete missing CF's
793
                        $id_list = array();
794
795
                        if (is_array($fields) && !empty($fields)) {
796
                            foreach ($fields as $position => $data) {
797
                                if (isset($data['id'])) {
798
                                    $id_list[] = (int)$data['id'];
799
                                }
800
                            }
801
                        }
802
803
                        $missing_cfs = Symphony::Database()
804
                            ->select(['id'])
805
                            ->from('tbl_fields')
806
                            ->usePlaceholders()
807
                            ->where(['parent_section' => $section_id]);
808
809
                        if (!empty($id_list)) {
810
                            $missing_cfs->where(['id' => ['not in' => $id_list]]);
811
                        }
812
813
                        $missing_cfs = $missing_cfs->execute()->column('id');
814
815
                        if (is_array($missing_cfs) && !empty($missing_cfs)) {
816
                            foreach ($missing_cfs as $id) {
817
                                FieldManager::delete($id);
818
                            }
819
                        }
820
                    }
821
822
                    // Save each custom field
823
                    if (is_array($fields) && !empty($fields)) {
824
                        foreach ($fields as $position => $data) {
825
                            $field = FieldManager::create($data['type']);
826
                            $field->setFromPOST($data);
827
                            $field->set('sortorder', (string)$position);
828
                            $field->set('parent_section', $section_id);
829
830
                            // It is possible that the "existing" field has been deleted
831
                            // so we are dealing with an invalid id.
832
                            // First make sure the field table still exists and that
833
                            // there is a field with the corresponding id in it
834
                            $newField = !((boolean)$field->get('id') && $field->tableExists() && $field->exists());
835
                            // If the field has not been found, erase the id from $_POST
836
                            if ($newField) {
837
                                $field->set('id', false);
838
                            }
839
840
                            // Save data
841
                            $field->commit();
842
                            // Get the new id
843
                            $field_id = $field->get('id');
844
845
                            if ($field_id) {
846
                                if ($newField) {
847
                                    /**
848
                                     * After creation of a Field.
849
                                     *
850
                                     * @delegate FieldPostCreate
851
                                     * @param string $context
852
                                     * '/blueprints/sections/'
853
                                     * @param Field $field
854
                                     *  The Field object, passed by reference
855
                                     * @param array $data
856
                                     *  The settings for ths `$field`, passed by reference
857
                                     */
858
                                    Symphony::ExtensionManager()->notifyMembers('FieldPostCreate', '/blueprints/sections/', array('field' => &$field, 'data' => &$data));
859
                                } else {
860
                                    /**
861
                                     * After editing of a Field.
862
                                     *
863
                                     * @delegate FieldPostEdit
864
                                     * @param string $context
865
                                     * '/blueprints/sections/'
866
                                     * @param Field $field
867
                                     *  The Field object, passed by reference
868
                                     * @param array $data
869
                                     *  The settings for ths `$field`, passed by reference
870
                                     */
871
                                    Symphony::ExtensionManager()->notifyMembers('FieldPostEdit', '/blueprints/sections/', array('field' => &$field, 'data' => &$data));
872
                                }
873
                            }
874
                        }
875
                    }
876
877
                    if (!$edit) {
878
                        /**
879
                         * After the Section has been created, and all the Field's have been
880
                         * created for this section, but just before the redirect
881
                         *
882
                         * @delegate SectionPostCreate
883
                         * @since Symphony 2.2
884
                         * @param string $context
885
                         * '/blueprints/sections/'
886
                         * @param integer $section_id
887
                         *  The newly created Section ID.
888
                         */
889
                        Symphony::ExtensionManager()->notifyMembers('SectionPostCreate', '/blueprints/sections/', array('section_id' => $section_id));
890
891
                        redirect(SYMPHONY_URL . "/blueprints/sections/edit/$section_id/created/");
0 ignored issues
show
Bug introduced by
The constant SYMPHONY_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
892
                    } else {
893
                        /**
894
                         * After the Section has been updated, and all the Field's have been
895
                         * updated for this section, but just before the redirect
896
                         *
897
                         * @delegate SectionPostEdit
898
                         * @since Symphony 2.2
899
                         * @param string $context
900
                         * '/blueprints/sections/'
901
                         * @param integer $section_id
902
                         *  The edited Section ID.
903
                         */
904
                        Symphony::ExtensionManager()->notifyMembers('SectionPostEdit', '/blueprints/sections/', array('section_id' => $section_id));
905
906
                        redirect(SYMPHONY_URL . "/blueprints/sections/edit/$section_id/saved/");
907
                    }
908
                }
909
            }
910
        }
911
912
        if (is_array($_POST['action']) && array_key_exists('delete', $_POST['action'])) {
913
            $section_id = $this->_context[1];
914
            $canProceed = $this->validateTimestamp($section_id);
915
916
            if (!$canProceed) {
917
                $section = (new SectionManager)->select()->section($section_id)->execute()->next();
918
                $this->addTimestampValidationPageAlert(
919
                    $this->_errors['timestamp'],
920
                    $section,
921
                    'delete'
922
                );
923
                return;
924
            }
925
926
            $section_ids = array($section_id);
927
928
            /**
929
             * Just prior to calling the Section Manager's delete function
930
             *
931
             * @delegate SectionPreDelete
932
             * @since Symphony 2.2
933
             * @param string $context
934
             * '/blueprints/sections/'
935
             * @param array $section_ids
936
             *  An array of Section ID's passed by reference
937
             */
938
            Symphony::ExtensionManager()->notifyMembers('SectionPreDelete', '/blueprints/sections/', array('section_ids' => &$section_ids));
939
940
            foreach ($section_ids as $section) {
941
                SectionManager::delete($section);
942
            }
943
944
            redirect(SYMPHONY_URL . '/blueprints/sections/');
945
        }
946
    }
947
948
    public function __actionEdit()
949
    {
950
        return $this->__actionNew();
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->__actionNew() targeting contentBlueprintsSections::__actionNew() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
951
    }
952
953
    public function addSectionOptions(array &$meta = null)
954
    {
955
        $fieldset = new XMLElement('fieldset');
956
        $fieldset->setAttribute('class', 'settings');
957
        $fieldset->appendChild(new XMLElement('legend', __('Options')));
958
959
        $div = new XMLElement('div', null, array('class' => 'two columns'));
960
961
        $hidediv = new XMLElement('div', null, array('class' => 'column'));
962
        $label = Widget::Checkbox('meta[hidden]', $meta['hidden'], __('Hide this section from the back-end menu'));
963
        $hidediv->appendChild($label);
964
        $div->appendChild($hidediv);
965
966
        $filterdiv = new XMLElement('div', null, array('class' => 'column'));
967
        $label = Widget::Checkbox('meta[filter]', $meta['filter'], __('Allow filtering of section entries'));
968
        $filterdiv->appendChild($label);
969
970
        $div->appendChild($filterdiv);
971
        $fieldset->appendChild($div);
972
        $this->Form->appendChild($fieldset);
973
974
        /**
975
         * Allows extensions to add elements to the header of the Section Editor
976
         * form. Usually for section settings, this delegate is passed the current
977
         * `$meta` array and the `$this->_errors` array.
978
         *
979
         * @delegate AddSectionElements
980
         * @since Symphony 2.2
981
         * @param string $context
982
         * '/blueprints/sections/'
983
         * @param XMLElement $form
984
         *  An XMLElement of the current `$this->Form`, just after the Section
985
         *  settings have been appended, but before the Fields duplicator
986
         * @param array $meta
987
         *  The current $_POST['meta'] array
988
         * @param array $errors
989
         *  The current errors array
990
         */
991
        Symphony::ExtensionManager()->notifyMembers('AddSectionElements', '/blueprints/sections/', array(
992
            'form' => &$this->Form,
993
            'meta' => &$meta,
994
            'errors' => &$this->_errors
995
        ));
996
    }
997
998
    /**
999
     * Given $_POST values, this function will validate the current timestamp
1000
     * and set the proper error messages.
1001
     *
1002
     * @since Symphony 2.7.0
1003
     * @param  int $section_id
1004
     *   The entry id to validate
1005
     * @return boolean
1006
     *   true if the timestamp is valid
1007
     */
1008
    protected function validateTimestamp($section_id, $checkMissing = false)
1009
    {
1010
        if (!isset($_POST['action']['ignore-timestamp'])) {
1011
            if ($checkMissing && !isset($_POST['action']['timestamp'])) {
1012
                if (isset($this->_errors) && is_array($this->_errors)) {
1013
                    $this->_errors['timestamp'] = __('The section could not be saved due to conflicting changes');
1014
                }
1015
                return false;
1016
            } elseif (isset($_POST['action']['timestamp'])) {
1017
                $tv = new TimestampValidator('sections');
1018
                if (!$tv->check($section_id, $_POST['action']['timestamp'])) {
1019
                    if (isset($this->_errors) && is_array($this->_errors)) {
1020
                        $this->_errors['timestamp'] = __('The section could not be saved due to conflicting changes');
1021
                    }
1022
                    return false;
1023
                }
1024
            }
1025
        }
1026
        return true;
1027
    }
1028
}
1029