Issues (3627)

bundles/EmailBundle/Controller/EmailController.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\EmailBundle\Controller;
13
14
use Mautic\CoreBundle\Controller\BuilderControllerTrait;
15
use Mautic\CoreBundle\Controller\FormController;
16
use Mautic\CoreBundle\Controller\FormErrorMessagesTrait;
17
use Mautic\CoreBundle\Event\DetermineWinnerEvent;
18
use Mautic\CoreBundle\Form\Type\BuilderSectionType;
19
use Mautic\CoreBundle\Form\Type\DateRangeType;
20
use Mautic\CoreBundle\Helper\EmojiHelper;
21
use Mautic\CoreBundle\Helper\InputHelper;
22
use Mautic\EmailBundle\Entity\Email;
23
use Mautic\EmailBundle\Form\Type\BatchSendType;
24
use Mautic\EmailBundle\Form\Type\ExampleSendType;
25
use Mautic\LeadBundle\Controller\EntityContactsTrait;
26
use Mautic\LeadBundle\Model\ListModel;
27
use MauticPlugin\MauticCitrixBundle\Helper\CitrixHelper;
28
use Symfony\Component\Form\Form;
29
use Symfony\Component\Form\FormError;
30
use Symfony\Component\HttpFoundation\JsonResponse;
31
use Symfony\Component\HttpFoundation\Response;
32
33
class EmailController extends FormController
34
{
35
    const EXAMPLE_EMAIL_SUBJECT_PREFIX = '[TEST]';
36
37
    use BuilderControllerTrait;
38
    use FormErrorMessagesTrait;
39
    use EntityContactsTrait;
40
41
    /**
42
     * @param int $page
43
     *
44
     * @return JsonResponse|\Symfony\Component\HttpFoundation\Response
45
     */
46
    public function indexAction($page = 1)
47
    {
48
        $model = $this->getModel('email');
49
50
        //set some permissions
51
        $permissions = $this->get('mautic.security')->isGranted(
52
            [
53
                'email:emails:viewown',
54
                'email:emails:viewother',
55
                'email:emails:create',
56
                'email:emails:editown',
57
                'email:emails:editother',
58
                'email:emails:deleteown',
59
                'email:emails:deleteother',
60
                'email:emails:publishown',
61
                'email:emails:publishother',
62
            ],
63
            'RETURN_ARRAY'
64
        );
65
66
        if (!$permissions['email:emails:viewown'] && !$permissions['email:emails:viewother']) {
67
            return $this->accessDenied();
68
        }
69
70
        $this->setListFilters();
71
72
        $session = $this->get('session');
73
74
        $listFilters = [
75
            'filters' => [
76
                'placeholder' => $this->get('translator')->trans('mautic.email.filter.placeholder'),
77
                'multiple'    => true,
78
            ],
79
        ];
80
81
        // Reset available groups
82
        $listFilters['filters']['groups'] = [];
83
84
        //set limits
85
        $limit = $session->get('mautic.email.limit', $this->coreParametersHelper->get('default_pagelimit'));
86
        $start = (1 === $page) ? 0 : (($page - 1) * $limit);
87
        if ($start < 0) {
88
            $start = 0;
89
        }
90
91
        $search = $this->request->get('search', $session->get('mautic.email.filter', ''));
92
        $session->set('mautic.email.filter', $search);
93
94
        $filter = [
95
            'string' => $search,
96
            'force'  => [
97
                ['column' => 'e.variantParent', 'expr' => 'isNull'],
98
                ['column' => 'e.translationParent', 'expr' => 'isNull'],
99
            ],
100
        ];
101
        if (!$permissions['email:emails:viewother']) {
102
            $filter['force'][] =
103
                ['column' => 'e.createdBy', 'expr' => 'eq', 'value' => $this->user->getId()];
104
        }
105
106
        //retrieve a list of Lead Lists
107
        $listFilters['filters']['groups']['mautic.core.filter.lists'] = [
108
            'options' => $this->getModel('lead.list')->getUserLists(),
109
            'prefix'  => 'list',
110
        ];
111
112
        //retrieve a list of themes
113
        $listFilters['filters']['groups']['mautic.core.filter.themes'] = [
114
            'options' => $this->factory->getInstalledThemes('email'),
115
            'prefix'  => 'theme',
116
        ];
117
118
        $currentFilters = $session->get('mautic.email.list_filters', []);
119
        $updatedFilters = $this->request->get('filters', false);
120
        $ignoreListJoin = true;
121
122
        if ($updatedFilters) {
123
            // Filters have been updated
124
125
            // Parse the selected values
126
            $newFilters     = [];
127
            $updatedFilters = json_decode($updatedFilters, true);
128
129
            if ($updatedFilters) {
130
                foreach ($updatedFilters as $updatedFilter) {
131
                    list($clmn, $fltr) = explode(':', $updatedFilter);
132
133
                    $newFilters[$clmn][] = $fltr;
134
                }
135
136
                $currentFilters = $newFilters;
137
            } else {
138
                $currentFilters = [];
139
            }
140
        }
141
        $session->set('mautic.email.list_filters', $currentFilters);
142
143
        if (!empty($currentFilters)) {
144
            $listIds = $catIds = $templates = [];
145
            foreach ($currentFilters as $type => $typeFilters) {
146
                switch ($type) {
147
                    case 'list':
148
                        $key = 'lists';
149
                        break;
150
                    case 'category':
151
                        $key = 'categories';
152
                        break;
153
                    case 'theme':
154
                        $key = 'themes';
155
                        break;
156
                }
157
158
                $listFilters['filters']['groups']['mautic.core.filter.'.$key]['values'] = $typeFilters;
159
160
                foreach ($typeFilters as $fltr) {
161
                    switch ($type) {
162
                        case 'list':
163
                            $listIds[] = (int) $fltr;
164
                            break;
165
                        case 'category':
166
                            $catIds[] = (int) $fltr;
167
                            break;
168
                        case 'theme':
169
                            $templates[] = $fltr;
170
                            break;
171
                    }
172
                }
173
            }
174
175
            if (!empty($listIds)) {
176
                $filter['force'][] = ['column' => 'l.id', 'expr' => 'in', 'value' => $listIds];
177
                $ignoreListJoin    = false;
178
            }
179
180
            if (!empty($catIds)) {
181
                $filter['force'][] = ['column' => 'c.id', 'expr' => 'in', 'value' => $catIds];
182
            }
183
184
            if (!empty($templates)) {
185
                $filter['force'][] = ['column' => 'e.template', 'expr' => 'in', 'value' => $templates];
186
            }
187
        }
188
189
        $orderBy    = $session->get('mautic.email.orderby', 'e.subject');
190
        $orderByDir = $session->get('mautic.email.orderbydir', 'DESC');
191
192
        $emails = $model->getEntities(
193
            [
194
                'start'          => $start,
195
                'limit'          => $limit,
196
                'filter'         => $filter,
197
                'orderBy'        => $orderBy,
198
                'orderByDir'     => $orderByDir,
199
                'ignoreListJoin' => $ignoreListJoin,
200
            ]
201
        );
202
203
        $count = count($emails);
204
        if ($count && $count < ($start + 1)) {
205
            //the number of entities are now less then the current page so redirect to the last page
206
            if (1 === $count) {
207
                $lastPage = 1;
208
            } else {
209
                $lastPage = (floor($count / $limit)) ?: 1;
210
            }
211
212
            $session->set('mautic.email.page', $lastPage);
213
            $returnUrl = $this->generateUrl('mautic_email_index', ['page' => $lastPage]);
214
215
            return $this->postActionRedirect(
216
                [
217
                    'returnUrl'       => $returnUrl,
218
                    'viewParameters'  => ['page' => $lastPage],
219
                    'contentTemplate' => 'MauticEmailBundle:Email:index',
220
                    'passthroughVars' => [
221
                        'activeLink'    => '#mautic_email_index',
222
                        'mauticContent' => 'email',
223
                    ],
224
                ]
225
            );
226
        }
227
        $session->set('mautic.email.page', $page);
228
229
        return $this->delegateView(
230
            [
231
                'viewParameters' => [
232
                    'searchValue' => $search,
233
                    'filters'     => $listFilters,
234
                    'items'       => $emails,
235
                    'totalItems'  => $count,
236
                    'page'        => $page,
237
                    'limit'       => $limit,
238
                    'tmpl'        => $this->request->get('tmpl', 'index'),
239
                    'permissions' => $permissions,
240
                    'model'       => $model,
241
                ],
242
                'contentTemplate' => 'MauticEmailBundle:Email:list.html.php',
243
                'passthroughVars' => [
244
                    'activeLink'    => '#mautic_email_index',
245
                    'mauticContent' => 'email',
246
                    'route'         => $this->generateUrl('mautic_email_index', ['page' => $page]),
247
                ],
248
            ]
249
        );
250
    }
251
252
    /**
253
     * Loads a specific form into the detailed panel.
254
     *
255
     * @param $objectId
256
     *
257
     * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response
258
     */
259
    public function viewAction($objectId)
260
    {
261
        /** @var \Mautic\EmailBundle\Model\EmailModel $model */
262
        $model    = $this->getModel('email');
263
        $security = $this->get('mautic.security');
264
265
        /** @var \Mautic\EmailBundle\Entity\Email $email */
266
        $email = $model->getEntity($objectId);
267
        //set the page we came from
268
        $page = $this->get('session')->get('mautic.email.page', 1);
269
270
        // Init the date range filter form
271
        $dateRangeValues = $this->request->get('daterange', []);
272
        $action          = $this->generateUrl('mautic_email_action', ['objectAction' => 'view', 'objectId' => $objectId]);
273
        $dateRangeForm   = $this->get('form.factory')->create(DateRangeType::class, $dateRangeValues, ['action' => $action]);
274
275
        if (null === $email) {
276
            //set the return URL
277
            $returnUrl = $this->generateUrl('mautic_email_index', ['page' => $page]);
278
279
            return $this->postActionRedirect(
280
                [
281
                    'returnUrl'       => $returnUrl,
282
                    'viewParameters'  => ['page' => $page],
283
                    'contentTemplate' => 'MauticEmailBundle:Email:index',
284
                    'passthroughVars' => [
285
                        'activeLink'    => '#mautic_email_index',
286
                        'mauticContent' => 'email',
287
                    ],
288
                    'flashes' => [
289
                        [
290
                            'type'    => 'error',
291
                            'msg'     => 'mautic.email.error.notfound',
292
                            'msgVars' => ['%id%' => $objectId],
293
                        ],
294
                    ],
295
                ]
296
            );
297
        } elseif (!$this->get('mautic.security')->hasEntityAccess(
298
            'email:emails:viewown',
299
            'email:emails:viewother',
300
            $email->getCreatedBy()
301
        )
302
        ) {
303
            return $this->accessDenied();
304
        }
305
306
        //get A/B test information
307
        list($parent, $children) = $email->getVariants();
308
        $properties              = [];
309
        $variantError            = false;
310
        $weight                  = 0;
311
        if (count($children)) {
312
            foreach ($children as $c) {
313
                $variantSettings = $c->getVariantSettings();
314
315
                if (is_array($variantSettings) && isset($variantSettings['winnerCriteria'])) {
316
                    if ($c->isPublished()) {
317
                        if (!isset($lastCriteria)) {
318
                            $lastCriteria = $variantSettings['winnerCriteria'];
319
                        }
320
321
                        //make sure all the variants are configured with the same criteria
322
                        if ($lastCriteria != $variantSettings['winnerCriteria']) {
323
                            $variantError = true;
324
                        }
325
326
                        $weight += $variantSettings['weight'];
327
                    }
328
                } else {
329
                    $variantSettings['winnerCriteria'] = '';
330
                    $variantSettings['weight']         = 0;
331
                }
332
333
                $properties[$c->getId()] = $variantSettings;
334
            }
335
336
            $properties[$parent->getId()]['weight']         = 100 - $weight;
337
            $properties[$parent->getId()]['winnerCriteria'] = '';
338
        }
339
340
        $abTestResults = [];
341
        $criteria      = $model->getBuilderComponents($email, 'abTestWinnerCriteria');
342
        if (!empty($lastCriteria) && empty($variantError)) {
343
            if (isset($criteria['criteria'][$lastCriteria])) {
344
                $testSettings = $criteria['criteria'][$lastCriteria];
345
346
                $args = [
347
                    'email'      => $email,
348
                    'parent'     => $parent,
349
                    'children'   => $children,
350
                    'properties' => $properties,
351
                ];
352
353
                $event = new DetermineWinnerEvent($args);
354
                $this->dispatcher->dispatch(
355
                        $testSettings['event'],
356
                        $event
357
                    );
358
359
                $abTestResults = $event->getAbTestResults();
360
            }
361
        }
362
363
        //get related translations
364
        list($translationParent, $translationChildren) = $email->getTranslations();
365
366
        // Audit Log
367
        $logs = $this->getModel('core.auditlog')->getLogForObject('email', $email->getId(), $email->getDateAdded());
368
369
        // Get click through stats
370
        $trackableLinks = $model->getEmailClickStats($email->getId());
371
372
        return $this->delegateView(
373
            [
374
                'returnUrl' => $this->generateUrl(
375
                    'mautic_email_action',
376
                    [
377
                        'objectAction' => 'view',
378
                        'objectId'     => $email->getId(),
379
                    ]
380
                ),
381
                'viewParameters' => [
382
                    'email'        => $email,
383
                    'trackables'   => $trackableLinks,
384
                    'pending'      => $model->getPendingLeads($email, null, true),
385
                    'logs'         => $logs,
386
                    'isEmbedded'   => $this->request->get('isEmbedded') ? $this->request->get('isEmbedded') : false,
387
                    'variants'     => [
388
                        'parent'     => $parent,
389
                        'children'   => $children,
390
                        'properties' => $properties,
391
                        'criteria'   => $criteria['criteria'],
392
                    ],
393
                    'translations' => [
394
                        'parent'   => $translationParent,
395
                        'children' => $translationChildren,
396
                    ],
397
                    'permissions' => $security->isGranted(
398
                        [
399
                            'email:emails:viewown',
400
                            'email:emails:viewother',
401
                            'email:emails:create',
402
                            'email:emails:editown',
403
                            'email:emails:editother',
404
                            'email:emails:deleteown',
405
                            'email:emails:deleteother',
406
                            'email:emails:publishown',
407
                            'email:emails:publishother',
408
                        ],
409
                        'RETURN_ARRAY'
410
                    ),
411
                    'abTestResults' => $abTestResults,
412
                    'security'      => $security,
413
                    'previewUrl'    => $this->generateUrl(
414
                        'mautic_email_preview',
415
                        ['objectId' => $email->getId()],
416
                        true
417
                    ),
418
                    'contacts' => $this->forward(
419
                        'MauticEmailBundle:Email:contacts',
420
                        [
421
                            'objectId'   => $email->getId(),
422
                            'page'       => $this->get('session')->get('mautic.email.contact.page', 1),
423
                            'ignoreAjax' => true,
424
                        ]
425
                    )->getContent(),
426
                    'dateRangeForm' => $dateRangeForm->createView(),
427
                ],
428
                'contentTemplate' => 'MauticEmailBundle:Email:details.html.php',
429
                'passthroughVars' => [
430
                    'activeLink'    => '#mautic_email_index',
431
                    'mauticContent' => 'email',
432
                ],
433
            ]
434
        );
435
    }
436
437
    /**
438
     * Generates new form and processes post data.
439
     *
440
     * @param \Mautic\EmailBundle\Entity\Email $entity
441
     *
442
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
443
     */
444
    public function newAction($entity = null)
445
    {
446
        $model = $this->getModel('email');
447
448
        if (!($entity instanceof Email)) {
449
            /** @var \Mautic\EmailBundle\Entity\Email $entity */
450
            $entity = $model->getEntity();
451
        }
452
453
        $method  = $this->request->getMethod();
454
        $session = $this->get('session');
455
456
        if (!$this->get('mautic.security')->isGranted('email:emails:create')) {
457
            return $this->accessDenied();
458
        }
459
460
        //set the page we came from
461
        $page         = $session->get('mautic.email.page', 1);
462
        $action       = $this->generateUrl('mautic_email_action', ['objectAction' => 'new']);
463
        $emailForm    = $this->request->request->get('emailform', []);
464
        $updateSelect = 'POST' === $method
465
            ? ($emailForm['updateSelect'] ?? false)
466
            : $this->request->get('updateSelect', false);
467
468
        if ($updateSelect) {
469
            // Force type to template
470
            $entity->setEmailType('template');
471
        }
472
473
        //create the form
474
        $form = $model->createForm($entity, $this->get('form.factory'), $action, ['update_select' => $updateSelect]);
475
476
        ///Check for a submitted form and process it
477
        if ('POST' === $method) {
478
            $valid = false;
479
480
            if (!$cancelled = $this->isFormCancelled($form)) {
481
                $formData = $this->request->request->get('emailform');
482
                if ($valid = $this->isFormValid($form) && $this->isFormValidForWebinar($formData, $form, $entity)) {
483
                    $content = $entity->getCustomHtml();
484
485
                    $entity->setCustomHtml($content);
486
487
                    //form is valid so process the data
488
                    $model->saveEntity($entity);
489
490
                    $this->addFlash(
491
                        'mautic.core.notice.created',
492
                        [
493
                            '%name%'      => $entity->getName(),
494
                            '%menu_link%' => 'mautic_email_index',
495
                            '%url%'       => $this->generateUrl(
496
                                'mautic_email_action',
497
                                [
498
                                    'objectAction' => 'edit',
499
                                    'objectId'     => $entity->getId(),
500
                                ]
501
                            ),
502
                        ]
503
                    );
504
505
                    if ($form->get('buttons')->get('save')->isClicked()) {
506
                        $viewParameters = [
507
                            'objectAction' => 'view',
508
                            'objectId'     => $entity->getId(),
509
                        ];
510
                        $returnUrl = $this->generateUrl('mautic_email_action', $viewParameters);
511
                        $template  = 'MauticEmailBundle:Email:view';
512
                    } else {
513
                        //return edit view so that all the session stuff is loaded
514
                        return $this->editAction($entity->getId(), true);
515
                    }
516
                }
517
            } else {
518
                $viewParameters = ['page' => $page];
519
                $returnUrl      = $this->generateUrl('mautic_email_index', $viewParameters);
520
                $template       = 'MauticEmailBundle:Email:index';
521
                //clear any modified content
522
                $session->remove('mautic.emailbuilder.'.$entity->getSessionId().'.content');
523
            }
524
525
            $passthrough = [
526
                'activeLink'    => 'mautic_email_index',
527
                'mauticContent' => 'email',
528
            ];
529
530
            // Check to see if this is a popup
531
            if (isset($form['updateSelect'])) {
532
                $template    = false;
533
                $passthrough = array_merge(
534
                    $passthrough,
535
                    [
536
                        'updateSelect' => $form['updateSelect']->getData(),
537
                        'id'           => $entity->getId(),
538
                        'name'         => $entity->getName(),
539
                        'group'        => $entity->getLanguage(),
540
                    ]
541
                );
542
            }
543
544
            if ($cancelled || ($valid && $form->get('buttons')->get('save')->isClicked())) {
545
                return $this->postActionRedirect(
546
                    [
547
                        'returnUrl'       => $returnUrl,
548
                        'viewParameters'  => $viewParameters,
549
                        'contentTemplate' => $template,
550
                        'passthroughVars' => $passthrough,
551
                    ]
552
                );
553
            }
554
        }
555
556
        $slotTypes   = $model->getBuilderComponents($entity, 'slotTypes');
557
        $sections    = $model->getBuilderComponents($entity, 'sections');
558
        $sectionForm = $this->get('form.factory')->create(BuilderSectionType::class);
559
        $routeParams = [
560
            'objectAction' => 'new',
561
        ];
562
        if ($updateSelect) {
563
            $routeParams['updateSelect'] = $updateSelect;
564
            $routeParams['contentOnly']  = 1;
565
        }
566
567
        //set some permissions
568
        $permissions = $this->get('mautic.security')->isGranted(
569
            [
570
                'page:preference_center:viewown',
571
                'page:preference_center:viewother',
572
            ],
573
            'RETURN_ARRAY'
574
        );
575
576
        return $this->delegateView(
577
            [
578
                'viewParameters' => [
579
                    'form'          => $this->setFormTheme($form, 'MauticEmailBundle:Email:form.html.php', 'MauticEmailBundle:FormTheme\Email'),
580
                    'isVariant'     => $entity->isVariant(true),
581
                    'email'         => $entity,
582
                    'slots'         => $this->buildSlotForms($slotTypes),
583
                    'sections'      => $this->buildSlotForms($sections),
584
                    'themes'        => $this->factory->getInstalledThemes('email', true),
585
                    'builderAssets' => trim(preg_replace('/\s+/', ' ', $this->getAssetsForBuilder())), // strip new lines
586
                    'sectionForm'   => $sectionForm->createView(),
587
                    'updateSelect'  => $updateSelect,
588
                    'permissions'   => $permissions,
589
                ],
590
                'contentTemplate' => 'MauticEmailBundle:Email:form.html.php',
591
                'passthroughVars' => [
592
                    'activeLink'      => '#mautic_email_index',
593
                    'mauticContent'   => 'email',
594
                    'updateSelect'    => $updateSelect,
595
                    'route'           => $this->generateUrl('mautic_email_action', $routeParams),
596
                    'validationError' => $this->getFormErrorForBuilder($form),
597
                ],
598
            ]
599
        );
600
    }
601
602
    /**
603
     * @param      $objectId
604
     * @param bool $ignorePost
605
     * @param bool $forceTypeSelection
606
     *
607
     * @return array|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
608
     */
609
    public function editAction($objectId, $ignorePost = false, $forceTypeSelection = false)
610
    {
611
        /** @var \Mautic\EmailBundle\Model\EmailModel $model */
612
        $model  = $this->getModel('email');
613
        $method = $this->request->getMethod();
614
615
        $entity  = $model->getEntity($objectId);
616
        $session = $this->get('session');
617
        $page    = $this->get('session')->get('mautic.email.page', 1);
618
619
        //set the return URL
620
        $returnUrl = $this->generateUrl('mautic_email_index', ['page' => $page]);
621
622
        $postActionVars = [
623
            'returnUrl'       => $returnUrl,
624
            'viewParameters'  => ['page' => $page],
625
            'contentTemplate' => 'MauticEmailBundle:Email:index',
626
            'passthroughVars' => [
627
                'activeLink'    => 'mautic_email_index',
628
                'mauticContent' => 'email',
629
            ],
630
        ];
631
632
        //not found
633
        if (null === $entity) {
634
            return $this->postActionRedirect(
635
                array_merge(
636
                    $postActionVars,
637
                    [
638
                        'flashes' => [
639
                            [
640
                                'type'    => 'error',
641
                                'msg'     => 'mautic.email.error.notfound',
642
                                'msgVars' => ['%id%' => $objectId],
643
                            ],
644
                        ],
645
                    ]
646
                )
647
            );
648
        } elseif (!$this->get('mautic.security')->hasEntityAccess(
649
            'email:emails:editown',
650
            'email:emails:editother',
651
            $entity->getCreatedBy()
652
        )
653
        ) {
654
            return $this->accessDenied();
655
        } elseif ($model->isLocked($entity)) {
656
            //deny access if the entity is locked
657
            return $this->isLocked($postActionVars, $entity, 'email');
658
        }
659
660
        //Create the form
661
        $action       = $this->generateUrl('mautic_email_action', ['objectAction' => 'edit', 'objectId' => $objectId]);
662
        $emailform    = $this->request->request->get('emailform', []);
663
        $updateSelect = 'POST' === $method
664
            ? ($emailform['updateSelect'] ?? false)
665
            : $this->request->get('updateSelect', false);
666
667
        if ($updateSelect) {
668
            // Force type to template
669
            $entity->setEmailType('template');
670
        }
671
        /** @var Form $form */
672
        $form = $model->createForm($entity, $this->get('form.factory'), $action, ['update_select' => $updateSelect]);
673
674
        ///Check for a submitted form and process it
675
        if (!$ignorePost && 'POST' === $method) {
676
            $valid = false;
677
            if (!$cancelled = $this->isFormCancelled($form)) {
678
                $formData = $this->request->request->get('emailform');
679
                if ($valid = $this->isFormValid($form) && $this->isFormValidForWebinar($formData, $form, $entity)) {
680
                    $content = $entity->getCustomHtml();
681
                    $entity->setCustomHtml($content);
682
683
                    //form is valid so process the data
684
                    $model->saveEntity($entity, $form->get('buttons')->get('save')->isClicked());
685
686
                    $this->addFlash(
687
                        'mautic.core.notice.updated',
688
                        [
689
                            '%name%'      => $entity->getName(),
690
                            '%menu_link%' => 'mautic_email_index',
691
                            '%url%'       => $this->generateUrl(
692
                                'mautic_email_action',
693
                                [
694
                                    'objectAction' => 'edit',
695
                                    'objectId'     => $entity->getId(),
696
                                ]
697
                            ),
698
                        ],
699
                        'warning'
700
                    );
701
                }
702
            } else {
703
                //clear any modified content
704
                $session->remove('mautic.emailbuilder.'.$objectId.'.content');
705
                //unlock the entity
706
                $model->unlockEntity($entity);
707
            }
708
709
            $template    = 'MauticEmailBundle:Email:view';
710
            $passthrough = [
711
                'activeLink'    => 'mautic_email_index',
712
                'mauticContent' => 'email',
713
            ];
714
715
            // Check to see if this is a popup
716
            if (isset($form['updateSelect'])) {
717
                $template    = false;
718
                $passthrough = array_merge(
719
                    $passthrough,
720
                    [
721
                        'updateSelect' => $form['updateSelect']->getData(),
722
                        'id'           => $entity->getId(),
723
                        'name'         => $entity->getName(),
724
                        'group'        => $entity->getLanguage(),
725
                    ]
726
                );
727
            }
728
729
            if ($cancelled || ($valid && $form->get('buttons')->get('save')->isClicked())) {
730
                $viewParameters = [
731
                    'objectAction' => 'view',
732
                    'objectId'     => $entity->getId(),
733
                ];
734
735
                return $this->postActionRedirect(
736
                    array_merge(
737
                        $postActionVars,
738
                        [
739
                            'returnUrl'       => $this->generateUrl('mautic_email_action', $viewParameters),
740
                            'viewParameters'  => $viewParameters,
741
                            'contentTemplate' => $template,
742
                            'passthroughVars' => $passthrough,
743
                        ]
744
                    )
745
                );
746
            } elseif ($valid && $form->get('buttons')->get('apply')->isClicked()) {
747
                // Rebuild the form in the case apply is clicked so that DEC content is properly populated if all were removed
748
                $form = $model->createForm($entity, $this->get('form.factory'), $action, ['update_select' => $updateSelect]);
749
            }
750
        } else {
751
            //lock the entity
752
            $model->lockEntity($entity);
753
754
            //clear any modified content
755
            $session->remove('mautic.emailbuilder.'.$objectId.'.content');
756
757
            // Set to view content
758
            $template = $entity->getTemplate();
759
            if (empty($template)) {
760
                $content = $entity->getCustomHtml();
761
                $form['customHtml']->setData($content);
762
            }
763
        }
764
765
        $assets         = $form['assetAttachments']->getData();
766
        $attachmentSize = $this->getModel('asset')->getTotalFilesize($assets);
767
768
        $slotTypes   = $model->getBuilderComponents($entity, 'slotTypes');
769
        $sections    = $model->getBuilderComponents($entity, 'sections');
770
        $sectionForm = $this->get('form.factory')->create(BuilderSectionType::class);
771
        $routeParams = [
772
            'objectAction' => 'edit',
773
            'objectId'     => $entity->getId(),
774
        ];
775
        if ($updateSelect) {
776
            $routeParams['updateSelect'] = $updateSelect;
777
            $routeParams['contentOnly']  = 1;
778
        }
779
780
        //set some permissions
781
        $permissions = $this->get('mautic.security')->isGranted(
782
            [
783
                'page:preference_center:viewown',
784
                'page:preference_center:viewother',
785
            ],
786
            'RETURN_ARRAY'
787
        );
788
789
        return $this->delegateView(
790
            [
791
                'viewParameters' => [
792
                    'form'               => $this->setFormTheme($form, 'MauticEmailBundle:Email:form.html.php', 'MauticEmailBundle:FormTheme\Email'),
793
                    'isVariant'          => $entity->isVariant(true),
794
                    'slots'              => $this->buildSlotForms($slotTypes),
795
                    'sections'           => $this->buildSlotForms($sections),
796
                    'themes'             => $this->factory->getInstalledThemes('email', true),
797
                    'email'              => $entity,
798
                    'forceTypeSelection' => $forceTypeSelection,
799
                    'attachmentSize'     => $attachmentSize,
800
                    'builderAssets'      => trim(preg_replace('/\s+/', ' ', $this->getAssetsForBuilder())), // strip new lines
801
                    'sectionForm'        => $sectionForm->createView(),
802
                    'permissions'        => $permissions,
803
                    'previewUrl'         => $this->generateUrl(
804
                        'mautic_email_preview',
805
                        ['objectId' => $entity->getId()],
806
                        true
807
                    ),
808
                ],
809
                'contentTemplate' => 'MauticEmailBundle:Email:form.html.php',
810
                'passthroughVars' => [
811
                    'activeLink'      => '#mautic_email_index',
812
                    'mauticContent'   => 'email',
813
                    'updateSelect'    => InputHelper::clean($this->request->query->get('updateSelect')),
814
                    'route'           => $this->generateUrl('mautic_email_action', $routeParams),
815
                    'validationError' => $this->getFormErrorForBuilder($form),
816
                ],
817
            ]
818
        );
819
    }
820
821
    /**
822
     * Clone an entity.
823
     *
824
     * @param $objectId
825
     *
826
     * @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
827
     */
828
    public function cloneAction($objectId)
829
    {
830
        $model = $this->getModel('email');
831
        /** @var Email $entity */
832
        $entity = $model->getEntity($objectId);
833
834
        if (null != $entity) {
835
            if (!$this->get('mautic.security')->isGranted('email:emails:create')
836
                || !$this->get('mautic.security')->hasEntityAccess(
837
                    'email:emails:viewown',
838
                    'email:emails:viewother',
839
                    $entity->getCreatedBy()
840
                )
841
            ) {
842
                return $this->accessDenied();
843
            }
844
845
            $entity      = clone $entity;
846
            $session     = $this->get('session');
847
            $contentName = 'mautic.emailbuilder.'.$entity->getSessionId().'.content';
848
849
            $session->set($contentName, $entity->getCustomHtml());
850
        }
851
852
        return $this->newAction($entity);
853
    }
854
855
    /**
856
     * Deletes the entity.
857
     *
858
     * @param $objectId
859
     *
860
     * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
861
     */
862
    public function deleteAction($objectId)
863
    {
864
        $page      = $this->get('session')->get('mautic.email.page', 1);
865
        $returnUrl = $this->generateUrl('mautic_email_index', ['page' => $page]);
866
        $flashes   = [];
867
868
        $postActionVars = [
869
            'returnUrl'       => $returnUrl,
870
            'viewParameters'  => ['page' => $page],
871
            'contentTemplate' => 'MauticEmailBundle:Email:index',
872
            'passthroughVars' => [
873
                'activeLink'    => 'mautic_email_index',
874
                'mauticContent' => 'email',
875
            ],
876
        ];
877
878
        if ('POST' == $this->request->getMethod()) {
879
            $model  = $this->getModel('email');
880
            $entity = $model->getEntity($objectId);
881
882
            if (null === $entity) {
883
                $flashes[] = [
884
                    'type'    => 'error',
885
                    'msg'     => 'mautic.email.error.notfound',
886
                    'msgVars' => ['%id%' => $objectId],
887
                ];
888
            } elseif (!$this->get('mautic.security')->hasEntityAccess(
889
                'email:emails:deleteown',
890
                'email:emails:deleteother',
891
                $entity->getCreatedBy()
892
            )
893
            ) {
894
                return $this->accessDenied();
895
            } elseif ($model->isLocked($entity)) {
896
                return $this->isLocked($postActionVars, $entity, 'email');
897
            }
898
899
            $model->deleteEntity($entity);
900
901
            $flashes[] = [
902
                'type'    => 'notice',
903
                'msg'     => 'mautic.core.notice.deleted',
904
                'msgVars' => [
905
                    '%name%' => $entity->getName(),
906
                    '%id%'   => $objectId,
907
                ],
908
            ];
909
        } //else don't do anything
910
911
        return $this->postActionRedirect(
912
            array_merge(
913
                $postActionVars,
914
                [
915
                    'flashes' => $flashes,
916
                ]
917
            )
918
        );
919
    }
920
921
    /**
922
     * Activate the builder.
923
     *
924
     * @param $objectId
925
     *
926
     * @return array|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
927
     *
928
     * @throws \Exception
929
     * @throws \Mautic\CoreBundle\Exception\FileNotFoundException
930
     */
931
    public function builderAction($objectId)
932
    {
933
        /** @var \Mautic\EmailBundle\Model\EmailModel $model */
934
        $model = $this->getModel('email');
935
936
        //permission check
937
        if (false !== strpos($objectId, 'new')) {
938
            $isNew = true;
939
            if (!$this->get('mautic.security')->isGranted('email:emails:create')) {
940
                return $this->accessDenied();
941
            }
942
            $entity = $model->getEntity();
943
            $entity->setSessionId($objectId);
944
        } else {
945
            $isNew  = false;
946
            $entity = $model->getEntity($objectId);
947
            if (null == $entity
948
                || !$this->get('mautic.security')->hasEntityAccess(
949
                    'email:emails:viewown',
950
                    'email:emails:viewother',
951
                    $entity->getCreatedBy()
952
                )
953
            ) {
954
                return $this->accessDenied();
955
            }
956
        }
957
958
        $template = InputHelper::clean($this->request->query->get('template'));
959
        $slots    = $this->factory->getTheme($template)->getSlots('email');
960
961
        //merge any existing changes
962
        $newContent = $this->get('session')->get('mautic.emailbuilder.'.$objectId.'.content', []);
963
        $content    = $entity->getContent();
964
965
        if (is_array($newContent)) {
966
            $content = array_merge($content, $newContent);
967
            // Update the content for processSlots
968
            $entity->setContent($content);
969
        }
970
971
        // Replace short codes to emoji
972
        $content = EmojiHelper::toEmoji($content, 'short');
973
974
        $this->processSlots($slots, $entity);
975
976
        $logicalName = $this->factory->getHelper('theme')->checkForTwigTemplate(':'.$template.':email.html.php');
977
978
        return $this->render(
979
            $logicalName,
980
            [
981
                'isNew'    => $isNew,
982
                'slots'    => $slots,
983
                'content'  => $content,
984
                'email'    => $entity,
985
                'template' => $template,
986
                'basePath' => $this->request->getBasePath(),
987
            ]
988
        );
989
    }
990
991
    /**
992
     * Create an AB test.
993
     *
994
     * @param $objectId
995
     *
996
     * @return array|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
997
     */
998
    public function abtestAction($objectId)
999
    {
1000
        $model  = $this->getModel('email');
1001
        $entity = $model->getEntity($objectId);
1002
1003
        if (null != $entity) {
1004
            $parent = $entity->getVariantParent();
1005
1006
            if ($parent || !$this->get('mautic.security')->isGranted('email:emails:create')
1007
                || !$this->get('mautic.security')->hasEntityAccess(
1008
                    'email:emails:viewown',
1009
                    'email:emails:viewother',
1010
                    $entity->getCreatedBy()
1011
                )
1012
            ) {
1013
                return $this->accessDenied();
1014
            }
1015
1016
            // Note this since it's cleared on __clone()
1017
            $emailType = $entity->getEmailType();
1018
1019
            $clone = clone $entity;
1020
1021
            $clone->setIsPublished(false);
1022
            $clone->setEmailType($emailType);
1023
            $clone->setVariantParent($entity);
1024
        }
1025
1026
        return $this->newAction($clone);
1027
    }
1028
1029
    /**
1030
     * Make the variant the main.
1031
     *
1032
     * @param $objectId
1033
     *
1034
     * @return array|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
1035
     */
1036
    public function winnerAction($objectId)
1037
    {
1038
        //todo - add confirmation to button click
1039
        $page      = $this->get('session')->get('mautic.email', 1);
1040
        $returnUrl = $this->generateUrl('mautic_email_index', ['page' => $page]);
1041
        $flashes   = [];
1042
1043
        $postActionVars = [
1044
            'returnUrl'       => $returnUrl,
1045
            'viewParameters'  => ['page' => $page],
1046
            'contentTemplate' => 'MauticEmailBundle:Page:index',
1047
            'passthroughVars' => [
1048
                'activeLink'    => 'mautic_email_index',
1049
                'mauticContent' => 'page',
1050
            ],
1051
        ];
1052
1053
        if ('POST' == $this->request->getMethod()) {
1054
            $model  = $this->getModel('email');
1055
            $entity = $model->getEntity($objectId);
1056
1057
            if (null === $entity) {
1058
                $flashes[] = [
1059
                    'type'    => 'error',
1060
                    'msg'     => 'mautic.email.error.notfound',
1061
                    'msgVars' => ['%id%' => $objectId],
1062
                ];
1063
            } elseif (!$this->get('mautic.security')->hasEntityAccess(
1064
                'email:emails:editown',
1065
                'email:emails:editother',
1066
                $entity->getCreatedBy()
1067
            )
1068
            ) {
1069
                return $this->accessDenied();
1070
            } elseif ($model->isLocked($entity)) {
1071
                return $this->isLocked($postActionVars, $entity, 'email');
1072
            }
1073
1074
            $model->convertVariant($entity);
1075
1076
            $flashes[] = [
1077
                'type'    => 'notice',
1078
                'msg'     => 'mautic.email.notice.activated',
1079
                'msgVars' => [
1080
                    '%name%' => $entity->getName(),
1081
                    '%id%'   => $objectId,
1082
                ],
1083
            ];
1084
1085
            $postActionVars['viewParameters'] = [
1086
                'objectAction' => 'view',
1087
                'objectId'     => $objectId,
1088
            ];
1089
            $postActionVars['returnUrl']       = $this->generateUrl('mautic_page_action', $postActionVars['viewParameters']);
1090
            $postActionVars['contentTemplate'] = 'MauticEmailBundle:Email:view';
1091
        } //else don't do anything
1092
1093
        return $this->postActionRedirect(
1094
            array_merge(
1095
                $postActionVars,
1096
                [
1097
                    'flashes' => $flashes,
1098
                ]
1099
            )
1100
        );
1101
    }
1102
1103
    /**
1104
     * Manually sends emails.
1105
     *
1106
     * @param $objectId
1107
     *
1108
     * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
1109
     */
1110
    public function sendAction($objectId)
1111
    {
1112
        /** @var \Mautic\EmailBundle\Model\EmailModel $model */
1113
        $model   = $this->getModel('email');
1114
        $entity  = $model->getEntity($objectId);
1115
        $session = $this->container->get('session');
1116
        $page    = $session->get('mautic.email.page', 1);
1117
1118
        //set the return URL
1119
        $returnUrl = $this->generateUrl('mautic_email_index', ['page' => $page]);
1120
1121
        $postActionVars = [
1122
            'returnUrl'       => $returnUrl,
1123
            'viewParameters'  => ['page' => $page],
1124
            'contentTemplate' => 'MauticEmailBundle:Email:index',
1125
            'passthroughVars' => [
1126
                'activeLink'    => 'mautic_email_index',
1127
                'mauticContent' => 'email',
1128
            ],
1129
        ];
1130
1131
        //not found
1132
        if (null === $entity) {
1133
            return $this->postActionRedirect(
1134
                array_merge(
1135
                    $postActionVars,
1136
                    [
1137
                        'flashes' => [
1138
                            [
1139
                                'type'    => 'error',
1140
                                'msg'     => 'mautic.email.error.notfound',
1141
                                'msgVars' => ['%id%' => $objectId],
1142
                            ],
1143
                        ],
1144
                    ]
1145
                )
1146
            );
1147
        }
1148
1149
        if (!$entity->isPublished()) {
1150
            return $this->postActionRedirect(
1151
                array_merge(
1152
                    $postActionVars,
1153
                    [
1154
                        'flashes' => [
1155
                            [
1156
                                'type'    => 'error',
1157
                                'msg'     => 'mautic.email.error.send.unpublished',
1158
                                'msgVars' => [
1159
                                    '%id%'   => $objectId,
1160
                                    '%name%' => $entity->getName(),
1161
                                ],
1162
                            ],
1163
                        ],
1164
                    ]
1165
                )
1166
            );
1167
        }
1168
1169
        if ('template' == $entity->getEmailType()
1170
            || !$this->get('mautic.security')->hasEntityAccess(
1171
                'email:emails:viewown',
1172
                'email:emails:viewother',
1173
                $entity->getCreatedBy()
1174
            )
1175
        ) {
1176
            return $this->accessDenied();
1177
        }
1178
1179
        // Check that the parent is getting sent
1180
        if ($variantParent = $entity->getVariantParent()) {
1181
            return $this->redirect($this->generateUrl('mautic_email_action',
1182
                [
1183
                    'objectAction' => 'send',
1184
                    'objectId'     => $variantParent->getId(),
1185
                ]
1186
            ));
1187
        }
1188
1189
        if ($translationParent = $entity->getTranslationParent()) {
1190
            return $this->redirect($this->generateUrl('mautic_email_action',
1191
                [
1192
                    'objectAction' => 'send',
1193
                    'objectId'     => $translationParent->getId(),
1194
                ]
1195
            ));
1196
        }
1197
1198
        $action   = $this->generateUrl('mautic_email_action', ['objectAction' => 'send', 'objectId' => $objectId]);
1199
        $pending  = $model->getPendingLeads($entity, null, true);
1200
        $form     = $this->get('form.factory')->create(BatchSendType::class, [], ['action' => $action]);
1201
        $complete = $this->request->request->get('complete', false);
1202
1203
        if ('POST' == $this->request->getMethod() && ($complete || $this->isFormValid($form))) {
1204
            if (!$complete) {
1205
                $progress = [0, (int) $pending];
1206
                $session->set('mautic.email.send.progress', $progress);
1207
1208
                $stats = ['sent' => 0, 'failed' => 0, 'failedRecipients' => []];
1209
                $session->set('mautic.email.send.stats', $stats);
1210
1211
                $status     = 'inprogress';
1212
                $batchlimit = $form['batchlimit']->getData();
1213
1214
                $session->set('mautic.email.send.active', false);
1215
            } else {
1216
                $stats      = $session->get('mautic.email.send.stats');
1217
                $progress   = $session->get('mautic.email.send.progress');
1218
                $batchlimit = 100;
1219
                $status     = (!empty($stats['failed'])) ? 'with_errors' : 'success';
1220
            }
1221
1222
            $contentTemplate = 'MauticEmailBundle:Send:progress.html.php';
1223
            $viewParameters  = [
1224
                'progress'   => $progress,
1225
                'stats'      => $stats,
1226
                'status'     => $status,
1227
                'email'      => $entity,
1228
                'batchlimit' => $batchlimit,
1229
            ];
1230
        } else {
1231
            //process and send
1232
            $contentTemplate = 'MauticEmailBundle:Send:form.html.php';
1233
            $viewParameters  = [
1234
                'form'    => $form->createView(),
1235
                'email'   => $entity,
1236
                'pending' => $pending,
1237
            ];
1238
        }
1239
1240
        return $this->delegateView(
1241
            [
1242
                'viewParameters'  => $viewParameters,
1243
                'contentTemplate' => $contentTemplate,
1244
                'passthroughVars' => [
1245
                    'mauticContent' => 'emailSend',
1246
                    'route'         => $action,
1247
                ],
1248
            ]
1249
        );
1250
    }
1251
1252
    /**
1253
     * Deletes a group of entities.
1254
     *
1255
     * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
1256
     */
1257
    public function batchDeleteAction()
1258
    {
1259
        $page      = $this->get('session')->get('mautic.email.page', 1);
1260
        $returnUrl = $this->generateUrl('mautic_email_index', ['page' => $page]);
1261
        $flashes   = [];
1262
1263
        $postActionVars = [
1264
            'returnUrl'       => $returnUrl,
1265
            'viewParameters'  => ['page' => $page],
1266
            'contentTemplate' => 'MauticEmailBundle:Email:index',
1267
            'passthroughVars' => [
1268
                'activeLink'    => '#mautic_email_index',
1269
                'mauticContent' => 'email',
1270
            ],
1271
        ];
1272
1273
        if ('POST' == $this->request->getMethod()) {
1274
            $model = $this->getModel('email');
1275
            $ids   = json_decode($this->request->query->get('ids', '{}'));
1276
1277
            $deleteIds = [];
1278
1279
            // Loop over the IDs to perform access checks pre-delete
1280
            foreach ($ids as $objectId) {
1281
                $entity = $model->getEntity($objectId);
1282
1283
                if (null === $entity) {
1284
                    $flashes[] = [
1285
                        'type'    => 'error',
1286
                        'msg'     => 'mautic.email.error.notfound',
1287
                        'msgVars' => ['%id%' => $objectId],
1288
                    ];
1289
                } elseif (!$this->get('mautic.security')->hasEntityAccess(
1290
                    'email:emails:viewown',
1291
                    'email:emails:viewother',
1292
                    $entity->getCreatedBy()
1293
                )
1294
                ) {
1295
                    $flashes[] = $this->accessDenied(true);
1296
                } elseif ($model->isLocked($entity)) {
1297
                    $flashes[] = $this->isLocked($postActionVars, $entity, 'email', true);
1298
                } else {
1299
                    $deleteIds[] = $objectId;
1300
                }
1301
            }
1302
1303
            // Delete everything we are able to
1304
            if (!empty($deleteIds)) {
1305
                $entities = $model->deleteEntities($deleteIds);
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

1305
                /** @scrutinizer ignore-call */ 
1306
                $entities = $model->deleteEntities($deleteIds);
Loading history...
1306
1307
                $flashes[] = [
1308
                    'type'    => 'notice',
1309
                    'msg'     => 'mautic.email.notice.batch_deleted',
1310
                    'msgVars' => [
1311
                        '%count%' => count($entities),
1312
                    ],
1313
                ];
1314
            }
1315
        } //else don't do anything
1316
1317
        return $this->postActionRedirect(
1318
            array_merge(
1319
                $postActionVars,
1320
                [
1321
                    'flashes' => $flashes,
1322
                ]
1323
            )
1324
        );
1325
    }
1326
1327
    /**
1328
     * Generating the modal box content for
1329
     * the send multiple example email option.
1330
     */
1331
    public function sendExampleAction($objectId)
1332
    {
1333
        $model  = $this->getModel('email');
1334
        /** @var Email $entity */
1335
        $entity = $model->getEntity($objectId);
1336
1337
        //not found or not allowed
1338
        if (null === $entity
1339
            || (!$this->get('mautic.security')->hasEntityAccess(
1340
                'email:emails:viewown',
1341
                'email:emails:viewother',
1342
                $entity->getCreatedBy()
1343
            ))
1344
        ) {
1345
            return $this->postActionRedirect(
1346
                [
1347
                    'passthroughVars' => [
1348
                        'closeModal' => 1,
1349
                        'route'      => false,
1350
                    ],
1351
                ]
1352
            );
1353
        }
1354
1355
        // Get the quick add form
1356
        $action = $this->generateUrl('mautic_email_action', ['objectAction' => 'sendExample', 'objectId' => $objectId]);
1357
        $user   = $this->get('mautic.helper.user')->getUser();
1358
1359
        // We have to add prefix to example emails
1360
        $subject = sprintf('%s %s', static::EXAMPLE_EMAIL_SUBJECT_PREFIX, $entity->getSubject());
1361
        $entity->setSubject($subject);
1362
1363
        $form = $this->createForm(ExampleSendType::class, ['emails' => ['list' => [$user->getEmail()]]], ['action' => $action]);
1364
        /* @var \Mautic\EmailBundle\Model\EmailModel $model */
1365
1366
        if ('POST' == $this->request->getMethod()) {
1367
            $isCancelled = $this->isFormCancelled($form);
1368
            $isValid     = $this->isFormValid($form);
1369
            if (!$isCancelled && $isValid) {
1370
                $emails = $form['emails']->getData()['list'];
1371
1372
                // Prepare a fake lead
1373
                /** @var \Mautic\LeadBundle\Model\FieldModel $fieldModel */
1374
                $fieldModel = $this->getModel('lead.field');
1375
                $fields     = $fieldModel->getFieldList(false, false);
1376
                array_walk(
1377
                    $fields,
1378
                    function (&$field) {
1379
                        $field = "[$field]";
1380
                    }
1381
                );
1382
                $fields['id'] = 0;
1383
1384
                $errors = [];
1385
                foreach ($emails as $email) {
1386
                    if (!empty($email)) {
1387
                        $users = [
1388
                            [
1389
                                // Setting the id, firstname and lastname to null as this is a unknown user
1390
                                'id'        => '',
1391
                                'firstname' => '',
1392
                                'lastname'  => '',
1393
                                'email'     => $email,
1394
                            ],
1395
                        ];
1396
1397
                        // Send to current user
1398
                        $error = $model->sendSampleEmailToUser($entity, $users, $fields, [], [], false);
1399
                        if (count($error)) {
1400
                            array_push($errors, $error[0]);
1401
                        }
1402
                    }
1403
                }
1404
1405
                if (0 != count($errors)) {
1406
                    $this->addFlash(implode('; ', $errors));
1407
                } else {
1408
                    $this->addFlash('mautic.email.notice.test_sent_multiple.success');
1409
                }
1410
            }
1411
1412
            if ($isValid || $isCancelled) {
1413
                return $this->postActionRedirect(
1414
                    [
1415
                        'passthroughVars' => [
1416
                            'closeModal' => 1,
1417
                            'route'      => false,
1418
                        ],
1419
                    ]
1420
                );
1421
            }
1422
        }
1423
1424
        return $this->delegateView(
1425
            [
1426
                'viewParameters' => [
1427
                    'form' => $form->createView(),
1428
                ],
1429
                'contentTemplate' => 'MauticEmailBundle:Email:recipients.html.php',
1430
            ]
1431
        );
1432
    }
1433
1434
    /**
1435
     * PreProcess page slots for public view.
1436
     *
1437
     * @param array $slots
1438
     * @param Email $entity
1439
     */
1440
    private function processSlots($slots, $entity)
1441
    {
1442
        /** @var \Mautic\CoreBundle\Templating\Helper\SlotsHelper $slotsHelper */
1443
        $slotsHelper = $this->get('templating.helper.slots');
1444
        $content     = $entity->getContent();
1445
1446
        //Set the slots
1447
        foreach ($slots as $slot => $slotConfig) {
1448
            //support previous format where email slots are not defined with config array
1449
            if (is_numeric($slot)) {
1450
                $slot       = $slotConfig;
1451
                $slotConfig = [];
1452
            }
1453
1454
            $value = isset($content[$slot]) ? $content[$slot] : '';
1455
            $slotsHelper->set($slot, "<div data-slot=\"text\" id=\"slot-{$slot}\">{$value}</div>");
1456
        }
1457
1458
        //add builder toolbar
1459
        $slotsHelper->start('builder'); ?>
1460
        <input type="hidden" id="builder_entity_id" value="<?php echo $entity->getSessionId(); ?>"/>
1461
        <?php
1462
        $slotsHelper->stop();
1463
    }
1464
1465
    /**
1466
     * Checks the form data for webinar tokens and validates that the segment has webinar filters.
1467
     *
1468
     * @return int
1469
     */
1470
    protected function isFormValidForWebinar(array $data, Form &$form, Email $email)
1471
    {
1472
        if (!CitrixHelper::isAuthorized('Gotowebinar')) {
1473
            return true;
1474
        }
1475
1476
        // search for webinar filters in the email segments
1477
        if (!array_key_exists('lists', $data) || 0 === count($data['lists'])) {
1478
            return true;
1479
        }
1480
1481
        // search for token in content
1482
        $html         = $email->getCustomHtml();
1483
        $isTokenFound = preg_match('/\{webinar_button\}/', $html);
1484
        if (!$isTokenFound) {
1485
            return true;
1486
        }
1487
1488
        $isWebinarFilterPresent = false;
1489
        $webinarFiltersCount    = 0;
1490
        $lists                  = $data['lists'];
1491
        /** @var ListModel $model */
1492
        $model = $this->getModel('lead.list');
1493
        foreach ($lists as $listId) {
1494
            $list    = $model->getEntity($listId);
1495
            $filters = $list->getFilters();
1496
            foreach ($filters as $filter) {
1497
                if ('webinar-registration' == $filter['field'] && 'in' == $filter['operator']) {
1498
                    $isWebinarFilterPresent = true;
1499
                    ++$webinarFiltersCount;
1500
                }
1501
            }
1502
        }
1503
        // make sure that each list has a webinar-registration filter
1504
        if (count($lists) !== $webinarFiltersCount) {
1505
            $isWebinarFilterPresent = false;
1506
        }
1507
        if (!$isWebinarFilterPresent) {
1508
            $error = $this->get('translator')->trans('plugin.citrix.webinar.token_error');
1509
            $form->addError(new FormError($error));
1510
1511
            return false;
1512
        }
1513
1514
        // everything is ok
1515
        return true;
1516
    }
1517
1518
    /**
1519
     * @param     $objectId
1520
     * @param int $page
1521
     *
1522
     * @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
1523
     */
1524
    public function contactsAction($objectId, $page = 1)
1525
    {
1526
        return $this->generateContactsGrid(
1527
            $objectId,
1528
            $page,
1529
            ['email:emails:viewown', 'email:emails:viewother'],
1530
            'email',
1531
            'email_stats',
1532
            'email',
1533
            'email_id'
1534
        );
1535
    }
1536
}
1537