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
Push — master ( 2240c6...8ae5ca )
by Nicolas
04:17
created

contentBlueprintsEvents::__actionEdit()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 31
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 14
c 0
b 0
f 0
nc 5
nop 0
dl 0
loc 31
rs 8.439
1
<?php
2
/**
3
 * @package content
4
 */
5
6
/**
7
 * The Event Editor allows a developer to create events that typically
8
 * allow Frontend forms to populate Sections or edit Entries.
9
 */
10
11
class contentBlueprintsEvents extends ResourcesPage
12
{
13
    public $_errors = array();
14
15
    public function __viewIndex($resource_type)
16
    {
17
        parent::__viewIndex(ResourceManager::RESOURCE_TYPE_EVENT);
18
19
        $this->setTitle(__('%1$s &ndash; %2$s', array(__('Events'), __('Symphony'))));
20
        $this->appendSubheading(__('Events'), Widget::Anchor(__('Create New'), Administration::instance()->getCurrentPageURL().'new/', __('Create a new event'), 'create button', null, array('accesskey' => 'c')));
21
    }
22
23
    public function __viewNew()
24
    {
25
        $this->__form();
26
    }
27
28
    public function __viewEdit()
29
    {
30
        $this->__form();
31
    }
32
33
    public function __viewInfo()
34
    {
35
        $this->__form(true);
36
    }
37
38
    public function __form($readonly = false)
39
    {
40
        $formHasErrors = (is_array($this->_errors) && !empty($this->_errors));
41
42
        if ($formHasErrors) {
43
            $this->pageAlert(
44
                __('An error occurred while processing this form. See below for details.'),
45
                Alert::ERROR
46
            );
47
48
            // These alerts are only valid if the form doesn't have errors
49
        } elseif (isset($this->_context[2])) {
50
            $time = Widget::Time();
51
52
            switch ($this->_context[2]) {
53
                case 'saved':
54
                    $message = __('Event updated at %s.', array($time->generate()));
55
                    break;
56
                case 'created':
57
                    $message = __('Event created at %s.', array($time->generate()));
58
            }
59
60
            $this->pageAlert(
61
                $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...
62
                . ' <a href="' . SYMPHONY_URL . '/blueprints/events/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...
63
                . __('Create another?')
64
                . '</a> <a href="' . SYMPHONY_URL . '/blueprints/events/" accesskey="a">'
65
                . __('View all Events')
66
                . '</a>',
67
                Alert::SUCCESS
68
            );
69
        }
70
71
        $isEditing = ($readonly ? true : false);
72
        $fields = array('name' => null, 'filters' => null);
73
        $about = array('name' => null);
74
        $providers = Symphony::ExtensionManager()->getProvidersOf(iProvider::EVENT);
75
        $canonical_link = null;
76
77
        if (isset($_POST['fields'])) {
78
            $fields = $_POST['fields'];
79
80
            if ($this->_context[0] == 'edit') {
81
                $isEditing = true;
82
            }
83
        } elseif ($this->_context[0] == 'edit' || $this->_context[0] == 'info') {
84
            $isEditing = true;
85
            $handle = $this->_context[1];
86
            $existing = EventManager::create($handle);
87
            $about = General::array_map_recursive('stripslashes', $existing->about());
0 ignored issues
show
Bug introduced by
The method about() does not exist on Event. ( Ignorable by Annotation )

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

87
            $about = General::array_map_recursive('stripslashes', $existing->/** @scrutinizer ignore-call */ about());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
88
89
            if ($this->_context[0] == 'edit' && !$existing->allowEditorToParse()) {
90
                redirect(SYMPHONY_URL . '/blueprints/events/info/' . $handle . '/');
91
            }
92
93
            $fields['name'] = $about['name'];
94
            $fields['source'] = stripslashes($existing->getSource());
95
            $provided = false;
96
97
            if (!empty($providers)) {
98
                foreach ($providers as $providerClass => $provider) {
99
                    if ($fields['source'] == call_user_func(array($providerClass, 'getClass'))) {
100
                        $fields = array_merge($fields, $existing->settings());
0 ignored issues
show
Bug introduced by
The method settings() does not exist on Event. ( Ignorable by Annotation )

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

100
                        $fields = array_merge($fields, $existing->/** @scrutinizer ignore-call */ settings());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
101
                        $provided = true;
102
                        break;
103
                    }
104
                }
105
            }
106
107
            if (!$provided) {
108
                if (isset($existing->eParamFILTERS)) {
109
                    $fields['filters'] = array_map('stripslashes', $existing->eParamFILTERS);
110
                }
111
            }
112
113
            $canonical_link = '/blueprints/events/' . $this->_context[0] . '/' . $handle . '/';
114
        }
115
116
        // Handle name on edited changes, or from reading an edited datasource
117
        if (isset($about['name'])) {
118
            $name = $about['name'];
119
        } elseif (isset($fields['name'])) {
120
            $name = $fields['name'];
121
        }
122
123
        $this->setPageType('form');
124
        $this->setTitle(__(($isEditing ? '%1$s &ndash; %2$s &ndash; %3$s' : '%2$s &ndash; %3$s'), array($name, __('Events'), __('Symphony'))));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $name does not seem to be defined for all execution paths leading up to this point.
Loading history...
125
        if ($canonical_link) {
126
            $this->addElementToHead(new XMLElement('link', null, array(
127
                'rel' => 'canonical',
128
                'href' => SYMPHONY_URL . $canonical_link,
129
            )));
130
        }
131
        $this->appendSubheading(($isEditing ? $about['name'] : __('Untitled')));
132
        $this->insertBreadcrumbs(array(
133
            Widget::Anchor(__('Events'), SYMPHONY_URL . '/blueprints/events/'),
134
        ));
135
136
        if (!$readonly) {
137
            $fieldset = new XMLElement('fieldset');
138
            $fieldset->setAttribute('class', 'settings');
139
            $fieldset->appendChild(new XMLElement('legend', __('Essentials')));
140
141
            // Target
142
            $sources = new XMLElement('div', null, array('class' => 'apply actions'));
143
            $div = new XMLElement('div');
144
            $label = Widget::Label(__('Target'), null, 'apply-label-left');
145
            $sources->appendChild($label);
146
            $sources->appendChild($div);
147
148
            $sections = SectionManager::fetch(null, 'ASC', 'name');
149
            $options = array();
150
            $section_options = array();
151
            $source = isset($fields['source']) ? $fields['source'] : null;
152
153
            if (is_array($sections) && !empty($sections)) {
154
                $section_options = array('label' => __('Sections'), 'options' => array());
155
156
                foreach ($sections as $s) {
157
                    $section_options['options'][] = array($s->get('id'), $source == $s->get('id'), General::sanitize($s->get('name')));
158
                }
159
            }
160
161
            $options[] = $section_options;
162
163
            // Loop over the event providers
164
            if (!empty($providers)) {
165
                $p = array('label' => __('From extensions'), 'options' => array());
166
167
                foreach ($providers as $providerClass => $provider) {
168
                    $p['options'][] = array(
169
                        $providerClass, ($fields['source'] == $providerClass), $provider
170
                    );
171
                }
172
173
                $options[] = $p;
174
            }
175
176
            $div->appendChild(
177
                Widget::Select('source', $options, array('id' => 'event-context'))
178
            );
179
180
            if (isset($this->_errors['source'])) {
181
                $this->Context->prependChild(Widget::Error($sources, $this->_errors['source']));
182
            } else {
183
                $this->Context->prependChild($sources);
184
            }
185
186
            $this->Form->appendChild(
187
                Widget::Input('fields[source]', $options[0]['options'][0][0], 'hidden', array('id' => 'event-source'))
188
            );
189
190
            // Name
191
            $group = new XMLElement('div');
192
            $label = Widget::Label(__('Name'));
193
            $label->appendChild(Widget::Input('fields[name]', General::sanitize($fields['name'])));
194
195
            $div = new XMLElement('div');
196
            $div->setAttribute('class', 'column');
197
198
            if (isset($this->_errors['name'])) {
199
                $div->appendChild(Widget::Error($label, $this->_errors['name']));
200
            } else {
201
                $div->appendChild($label);
202
            }
203
            $group->appendChild($div);
204
            $fieldset->appendChild($group);
205
            $this->Form->appendChild($fieldset);
206
207
            // Filters
208
            $fieldset = new XMLElement('fieldset');
209
            $fieldset->setAttribute('class', 'settings pickable');
210
            $fieldset->appendChild(new XMLElement('legend', __('Filters')));
211
            $p = new XMLElement('p', __('Event Filters add additional conditions or actions to an event.'));
212
            $p->setAttribute('class', 'help');
213
            $fieldset->appendChild($p);
214
215
            $filters = isset($fields['filters']) ? $fields['filters'] : array();
216
            $options = array(
217
                array('admin-only', in_array('admin-only', $filters), __('Admin Only')),
218
                array('send-email', in_array('send-email', $filters), __('Send Notification Email')),
219
                array('expect-multiple', in_array('expect-multiple', $filters), __('Allow Multiple')),
220
            );
221
222
            /**
223
             * Allows adding of new filter rules to the Event filter rule select box
224
             *
225
             * @delegate AppendEventFilter
226
             * @param string $context
227
             * '/blueprints/events/(edit|new|info)/'
228
             * @param array $selected
229
             *  An array of all the selected filters for this Event
230
             * @param array $options
231
             *  An array of all the filters that are available, passed by reference
232
             */
233
            Symphony::ExtensionManager()->notifyMembers('AppendEventFilter', '/blueprints/events/' . $this->_context[0] . '/', array(
234
                'selected' => $filters,
235
                'options' => &$options
236
            ));
237
238
            $fieldset->appendChild(Widget::Select('fields[filters][]', $options, array('multiple' => 'multiple', 'id' => 'event-filters')));
239
            $this->Form->appendChild($fieldset);
240
241
            // Connections
242
            $fieldset = new XMLElement('fieldset');
243
            $fieldset->setAttribute('class', 'settings');
244
            $fieldset->appendChild(new XMLElement('legend', __('Attach to Pages')));
245
            $p = new XMLElement('p', __('The event will only be available on the selected pages.'));
246
            $p->setAttribute('class', 'help');
247
            $fieldset->appendChild($p);
248
249
            $div = new XMLElement('div');
250
            $label = Widget::Label(__('Pages'));
251
252
            $pages = PageManager::fetch();
253
            $event_handle = str_replace('-', '_', Lang::createHandle($fields['name']));
254
            $connections = ResourceManager::getAttachedPages(ResourceManager::RESOURCE_TYPE_EVENT, $event_handle);
255
            $selected = array();
256
257
            foreach ($connections as $connection) {
258
                $selected[] = $connection['id'];
259
            }
260
261
            $options = array();
262
263
            foreach ($pages as $page) {
264
                $options[] = array(
265
                    $page['id'],
266
                    in_array($page['id'], $selected),
267
                    General::sanitize(PageManager::resolvePageTitle($page['id']))
268
                );
269
            }
270
271
            $label->appendChild(Widget::Select('fields[connections][]', $options, array('multiple' => 'multiple')));
272
            $div->appendChild($label);
273
274
            $fieldset->appendChild($div);
275
            $this->Form->appendChild($fieldset);
276
277
            // Providers
278
            if (!empty($providers)) {
279
                foreach ($providers as $providerClass => $provider) {
280
                    if ($isEditing && $fields['source'] !== call_user_func(array($providerClass, 'getSource'))) {
281
                        continue;
282
                    }
283
284
                    call_user_func_array(array($providerClass, 'buildEditor'), array($this->Form, &$this->_errors, $fields, $handle));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $handle does not seem to be defined for all execution paths leading up to this point.
Loading history...
285
                }
286
            }
287
        } else {
288
            // Author
289
            if (isset($about['author']['website'])) {
290
                $link = Widget::Anchor($about['author']['name'], General::validateURL($about['author']['website']));
291
            } elseif (isset($about['author']['email'])) {
292
                $link = Widget::Anchor($about['author']['name'], 'mailto:' . $about['author']['email']);
293
            } else {
294
                $link = $about['author']['name'];
295
            }
296
297
            if ($link) {
298
                $fieldset = new XMLElement('fieldset');
299
                $fieldset->setAttribute('class', 'settings');
300
                $fieldset->appendChild(new XMLElement('legend', __('Author')));
301
                $fieldset->appendChild(new XMLElement('p', $link->generate(false)));
302
                $this->Form->appendChild($fieldset);
303
            }
304
305
            // Version
306
            $fieldset = new XMLElement('fieldset');
307
            $fieldset->setAttribute('class', 'settings');
308
            $fieldset->appendChild(new XMLElement('legend', __('Version')));
309
            $version = array_key_exists('version', $about) ? $about['version'] : null;
310
            $release_date = array_key_exists('release-date', $about) ? $about['release-date'] : filemtime(EventManager::__getDriverPath($handle));
311
312
            if (preg_match('/^\d+(\.\d+)*$/', $version)) {
313
                $fieldset->appendChild(
314
                    new XMLElement('p', __('%1$s released on %2$s', array($version, DateTimeObj::format($release_date, __SYM_DATE_FORMAT__))))
0 ignored issues
show
Bug introduced by
The constant __SYM_DATE_FORMAT__ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
315
                );
316
            } elseif (!is_null($version)) {
317
                $fieldset->appendChild(
318
                    new XMLElement('p', __('Created by %1$s at %2$s', array($version, DateTimeObj::format($release_date, __SYM_DATE_FORMAT__))))
319
                );
320
            } else {
321
                $fieldset->appendChild(
322
                    new XMLElement('p', __('Last modified on %s', array(DateTimeObj::format($release_date, __SYM_DATE_FORMAT__))))
323
                );
324
            }
325
            $this->Form->appendChild($fieldset);
326
        }
327
328
        // If we are editing an event, it assumed that the event has documentation
329
        $fieldset = new XMLElement('fieldset');
330
        $fieldset->setAttribute('id', 'event-documentation');
331
        $fieldset->setAttribute('class', 'settings');
332
333
        if ($isEditing && method_exists($existing, 'documentation')) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $existing does not seem to be defined for all execution paths leading up to this point.
Loading history...
334
            $doc = $existing->documentation();
335
336
            if ($doc) {
337
                $fieldset->setValue(
338
                    '<legend>' . __('Documentation') . '</legend>' . PHP_EOL .
339
                    General::tabsToSpaces(is_object($doc) ? $doc->generate(true, 4) : $doc)
340
                );
341
            }
342
        }
343
344
        $this->Form->appendChild($fieldset);
345
346
        $div = new XMLElement('div');
347
        $div->setAttribute('class', 'actions');
348
        $div->appendChild(Widget::Input('action[save]', ($isEditing ? __('Save Changes') : __('Create Event')), 'submit', array('accesskey' => 's')));
349
350
        if ($isEditing) {
351
            $button = new XMLElement('button', __('Delete'));
352
            $button->setAttributeArray(array('name' => 'action[delete]', 'class' => 'button confirm delete', 'title' => __('Delete this event'), 'type' => 'submit', 'accesskey' => 'd', 'data-message' => __('Are you sure you want to delete this event?')));
353
            $div->appendChild($button);
354
        }
355
356
        if (!$readonly) {
357
            $this->Form->appendChild($div);
358
        }
359
    }
