Issues (3627)

PointBundle/Controller/TriggerController.php (1 issue)

1
<?php
2
3
/*
4
 * @copyright   2014 Mautic Contributors. All rights reserved
5
 * @author      Mautic
6
 *
7
 * @link        http://mautic.org
8
 *
9
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
10
 */
11
12
namespace Mautic\PointBundle\Controller;
13
14
use Mautic\CoreBundle\Controller\FormController;
15
use Mautic\CoreBundle\Factory\PageHelperFactoryInterface;
16
use Mautic\PointBundle\Entity\Trigger;
17
use Symfony\Component\Form\FormError;
18
use Symfony\Component\HttpFoundation\JsonResponse;
19
use Symfony\Component\HttpFoundation\Response;
20
21
class TriggerController extends FormController
22
{
23
    /**
24
     * @param int $page
25
     *
26
     * @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
27
     */
28
    public function indexAction($page = 1)
29
    {
30
        //set some permissions
31
        $permissions = $this->get('mautic.security')->isGranted([
32
            'point:triggers:view',
33
            'point:triggers:create',
34
            'point:triggers:edit',
35
            'point:triggers:delete',
36
            'point:triggers:publish',
37
        ], 'RETURN_ARRAY');
38
39
        if (!$permissions['point:triggers:view']) {
40
            return $this->accessDenied();
41
        }
42
43
        $this->setListFilters();
44
45
        /** @var PageHelperFactoryInterface $pageHelperFacotry */
46
        $pageHelperFacotry = $this->get('mautic.page.helper.factory');
47
        $pageHelper        = $pageHelperFacotry->make('mautic.point.trigger', $page);
48
49
        $limit      = $pageHelper->getLimit();
50
        $start      = $pageHelper->getStart();
51
        $search     = $this->request->get('search', $this->get('session')->get('mautic.point.trigger.filter', ''));
52
        $filter     = ['string' => $search, 'force' => []];
53
        $orderBy    = $this->get('session')->get('mautic.point.trigger.orderby', 't.name');
54
        $orderByDir = $this->get('session')->get('mautic.point.trigger.orderbydir', 'ASC');
55
        $triggers   = $this->getModel('point.trigger')->getEntities(
56
            [
57
                'start'      => $start,
58
                'limit'      => $limit,
59
                'filter'     => $filter,
60
                'orderBy'    => $orderBy,
61
                'orderByDir' => $orderByDir,
62
            ]
63
        );
64
65
        $this->get('session')->set('mautic.point.trigger.filter', $search);
66
67
        $count = count($triggers);
68
        if ($count && $count < ($start + 1)) {
69
            $lastPage  = $pageHelper->countPage($count);
70
            $returnUrl = $this->generateUrl('mautic_pointtrigger_index', ['page' => $lastPage]);
71
            $pageHelper->rememberPage($lastPage);
72
73
            return $this->postActionRedirect([
74
                'returnUrl'       => $returnUrl,
75
                'viewParameters'  => ['page' => $lastPage],
76
                'contentTemplate' => 'MauticPointBundle:Trigger:index',
77
                'passthroughVars' => [
78
                    'activeLink'    => '#mautic_pointtrigger_index',
79
                    'mauticContent' => 'pointTrigger',
80
                ],
81
            ]);
82
        }
83
84
        $pageHelper->rememberPage($page);
85
86
        return $this->delegateView([
87
            'viewParameters' => [
88
                'searchValue' => $search,
89
                'items'       => $triggers,
90
                'page'        => $page,
91
                'limit'       => $limit,
92
                'permissions' => $permissions,
93
                'tmpl'        => $this->request->isXmlHttpRequest() ? $this->request->get('tmpl', 'index') : 'index',
94
            ],
95
            'contentTemplate' => 'MauticPointBundle:Trigger:list.html.php',
96
            'passthroughVars' => [
97
                'activeLink'    => '#mautic_pointtrigger_index',
98
                'mauticContent' => 'pointTrigger',
99
                'route'         => $this->generateUrl('mautic_pointtrigger_index', ['page' => $page]),
100
            ],
101
        ]);
102
    }
103
104
    /**
105
     * View a specific trigger.
106
     *
107
     * @param int $objectId
108
     *
109
     * @return array|JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
110
     */
111
    public function viewAction($objectId)
112
    {
113
        $entity = $this->getModel('point.trigger')->getEntity($objectId);
114
115
        //set the page we came from
116
        $page = $this->get('session')->get('mautic.point.trigger.page', 1);
117
118
        $permissions = $this->get('mautic.security')->isGranted([
119
            'point:triggers:view',
120
            'point:triggers:create',
121
            'point:triggers:edit',
122
            'point:triggers:delete',
123
            'point:triggers:publish',
124
        ], 'RETURN_ARRAY');
125
126
        if (null === $entity) {
127
            //set the return URL
128
            $returnUrl = $this->generateUrl('mautic_pointtrigger_index', ['page' => $page]);
129
130
            return $this->postActionRedirect([
131
                'returnUrl'       => $returnUrl,
132
                'viewParameters'  => ['page' => $page],
133
                'contentTemplate' => 'MauticPointBundle:Trigger:index',
134
                'passthroughVars' => [
135
                    'activeLink'    => '#mautic_pointtrigger_index',
136
                    'mauticContent' => 'pointTrigger',
137
                ],
138
                'flashes' => [
139
                    [
140
                        'type'    => 'error',
141
                        'msg'     => 'mautic.point.trigger.error.notfound',
142
                        'msgVars' => ['%id%' => $objectId],
143
                    ],
144
                ],
145
            ]);
146
        } elseif (!$permissions['point:triggers:view']) {
147
            return $this->accessDenied();
148
        }
149
150
        return $this->delegateView([
151
            'viewParameters' => [
152
                'entity'      => $entity,
153
                'page'        => $page,
154
                'permissions' => $permissions,
155
            ],
156
            'contentTemplate' => 'MauticPointBundle:Trigger:details.html.php',
157
            'passthroughVars' => [
158
                'activeLink'    => '#mautic_pointtrigger_index',
159
                'mauticContent' => 'pointTrigger',
160
                'route'         => $this->generateUrl('mautic_pointtrigger_action', [
161
                        'objectAction' => 'view',
162
                        'objectId'     => $entity->getId(), ]
163
                ),
164
            ],
165
        ]);
166
    }
167
168
    /**
169
     * Generates new form and processes post data.
170
     *
171
     * @param \Mautic\PointBundle\Entity\Trigger $entity
172
     *
173
     * @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
174
     */
175
    public function newAction($entity = null)
176
    {
177
        /** @var \Mautic\PointBundle\Model\TriggerModel $model */
178
        $model = $this->getModel('point.trigger');
179
180
        if (!($entity instanceof Trigger)) {
181
            /** @var \Mautic\PointBundle\Entity\Trigger $entity */
182
            $entity = $model->getEntity();
183
        }
184
185
        $session      = $this->get('session');
186
        $pointTrigger = $this->request->request->get('pointtrigger', []);
187
        $sessionId    = $pointTrigger['sessionId'] ?? 'mautic_'.sha1(uniqid(mt_rand(), true));
188
189
        if (!$this->get('mautic.security')->isGranted('point:triggers:create')) {
190
            return $this->accessDenied();
191
        }
192
193
        //set the page we came from
194
        $page = $this->get('session')->get('mautic.point.trigger.page', 1);
195
196
        //set added/updated events
197
        $addEvents     = $session->get('mautic.point.'.$sessionId.'.triggerevents.modified', []);
198
        $deletedEvents = $session->get('mautic.point.'.$sessionId.'.triggerevents.deleted', []);
199
200
        $action = $this->generateUrl('mautic_pointtrigger_action', ['objectAction' => 'new']);
201
        $form   = $model->createForm($entity, $this->get('form.factory'), $action);
202
        $form->get('sessionId')->setData($sessionId);
203
204
        ///Check for a submitted form and process it
205
        if ('POST' == $this->request->getMethod()) {
206
            $valid = false;
207
            if (!$cancelled = $this->isFormCancelled($form)) {
208
                if ($valid = $this->isFormValid($form)) {
209
                    //only save events that are not to be deleted
210
                    $events = array_diff_key($addEvents, array_flip($deletedEvents));
211
212
                    //make sure that at least one action is selected
213
                    if ('point.trigger' == 'point' && empty($events)) {
214
                        //set the error
215
                        $form->addError(new FormError(
216
                            $this->get('translator')->trans('mautic.core.value.required', [], 'validators')
217
                        ));
218
                        $valid = false;
219
                    } else {
220
                        $model->setEvents($entity, $events);
221
222
                        $model->saveEntity($entity);
223
224
                        $this->addFlash('mautic.core.notice.created', [
225
                            '%name%'      => $entity->getName(),
226
                            '%menu_link%' => 'mautic_pointtrigger_index',
227
                            '%url%'       => $this->generateUrl('mautic_pointtrigger_action', [
228
                                'objectAction' => 'edit',
229
                                'objectId'     => $entity->getId(),
230
                            ]),
231
                        ]);
232
233
                        if (!$form->get('buttons')->get('save')->isClicked()) {
234
                            //return edit view so that all the session stuff is loaded
235
                            return $this->editAction($entity->getId(), true);
236
                        }
237
                    }
238
                }
239
            }
240
241
            if ($cancelled || ($valid && $form->get('buttons')->get('save')->isClicked())) {
242
                $viewParameters = ['page' => $page];
243
                $returnUrl      = $this->generateUrl('mautic_pointtrigger_index', $viewParameters);
244
                $template       = 'MauticPointBundle:Trigger:index';
245
246
                //clear temporary fields
247
                $this->clearSessionComponents($sessionId);
248
249
                return $this->postActionRedirect([
250
                    'returnUrl'       => $returnUrl,
251
                    'viewParameters'  => $viewParameters,
252
                    'contentTemplate' => $template,
253
                    'passthroughVars' => [
254
                        'activeLink'    => '#mautic_pointtrigger_index',
255
                        'mauticContent' => 'pointTrigger',
256
                    ],
257
                ]);
258
            }
259
        } else {
260
            //clear out existing fields in case the form was refreshed, browser closed, etc
261
            $this->clearSessionComponents($sessionId);
262
            $addEvents = $deletedEvents = [];
263
        }
264
265
        return $this->delegateView([
266
            'viewParameters' => [
267
                'events'        => $model->getEventGroups(),
268
                'triggerEvents' => $addEvents,
269
                'deletedEvents' => $deletedEvents,
270
                'tmpl'          => $this->request->isXmlHttpRequest() ? $this->request->get('tmpl', 'index') : 'index',
271
                'entity'        => $entity,
272
                'form'          => $form->createView(),
273
                'sessionId'     => $sessionId,
274
            ],
275
            'contentTemplate' => 'MauticPointBundle:Trigger:form.html.php',
276
            'passthroughVars' => [
277
                'activeLink'    => '#mautic_pointtrigger_index',
278
                'mauticContent' => 'pointTrigger',
279
                'route'         => $this->generateUrl('mautic_pointtrigger_action', [
280
                        'objectAction' => (!empty($valid) ? 'edit' : 'new'), //valid means a new form was applied
281
                        'objectId'     => $entity->getId(), ]
282
                ),
283
            ],
284
        ]);
285
    }
286
287
    /**
288
     * Generates edit form and processes post data.
289
     *
290
     * @param int  $objectId
291
     * @param bool $ignorePost
292
     *
293
     * @return JsonResponse|Response
294
     */
295
    public function editAction($objectId, $ignorePost = false)
296
    {
297
        /** @var \Mautic\PointBundle\Model\TriggerModel $model */
298
        $model      = $this->getModel('point.trigger');
299
        $entity     = $model->getEntity($objectId);
300
        $session    = $this->get('session');
301
        $cleanSlate = true;
302
303
        //set the page we came from
304
        $page = $this->get('session')->get('mautic.point.trigger.page', 1);
305
306
        //set the return URL
307
        $returnUrl = $this->generateUrl('mautic_pointtrigger_index', ['page' => $page]);
308
309
        $postActionVars = [
310
            'returnUrl'       => $returnUrl,
311
            'viewParameters'  => ['page' => $page],
312
            'contentTemplate' => 'MauticPointBundle:Trigger:index',
313
            'passthroughVars' => [
314
                'activeLink'    => '#mautic_pointtrigger_index',
315
                'mauticContent' => 'pointTrigger',
316
            ],
317
        ];
318
319
        //form not found
320
        if (null === $entity) {
321
            return $this->postActionRedirect(
322
                array_merge($postActionVars, [
323
                    'flashes' => [
324
                        [
325
                            'type'    => 'error',
326
                            'msg'     => 'mautic.point.trigger.error.notfound',
327
                            'msgVars' => ['%id%' => $objectId],
328
                        ],
329
                    ],
330
                ])
331
            );
332
        } elseif (!$this->get('mautic.security')->isGranted('point:triggers:edit')) {
333
            return $this->accessDenied();
334
        } elseif ($model->isLocked($entity)) {
335
            //deny access if the entity is locked
336
            return $this->isLocked($postActionVars, $entity, 'point.trigger');
337
        }
338
339
        $action = $this->generateUrl('mautic_pointtrigger_action', ['objectAction' => 'edit', 'objectId' => $objectId]);
340
        $form   = $model->createForm($entity, $this->get('form.factory'), $action);
341
        $form->get('sessionId')->setData($objectId);
342
343
        ///Check for a submitted form and process it
344
        if (!$ignorePost && 'POST' == $this->request->getMethod()) {
345
            $valid = false;
346
            if (!$cancelled = $this->isFormCancelled($form)) {
347
                //set added/updated events
348
                $addEvents     = $session->get('mautic.point.'.$objectId.'.triggerevents.modified', []);
349
                $deletedEvents = $session->get('mautic.point.'.$objectId.'.triggerevents.deleted', []);
350
                $events        = array_diff_key($addEvents, array_flip($deletedEvents));
351
352
                if ($valid = $this->isFormValid($form)) {
353
                    //make sure that at least one field is selected
354
                    if ('point.trigger' == 'point' && empty($addEvents)) {
355
                        //set the error
356
                        $form->addError(new FormError(
357
                            $this->get('translator')->trans('mautic.core.value.required', [], 'validators')
358
                        ));
359
                        $valid = false;
360
                    } else {
361
                        $model->setEvents($entity, $events);
362
363
                        //form is valid so process the data
364
                        $model->saveEntity($entity, $form->get('buttons')->get('save')->isClicked());
365
366
                        //delete entities
367
                        if (count($deletedEvents)) {
368
                            $this->getModel('point.triggerEvent')->deleteEntities($deletedEvents);
0 ignored issues
show
The method deleteEntities() does not exist on Mautic\CoreBundle\Model\AbstractCommonModel. It seems like you code against a sub-type of Mautic\CoreBundle\Model\AbstractCommonModel such as Mautic\CoreBundle\Model\FormModel. ( Ignorable by Annotation )

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

368
                            $this->getModel('point.triggerEvent')->/** @scrutinizer ignore-call */ deleteEntities($deletedEvents);
Loading history...
369
                        }
370
371
                        $this->addFlash('mautic.core.notice.updated', [
372
                            '%name%'      => $entity->getName(),
373
                            '%menu_link%' => 'mautic_pointtrigger_index',
374
                            '%url%'       => $this->generateUrl('mautic_pointtrigger_action', [
375
                                'objectAction' => 'edit',
376
                                'objectId'     => $entity->getId(),
377
                            ]),
378
                        ]);
379
                    }
380
                }
381
            } else {
382
                //unlock the entity
383
                $model->unlockEntity($entity);
384
            }
385
386
            if ($cancelled || ($valid && $form->get('buttons')->get('save')->isClicked())) {
387
                $viewParameters = ['page' => $page];
388
                $returnUrl      = $this->generateUrl('mautic_pointtrigger_index', $viewParameters);
389
                $template       = 'MauticPointBundle:Trigger:index';
390
391
                //remove fields from session
392
                $this->clearSessionComponents($objectId);
393
394
                return $this->postActionRedirect(
395
                    array_merge($postActionVars, [
396
                        'returnUrl'       => $returnUrl,
397
                        'viewParameters'  => $viewParameters,
398
                        'contentTemplate' => $template,
399
                    ])
400
                );
401
            } elseif ($form->get('buttons')->get('apply')->isClicked()) {
402
                //rebuild everything to include new ids
403
                $cleanSlate = true;
404
            }
405
        } else {
406
            $cleanSlate = true;
407
408
            //lock the entity
409
            $model->lockEntity($entity);
410
        }
411
412
        if ($cleanSlate) {
413
            //clean slate
414
            $this->clearSessionComponents($objectId);
415
416
            //load existing events into session
417
            $triggerEvents   = [];
418
            $existingActions = $entity->getEvents()->toArray();
419
            foreach ($existingActions as $a) {
420
                $id     = $a->getId();
421
                $action = $a->convertToArray();
422
                unset($action['form']);
423
                $triggerEvents[$id] = $action;
424
            }
425
            $session->set('mautic.point.'.$objectId.'.triggerevents.modified', $triggerEvents);
426
            $deletedEvents = [];
427
        }
428
429
        return $this->delegateView([
430
            'viewParameters' => [
431
                'events'        => $model->getEventGroups(),
432
                'triggerEvents' => $triggerEvents,
433
                'deletedEvents' => $deletedEvents,
434
                'tmpl'          => $this->request->isXmlHttpRequest() ? $this->request->get('tmpl', 'index') : 'index',
435
                'entity'        => $entity,
436
                'form'          => $form->createView(),
437
                'sessionId'     => $objectId,
438
            ],
439
            'contentTemplate' => 'MauticPointBundle:Trigger:form.html.php',
440
            'passthroughVars' => [
441
                'activeLink'    => '#mautic_pointtrigger_index',
442
                'mauticContent' => 'pointTrigger',
443
                'route'         => $this->generateUrl('mautic_pointtrigger_action', [
444
                        'objectAction' => 'edit',
445
                        'objectId'     => $entity->getId(), ]
446
                ),
447
            ],
448
        ]);
449
    }
450
451
    /**
452
     * Clone an entity.
453
     *
454
     * @param int $objectId
455
     *
456
     * @return array|JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
457
     */
458
    public function cloneAction($objectId)
459
    {
460
        $model  = $this->getModel('point.trigger');
461
        $entity = $model->getEntity($objectId);
462
463
        if (null != $entity) {
464
            if (!$this->get('mautic.security')->isGranted('point:triggers:create')) {
465
                return $this->accessDenied();
466
            }
467
468
            $entity = clone $entity;
469
            $entity->setIsPublished(false);
470
        }
471
472
        return $this->newAction($entity);
473
    }
474
475
    /**
476
     * Deletes the entity.
477
     *
478
     * @param $objectId
479
     *
480
     * @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
481
     */
482
    public function deleteAction($objectId)
483
    {
484
        $page      = $this->get('session')->get('mautic.point.trigger.page', 1);
485
        $returnUrl = $this->generateUrl('mautic_pointtrigger_index', ['page' => $page]);
486
        $flashes   = [];
487
488
        $postActionVars = [
489
            'returnUrl'       => $returnUrl,
490
            'viewParameters'  => ['page' => $page],
491
            'contentTemplate' => 'MauticPointBundle:Trigger:index',
492
            'passthroughVars' => [
493
                'activeLink'    => '#mautic_pointtrigger_index',
494
                'mauticContent' => 'pointTrigger',
495
            ],
496
        ];
497
498
        if ('POST' == $this->request->getMethod()) {
499
            $model  = $this->getModel('point.trigger');
500
            $entity = $model->getEntity($objectId);
501
502
            if (null === $entity) {
503
                $flashes[] = [
504
                    'type'    => 'error',
505
                    'msg'     => 'mautic.point.trigger.error.notfound',
506
                    'msgVars' => ['%id%' => $objectId],
507
                ];
508
            } elseif (!$this->get('mautic.security')->isGranted('point:triggers:delete')) {
509
                return $this->accessDenied();
510
            } elseif ($model->isLocked($entity)) {
511
                return $this->isLocked($postActionVars, $entity, 'point.trigger');
512
            }
513
514
            $model->deleteEntity($entity);
515
516
            $identifier = $this->get('translator')->trans($entity->getName());
517
            $flashes[]  = [
518
                'type'    => 'notice',
519
                'msg'     => 'mautic.core.notice.deleted',
520
                'msgVars' => [
521
                    '%name%' => $identifier,
522
                    '%id%'   => $objectId,
523
                ],
524
            ];
525
        } //else don't do anything
526
527
        return $this->postActionRedirect(
528
            array_merge($postActionVars, [
529
                'flashes' => $flashes,
530
            ])
531
        );
532
    }
533
534
    /**
535
     * Deletes a group of entities.
536
     *
537
     * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
538
     */
539
    public function batchDeleteAction()
540
    {
541
        $page      = $this->get('session')->get('mautic.point.trigger.page', 1);
542
        $returnUrl = $this->generateUrl('mautic_pointtrigger_index', ['page' => $page]);
543
        $flashes   = [];
544
545
        $postActionVars = [
546
            'returnUrl'       => $returnUrl,
547
            'viewParameters'  => ['page' => $page],
548
            'contentTemplate' => 'MauticPointBundle:Trigger:index',
549
            'passthroughVars' => [
550
                'activeLink'    => '#mautic_pointtrigger_index',
551
                'mauticContent' => 'pointTrigger',
552
            ],
553
        ];
554
555
        if ('POST' == $this->request->getMethod()) {
556
            $model     = $this->getModel('point.trigger');
557
            $ids       = json_decode($this->request->query->get('ids', '{}'));
558
            $deleteIds = [];
559
560
            // Loop over the IDs to perform access checks pre-delete
561
            foreach ($ids as $objectId) {
562
                $entity = $model->getEntity($objectId);
563
564
                if (null === $entity) {
565
                    $flashes[] = [
566
                        'type'    => 'error',
567
                        'msg'     => 'mautic.point.trigger.error.notfound',
568
                        'msgVars' => ['%id%' => $objectId],
569
                    ];
570
                } elseif (!$this->get('mautic.security')->isGranted('point:triggers:delete')) {
571
                    $flashes[] = $this->accessDenied(true);
572
                } elseif ($model->isLocked($entity)) {
573
                    $flashes[] = $this->isLocked($postActionVars, $entity, 'point.trigger', true);
574
                } else {
575
                    $deleteIds[] = $objectId;
576
                }
577
            }
578
579
            // Delete everything we are able to
580
            if (!empty($deleteIds)) {
581
                $entities = $model->deleteEntities($deleteIds);
582
583
                $flashes[] = [
584
                    'type'    => 'notice',
585
                    'msg'     => 'mautic.point.trigger.notice.batch_deleted',
586
                    'msgVars' => [
587
                        '%count%' => count($entities),
588
                    ],
589
                ];
590
            }
591
        } //else don't do anything
592
593
        return $this->postActionRedirect(
594
            array_merge($postActionVars, [
595
                'flashes' => $flashes,
596
            ])
597
        );
598
    }
599
600
    /**
601
     * Clear field and events from the session.
602
     */
603
    public function clearSessionComponents($sessionId)
604
    {
605
        $session = $this->get('session');
606
        $session->remove('mautic.point.'.$sessionId.'.triggerevents.modified');
607
        $session->remove('mautic.point.'.$sessionId.'.triggerevents.deleted');
608
    }
609
}
610