360
361
    public function __actionNew()
362
    {
363
        if (array_key_exists('save', $_POST['action'])) {
364
            return $this->__formAction();
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->__formAction() targeting contentBlueprintsEvents::__formAction() 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...
365
        }
366
    }
367
368
    public function __actionEdit()
369
    {
370
        if (array_key_exists('save', $_POST['action'])) {
371
            return $this->__formAction();
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->__formAction() targeting contentBlueprintsEvents::__formAction() 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...
372
        } elseif (array_key_exists('delete', $_POST['action'])) {
373
            /**
374
             * Prior to deleting the Event file. Target file path is provided.
375
             *
376
             * @delegate EventPreDelete
377
             * @since Symphony 2.2
378
             * @param string $context
379
             * '/blueprints/events/'
380
             * @param string $file
381
             *  The path to the Event file
382
             */
383
            Symphony::ExtensionManager()->notifyMembers('EventPreDelete', '/blueprints/events/', array('file' => EVENTS . "/event." . $this->_context[1] . ".php"));
0 ignored issues
show
Bug introduced by
The constant EVENTS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
384
385
            if (!General::deleteFile(EVENTS . '/event.' . $this->_context[1] . '.php')) {
386
                $this->pageAlert(
387
                    __('Failed to delete %s.', array('<code>' . $this->_context[1] . '</code>'))
388
                    . ' ' . __('Please check permissions on %s.', array('<code>/workspace/events</code>')),
389
                    Alert::ERROR
390
                );
391
            } else {
392
                $pages = ResourceManager::getAttachedPages(ResourceManager::RESOURCE_TYPE_EVENT, $this->_context[1]);
393
394
                foreach ($pages as $page) {
395
                    ResourceManager::detach(ResourceManager::RESOURCE_TYPE_EVENT, $this->_context[1], $page['id']);
396
                }
397
398
                redirect(SYMPHONY_URL . '/blueprints/events/');
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...
399
            }
400
        }
401
    }
402
403
    public function __actionIndex($resource_type)
404
    {
405
        return parent::__actionIndex(ResourceManager::RESOURCE_TYPE_EVENT);
0 ignored issues
show
Bug introduced by
Are you sure the usage of parent::__actionIndex(Re...r::RESOURCE_TYPE_EVENT) targeting ResourcesPage::__actionIndex() 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...
406
    }
407
408
    public function __formAction()
409
    {
410
        $fields = $_POST['fields'];
411
        $this->_errors = array();
412
        $providers = Symphony::ExtensionManager()->getProvidersOf(iProvider::EVENT);
413
        $providerClass = null;
414
415
        if (trim($fields['name']) == '') {
416
            $this->_errors['name'] = __('This is a required field');
417
        } elseif (strpos($fields['name'], '\\') !== false) {
418
            $this->_errors['name'] = __('This field contains invalid characters') . ' (\\)';
419
        }
420
421
        if (trim($fields['source']) == '') {
422
            $this->_errors['source'] = __('This is a required field');
423
        }
424
425
        $filters = isset($fields['filters']) ? $fields['filters'] : array();
426
427
        // See if a Provided Datasource is saved
428
        if (!empty($providers)) {
429
            foreach ($providers as $providerClass => $provider) {
430
                if ($fields['source'] == call_user_func(array($providerClass, 'getSource'))) {
431
                    call_user_func_array(array($providerClass, 'validate'), array(&$fields, &$this->_errors));
432
                    break;
433
                }
434
435
                unset($providerClass);
436
            }
437
        }
438
439
        $classname = Lang::createHandle($fields['name'], 255, '_', false, true, array('@^[^a-z\d]+@i' => '', '/[^\w-\.]/i' => ''));
440
        $rootelement = str_replace('_', '-', $classname);
441
        $extends = 'SectionEvent';
442
443
        // Check to make sure the classname is not empty after handlisation.
444
        if (empty($classname) && !isset($this->_errors['name'])) {
445
            $this->_errors['name'] = __('Please ensure name contains at least one Latin-based character.', array($classname));
446
        }
447
448
        $file = EVENTS . '/event.' . $classname . '.php';
0 ignored issues
show
Bug introduced by
The constant EVENTS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
449
        $isDuplicate = false;
450
        $queueForDeletion = null;
451
452
        if ($this->_context[0] == 'new' && is_file($file)) {
453
            $isDuplicate = true;
454
        } elseif ($this->_context[0] == 'edit') {
455
            $existing_handle = $this->_context[1];
456
457
            if ($classname != $existing_handle && is_file($file)) {
458
                $isDuplicate = true;
459
            } elseif ($classname != $existing_handle) {
460
                $queueForDeletion = EVENTS . '/event.' . $existing_handle . '.php';
461
            }
462
        }
463
464
        // Duplicate
465
        if ($isDuplicate) {
466
            $this->_errors['name'] = __('An Event with the name %s already exists', array('<code>' . $classname . '</code>'));
467
        }
468
469
        if (empty($this->_errors)) {
470
            $source = $fields['source'];
471
            $params = array(
472
                'rootelement' => $rootelement,
473
            );
474
475
            $about = array(
476
                'name' => $fields['name'],
477
                'version' => 'Symphony ' . Symphony::Configuration()->get('version', 'symphony'),
478
                'release date' => DateTimeObj::getGMT('c'),
479
                'author name' => Symphony::Author()->getFullName(),
480
                'author website' => URL,
0 ignored issues
show
Bug introduced by
The constant URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
481
                'author email' => Symphony::Author()->get('email')
482
            );
483
484
            // If there is a provider, get their template
485
            if ($providerClass) {
486
                $eventShell = file_get_contents(call_user_func(array($providerClass, 'getTemplate')));
487
            } else {
488
                $eventShell = file_get_contents($this->getTemplate('blueprints.event'));
0 ignored issues
show
Bug introduced by
It seems like $this->getTemplate('blueprints.event') can also be of type false; however, parameter $filename of file_get_contents() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

488
                $eventShell = file_get_contents(/** @scrutinizer ignore-type */ $this->getTemplate('blueprints.event'));
Loading history...
489
                $about['trigger condition'] = $rootelement;
490
            }
491
492
            $this->__injectAboutInformation($eventShell, $about);
493
494
            // Replace the name
495
            $eventShell = str_replace('<!-- CLASS NAME -->', $classname, $eventShell);
496
497
            // Build the templates
498
            if ($providerClass) {
499
                $eventShell = call_user_func(array($providerClass, 'prepare'), $fields, $params, $eventShell);
500
            } else {
501
                $this->__injectFilters($eventShell, $filters);
502
503
                // Add Documentation
504
                $ajaxEventDoc = new contentAjaxEventDocumentation();
505
                $doc_parts = array();
506
507
                // Add Documentation (Success/Failure)
508
                $ajaxEventDoc->addEntrySuccessDoc($doc_parts, $rootelement, $filters);
509
                $ajaxEventDoc->addEntryFailureDoc($doc_parts, $rootelement, $filters);
510
511
                // Filters
512
                $ajaxEventDoc->addDefaultFiltersDoc($doc_parts, $rootelement, $filters);
513
514
                // Frontend Markup
515
                $ajaxEventDoc->addFrontendMarkupDoc($doc_parts, $rootelement, $fields['source'], $filters);
516
                $ajaxEventDoc->addSendMailFilterDoc($doc_parts, $filters);
517
518
                /**
519
                 * Allows adding documentation for new filters. A reference to the $documentation
520
                 * array is provided, along with selected filters
521
                 * @delegate AppendEventFilterDocumentation
522
                 * @param string $context
523
                 * '/blueprints/events/(edit|new|info)/'
524
                 * @param array $selected
525
                 *  An array of all the selected filters for this Event
526
                 * @param array $documentation
527
                 *  An array of all the documentation XMLElements, passed by reference
528
                 * @param string $rootelment
529
                 *  The name of this event, as a handle.
530
                 */
531
                Symphony::ExtensionManager()->notifyMembers('AppendEventFilterDocumentation', '/blueprints/events/', array(
532
                    'selected' => $filters,
533
                    'documentation' => &$doc_parts,
534
                    'rootelement' => $rootelement
535
                ));
536
537
                $documentation = join(PHP_EOL, array_map(function($part) {
538
                    return rtrim($part->generate(true, 4));
539
                }, $doc_parts));
540
                $documentation = str_replace('\'', '\\\'', $documentation);
541
542
                $eventShell = str_replace('<!-- CLASS EXTENDS -->', $extends, $eventShell);
543
                $eventShell = str_replace('<!-- DOCUMENTATION -->', General::tabsToSpaces($documentation, 4), $eventShell);
544
            }
545
546
            $eventShell = str_replace('<!-- ROOT ELEMENT -->', $rootelement, $eventShell);
547
            $eventShell = str_replace('<!-- CLASS NAME -->', $classname, $eventShell);
548
            $eventShell = str_replace('<!-- SOURCE -->', addslashes($source), $eventShell);
549
550
            // Remove left over placeholders
551
            $eventShell = preg_replace(array('/<!--[\w ]++-->/'), '', $eventShell);
552
553
            if ($this->_context[0] == 'new') {
554
                /**
555
                 * Prior to creating an Event, the file path where it will be written to
556
                 * is provided and well as the contents of that file.
557
                 *
558
                 * @delegate EventsPreCreate
559
                 * @since Symphony 2.2
560
                 * @param string $context
561
                 * '/blueprints/events/'
562
                 * @param string $file
563
                 *  The path to the Event file
564
                 * @param string $contents
565
                 *  The contents for this Event as a string passed by reference
566
                 * @param array $filters
567
                 *  An array of the filters attached to this event
568
                 */
569
                Symphony::ExtensionManager()->notifyMembers('EventPreCreate', '/blueprints/events/', array(
570
                    'file' => $file,
571
                    'contents' => &$eventShell,
572
                    'filters' => $filters
573
                ));
574
            } else {
575
                /**
576
                 * Prior to editing an Event, the file path where it will be written to
577
                 * is provided and well as the contents of that file.
578
                 *
579
                 * @delegate EventPreEdit
580
                 * @since Symphony 2.2
581
                 * @param string $context
582
                 * '/blueprints/events/'
583
                 * @param string $file
584
                 *  The path to the Event file
585
                 * @param string $contents
586
                 *  The contents for this Event as a string passed by reference
587
                 * @param array $filters
588
                 *  An array of the filters attached to this event
589
                 */
590
                Symphony::ExtensionManager()->notifyMembers('EventPreEdit', '/blueprints/events/', array(
591
                    'file' => $file,
592
                    'contents' => &$eventShell,
593
                    'filters' => $filters
594
                ));
595
            }
596
597
            // Write the file
598
            if (!General::writeFile($file, $eventShell, Symphony::Configuration()->get('write_mode', 'file'))) {
0 ignored issues
show
Bug introduced by
It seems like Symphony::Configuration(...t('write_mode', 'file') can also be of type array; however, parameter $perm of General::writeFile() does only seem to accept integer|string, maybe add an additional type check? ( Ignorable by Annotation )

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

598
            if (!General::writeFile($file, $eventShell, /** @scrutinizer ignore-type */ Symphony::Configuration()->get('write_mode', 'file'))) {
Loading history...
599
                $this->pageAlert(
600
                    __('Failed to write Event to disk.')
601
                    . ' ' . __('Please check permissions on %s.', array('<code>/workspace/events</code>')),
602
                    Alert::ERROR
603
                );
604
605
                // Write successful
606
            } else {
607
                if (function_exists('opcache_invalidate')) {
608
                    opcache_invalidate($file, true);
609
                }
610
611
                // Attach this event to pages
612
                $connections = $fields['connections'];
613
                ResourceManager::setPages(ResourceManager::RESOURCE_TYPE_EVENT, is_null($existing_handle) ? $classname : $existing_handle, $connections);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $existing_handle does not seem to be defined for all execution paths leading up to this point.
Loading history...
614
615
                if ($queueForDeletion) {
616
                    General::deleteFile($queueForDeletion);
617
618
                    $pages = PageManager::fetch(false, array('events', 'id'), array("
619
                        `events` REGEXP '[[:<:]]" . $existing_handle . "[[:>:]]'
620
                    "));
621
622
                    if (is_array($pages) && !empty($pages)) {
623
                        foreach ($pages as $page) {
624
                            $page['events'] = preg_replace('/\b'.$existing_handle.'\b/i', $classname, $page['events']);
625
626
                            PageManager::edit($page['id'], $page);
627
                        }
628
                    }
629
                }
630
631
                if ($this->_context[0] == 'new') {
632
                    /**
633
                     * After creating the Event, the path to the Event file is provided
634
                     *
635
                     * @delegate EventPostCreate
636
                     * @since Symphony 2.2
637
                     * @param string $context
638
                     * '/blueprints/events/'
639
                     * @param string $file
640
                     *  The path to the Event file
641
                     */
642
                    Symphony::ExtensionManager()->notifyMembers('EventPostCreate', '/blueprints/events/', array(
643
                        'file' => $file
644
                    ));
645
                } else {
646
                    /**
647
                     * After editing the Event, the path to the Event file is provided
648
                     *
649
                     * @delegate EventPostEdit
650
                     * @since Symphony 2.2
651
                     * @param string $context
652
                     * '/blueprints/events/'
653
                     * @param string $file
654
                     *  The path to the Event file
655
                     * @param string $previous_file
656
                     *  The path of the previous Event file in the case where an Event may
657
                     *  have been renamed. To get the handle from this value, see
658
                     *  `EventManager::__getHandleFromFilename`
659
                     */
660
                    Symphony::ExtensionManager()->notifyMembers('EventPostEdit', '/blueprints/events/', array(
661
                        'file' => $file,
662
                        'previous_file' => ($queueForDeletion) ? $queueForDeletion : null
663
                    ));
664
                }
665
666
                redirect(SYMPHONY_URL . '/blueprints/events/edit/'.$classname.'/'.($this->_context[0] == 'new' ? 'created' : 'saved') . '/');
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...
667
            }
668
        }
669
    }
670
671
    public function __injectFilters(&$shell, $elements)
672
    {
673
        if (!is_array($elements) || empty($elements)) {
674
            return;
675
        }
676
        $elements = array_map('addslashes', $elements);
677
        $shell = str_replace('<!-- FILTERS -->', "'" . implode("'," . PHP_EOL . "        '", $elements) . "'", $shell);
678
    }
679
680
    public function __injectAboutInformation(&$shell, $details)
681
    {
682
        if (!is_array($details) || empty($details)) {
683
            return;
684
        }
685
686
        foreach ($details as $key => $val) {
687
            if (!is_string($key) || !is_string($val)) {
688
                continue;
689
            }
690
691
            $shell = str_replace('<!-- ' . strtoupper(addslashes($key)) . ' -->', addslashes($val), $shell);
692
        }
693
    }
694
}
695