File size: 28,554 Bytes
d2897cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
<?php

namespace Mautic\LeadBundle\Controller;

use Doctrine\Persistence\ManagerRegistry;
use Mautic\CoreBundle\Controller\FormController;
use Mautic\CoreBundle\Factory\MauticFactory;
use Mautic\CoreBundle\Factory\ModelFactory;
use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\CoreBundle\Helper\CsvHelper;
use Mautic\CoreBundle\Helper\UserHelper;
use Mautic\CoreBundle\Security\Permissions\CorePermissions;
use Mautic\CoreBundle\Service\FlashBag;
use Mautic\CoreBundle\Translation\Translator;
use Mautic\FormBundle\Helper\FormFieldHelper;
use Mautic\LeadBundle\Entity\Import;
use Mautic\LeadBundle\Event\ImportInitEvent;
use Mautic\LeadBundle\Event\ImportMappingEvent;
use Mautic\LeadBundle\Event\ImportValidateEvent;
use Mautic\LeadBundle\Form\Type\LeadImportFieldType;
use Mautic\LeadBundle\Form\Type\LeadImportType;
use Mautic\LeadBundle\Helper\Progress;
use Mautic\LeadBundle\LeadEvents;
use Mautic\LeadBundle\Model\ImportModel;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Form\Exception\LogicException;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class ImportController extends FormController
{
    // Steps of the import
    public const STEP_UPLOAD_CSV      = 1;

    public const STEP_MATCH_FIELDS    = 2;

    public const STEP_PROGRESS_BAR    = 3;

    public const STEP_IMPORT_FROM_CSV = 4;

    private \Symfony\Component\HttpFoundation\Session\SessionInterface $session;

    private ImportModel $importModel;

    public function __construct(
        FormFactoryInterface $formFactory,
        FormFieldHelper $fieldHelper,
        private LoggerInterface $logger,
        ManagerRegistry $doctrine,
        MauticFactory $factory,
        ModelFactory $modelFactory,
        UserHelper $userHelper,
        CoreParametersHelper $coreParametersHelper,
        EventDispatcherInterface $dispatcher,
        Translator $translator,
        FlashBag $flashBag,
        RequestStack $requestStack,
        CorePermissions $security
    ) {
        /** @var ImportModel $model */
        $model = $modelFactory->getModel($this->getModelName());

        $this->session     = $requestStack->getMainRequest()->getSession();
        $this->importModel = $model;

        parent::__construct($formFactory, $fieldHelper, $doctrine, $factory, $modelFactory, $userHelper, $coreParametersHelper, $dispatcher, $translator, $flashBag, $requestStack, $security);
    }

    /**
     * @param int $page
     *
     * @return JsonResponse|RedirectResponse
     */
    public function indexAction(Request $request, $page = 1): Response
    {
        $initEvent = $this->dispatchImportOnInit();
        $this->session->set('mautic.import.object', $initEvent->objectSingular);

        return $this->indexStandard($request, $page);
    }

    /**
     * Get items for index list.
     *
     * @param int     $start
     * @param int     $limit
     * @param mixed[] $filter
     * @param string  $orderBy
     * @param string  $orderByDir
     * @param mixed[] $args
     */
    protected function getIndexItems($start, $limit, $filter, $orderBy, $orderByDir, array $args = []): array
    {
        $object = $this->session->get('mautic.import.object');

        $filter['force'][] = [
            'column' => $this->importModel->getRepository()->getTableAlias().'.object',
            'expr'   => 'eq',
            'value'  => $object,
        ];

        $items = $this->importModel->getEntities(
            array_merge(
                [
                    'start'      => $start,
                    'limit'      => $limit,
                    'filter'     => $filter,
                    'orderBy'    => $orderBy,
                    'orderByDir' => $orderByDir,
                ],
                $args
            )
        );

        $count = count($items);

        return [$count, $items];
    }

    /**
     * @param int $objectId
     *
     * @return array|JsonResponse|RedirectResponse|Response
     */
    public function viewAction(Request $request, $objectId)
    {
        return $this->viewStandard($request, $objectId, 'import', 'lead');
    }

    /**
     * Cancel and unpublish the import during manual import.
     *
     * @return JsonResponse|RedirectResponse
     */
    public function cancelAction(Request $request): Response
    {
        $initEvent   = $this->dispatchImportOnInit();
        $object      = $initEvent->objectSingular;
        $fullPath    = $this->getFullCsvPath($object);
        $import      = $this->importModel->getEntity($this->session->get('mautic.lead.import.id', null));

        if ($import && $import->getId()) {
            $import->setStatus($import::STOPPED)
                ->setIsPublished(false);
            $this->importModel->saveEntity($import);
        }

        $this->resetImport($object);
        $this->removeImportFile($fullPath);
        $this->logger->log(LogLevel::INFO, "Import for file {$fullPath} was canceled.");

        return $this->indexAction($request);
    }

    /**
     * Schedules manual import to background queue.
     */
    public function queueAction(Request $request): Response
    {
        $initEvent   = $this->dispatchImportOnInit();
        $object      = $initEvent->objectSingular;
        $fullPath    = $this->getFullCsvPath($object);
        $import      = $this->importModel->getEntity($this->session->get('mautic.lead.import.id', null));

        if ($import) {
            $import->setStatus($import::QUEUED);
            $this->importModel->saveEntity($import);
        }

        $this->resetImport($object);
        $this->logger->log(LogLevel::INFO, "Import for file {$fullPath} moved to be processed in the background.");

        return $this->indexAction($request);
    }

    /**
     * @param int  $objectId
     * @param bool $ignorePost
     */
    public function newAction(Request $request, $objectId = 0, $ignorePost = false): Response
    {
        $dispatcher = $this->dispatcher;

        try {
            $initEvent = $this->dispatchImportOnInit();
        } catch (AccessDeniedException $e) {
            return $this->accessDenied();
        }

        if (!$initEvent->objectSupported) {
            return $this->notFound();
        }

        $object = $initEvent->objectSingular;

        $this->session->set('mautic.import.object', $object);

        // Move the file to cache and rename it
        $forceStop = $request->get('cancel', false);
        $step      = ($forceStop) ? self::STEP_UPLOAD_CSV : $this->session->get('mautic.'.$object.'.import.step', self::STEP_UPLOAD_CSV);
        $fileName  = $this->getImportFileName($object);
        $importDir = $this->getImportDirName();
        $fullPath  = $this->getFullCsvPath($object);
        $fs        = new Filesystem();
        $complete  = false;

        if (!file_exists($fullPath) && self::STEP_UPLOAD_CSV !== $step) {
            // Force step one if the file doesn't exist
            $this->logger->log(LogLevel::WARNING, "File {$fullPath} does not exist anymore. Reseting import to step STEP_UPLOAD_CSV.");
            $this->addFlashMessage('mautic.import.file.missing', ['%file%' => $this->getImportFileName($object)], FlashBag::LEVEL_ERROR);
            $step = self::STEP_UPLOAD_CSV;
            $this->session->set('mautic.'.$object.'.import.step', self::STEP_UPLOAD_CSV);
        }

        $progress = (new Progress())->bindArray($this->session->get('mautic.'.$object.'.import.progress', [0, 0]));
        $import   = $this->importModel->getEntity();
        $action   = $this->generateUrl('mautic_import_action', ['object' => $request->get('object'), 'objectAction' => 'new']);

        switch ($step) {
            case self::STEP_UPLOAD_CSV:
                if ($forceStop) {
                    $this->resetImport($object);
                    $this->removeImportFile($fullPath);
                    $this->logger->log(LogLevel::WARNING, "Import for file {$fullPath} was force-stopped.");
                }

                $form = $this->formFactory->create(LeadImportType::class, [], ['action' => $action]);
                break;
            case self::STEP_MATCH_FIELDS:
                $mappingEvent = $dispatcher->dispatch(
                    new ImportMappingEvent($request->get('object')),
                    LeadEvents::IMPORT_ON_FIELD_MAPPING
                );

                try {
                    $form = $this->formFactory->create(
                        LeadImportFieldType::class,
                        [],
                        [
                            'object'           => $object,
                            'action'           => $action,
                            'all_fields'       => $mappingEvent->fields,
                            'import_fields'    => $this->session->get('mautic.'.$object.'.import.importfields', []),
                            'line_count_limit' => $this->getLineCountLimit(),
                        ]
                    );
                } catch (LogicException $e) {
                    $this->resetImport($object);
                    $this->removeImportFile($fullPath);
                    $this->logger->log(LogLevel::INFO, "Import for file {$fullPath} failed with: {$e->getMessage()}.");

                    return $this->newAction($request, 0, true);
                }

                break;
            case self::STEP_PROGRESS_BAR:
                // Just show the progress form
                $this->session->set('mautic.'.$object.'.import.step', self::STEP_IMPORT_FROM_CSV);
                break;

            case self::STEP_IMPORT_FROM_CSV:
                ignore_user_abort(true);

                $inProgress = $this->session->get('mautic.'.$object.'.import.inprogress', false);
                $checks     = $this->session->get('mautic.'.$object.'.import.progresschecks', 1);
                if (!$inProgress || $checks > 5) {
                    $this->session->set('mautic.'.$object.'.import.inprogress', true);
                    $this->session->set('mautic.'.$object.'.import.progresschecks', 1);

                    $import = $this->importModel->getEntity($this->session->get('mautic.'.$object.'.import.id', null));

                    if (!$import->getDateStarted()) {
                        $import->setDateStarted(new \DateTime());
                    }

                    $this->importModel->process($import, $progress);

                    // Clear in progress
                    if ($progress->isFinished()) {
                        $import->setStatus($import::IMPORTED)
                            ->setDateEnded(new \DateTime());
                        $this->resetImport($object);
                        $this->removeImportFile($fullPath);
                        $complete = true;
                    } else {
                        $complete = false;
                        $this->session->set('mautic.'.$object.'.import.inprogress', false);
                        $this->session->set('mautic.'.$object.'.import.progress', $progress->toArray());
                    }

                    $this->importModel->saveEntity($import);

                    break;
                } else {
                    ++$checks;
                    $this->session->set('mautic.'.$object.'.import.progresschecks', $checks);
                }
        }

        // /Check for a submitted form and process it
        if (!$ignorePost && 'POST' === $request->getMethod()) {
            if (!isset($form) || $this->isFormCancelled($form)) {
                $this->resetImport($object);
                $this->removeImportFile($fullPath);
                $reason = isset($form) ? 'the form is empty' : 'the form was canceled';
                $this->logger->log(LogLevel::WARNING, "Import for file {$fullPath} was aborted because {$reason}.");

                return $this->newAction($request, 0, true);
            }

            $valid = $this->isFormValid($form);
            switch ($step) {
                case self::STEP_UPLOAD_CSV:
                    if ($valid) {
                        if (file_exists($fullPath)) {
                            unlink($fullPath);
                        }

                        $fileData = $form['file']->getData();
                        if (!empty($fileData)) {
                            $errorMessage    = null;
                            $errorParameters = [];
                            try {
                                // Create the import dir recursively
                                $fs->mkdir($importDir);

                                $fileData->move($importDir, $fileName);

                                $file = new \SplFileObject($fullPath);

                                $config = $form->getData();
                                unset($config['file']);
                                unset($config['start']);

                                foreach ($config as $key => &$c) {
                                    $c = htmlspecialchars_decode($c);

                                    if ('batchlimit' == $key) {
                                        $c = (int) $c;
                                    }
                                }

                                $this->session->set('mautic.'.$object.'.import.config', $config);

                                if (false !== $file) {
                                    // Get the headers for matching
                                    $headers = $file->fgetcsv($config['delimiter'], $config['enclosure'], $config['escape']);

                                    // Get the number of lines so we can track progress
                                    $file->seek(PHP_INT_MAX);
                                    $linecount = $file->key();

                                    if (!empty($headers) && is_array($headers)) {
                                        $headers = CsvHelper::sanitizeHeaders($headers);

                                        $this->session->set('mautic.'.$object.'.import.headers', $headers);
                                        $this->session->set('mautic.'.$object.'.import.step', self::STEP_MATCH_FIELDS);
                                        $this->session->set('mautic.'.$object.'.import.importfields', CsvHelper::convertHeadersIntoFields($headers));
                                        $this->session->set('mautic.'.$object.'.import.progress', [0, $linecount]);
                                        $this->session->set('mautic.'.$object.'.import.original.file', $fileData->getClientOriginalName());

                                        return $this->newAction($request, 0, true);
                                    }
                                }
                            } catch (FileException $e) {
                                if (str_contains($e->getMessage(), 'upload_max_filesize')) {
                                    $errorMessage    = 'mautic.lead.import.filetoolarge';
                                    $errorParameters = [
                                        '%upload_max_filesize%' => ini_get('upload_max_filesize'),
                                    ];
                                } else {
                                    $errorMessage = 'mautic.lead.import.filenotreadable';
                                }
                            } catch (\Exception) {
                                $errorMessage = 'mautic.lead.import.filenotreadable';
                            } finally {
                                if (!is_null($errorMessage)) {
                                    $form->addError(
                                        new FormError(
                                            $this->translator->trans($errorMessage, $errorParameters, 'validators')
                                        )
                                    );
                                }
                            }
                        }
                    }
                    break;
                case self::STEP_MATCH_FIELDS:
                    $validateEvent = new ImportValidateEvent($request->get('object'), $form);

                    $dispatcher->dispatch($validateEvent, LeadEvents::IMPORT_ON_VALIDATE);

                    if ($validateEvent->hasErrors()) {
                        break;
                    }

                    $matchedFields = $validateEvent->getMatchedFields();

                    if (empty($matchedFields)) {
                        $this->resetImport($object);
                        $this->removeImportFile($fullPath);
                        $this->logger->log(LogLevel::WARNING, "Import for file {$fullPath} was aborted as there were no matched files found.");

                        return $this->newAction($request, 0, true);
                    }

                    /** @var Import $import */
                    $import = $this->importModel->getEntity();

                    $import->setMatchedFields($matchedFields)
                        ->setObject($object)
                        ->setDir($importDir)
                        ->setLineCount($this->getLineCount($object))
                        ->setFile($fileName)
                        ->setOriginalFile($this->session->get('mautic.'.$object.'.import.original.file'))
                        ->setDefault('owner', $validateEvent->getOwnerId())
                        ->setDefault('list', $validateEvent->getList())
                        ->setDefault('tags', $validateEvent->getTags())
                        ->setDefault('skip_if_exists', $validateEvent->getSkipIfExists())
                        ->setHeaders($this->session->get('mautic.'.$object.'.import.headers'))
                        ->setParserConfig($this->session->get('mautic.'.$object.'.import.config'));

                    // In case the user chose to import in browser
                    if ($this->importInBrowser($form, $object)) {
                        $import->setStatus($import::MANUAL);
                        $this->session->set('mautic.'.$object.'.import.step', self::STEP_PROGRESS_BAR);
                    }
                    $this->importModel->saveEntity($import);
                    $this->session->set('mautic.'.$object.'.import.id', $import->getId());
                    // In case the user decided to queue the import
                    if ($this->importInCli($form, $object)) {
                        $this->addFlashMessage('mautic.lead.batch.import.created');
                        $this->resetImport($object);

                        return $this->indexAction($request);
                    }

                    return $this->newAction($request, 0, true);
                default:
                    // Done or something wrong

                    $this->resetImport($object);
                    $this->removeImportFile($fullPath);
                    $this->logger->log(LogLevel::ERROR, "Import for file {$fullPath} was aborted for unknown step of '{$step}'");

                    break;
            }
        }

        if (self::STEP_UPLOAD_CSV === $step || self::STEP_MATCH_FIELDS === $step) {
            $contentTemplate = '@MauticLead/Import/new.html.twig';
            $viewParameters  = [
                'form'       => $form->createView(),
                'objectName' => $initEvent->objectName,
            ];
        } else {
            $contentTemplate = '@MauticLead/Import/progress.html.twig';
            $viewParameters  = [
                'progress'         => $progress,
                'import'           => $import,
                'complete'         => $complete,
                'failedRows'       => $this->importModel->getFailedRows($import->getId(), $import->getObject()),
                'objectName'       => $initEvent->objectName,
                'indexRoute'       => $initEvent->indexRoute,
                'indexRouteParams' => $initEvent->indexRouteParams,
            ];
        }

        if (!$complete && $request->query->has('importbatch')) {
            // Ajax request to batch process so just return ajax response unless complete

            $response = new JsonResponse(['success' => 1, 'ignore_wdt' => 1]);
        } else {
            $viewParameters['step'] = $step;

            $response = $this->delegateView(
                [
                    'viewParameters'  => $viewParameters,
                    'contentTemplate' => $contentTemplate,
                    'passthroughVars' => [
                        'activeLink'    => $initEvent->activeLink,
                        'mauticContent' => 'leadImport',
                        'route'         => $this->generateUrl(
                            'mautic_import_action',
                            [
                                'object'       => $initEvent->routeObjectName,
                                'objectAction' => 'new',
                            ]
                        ),
                        'step'     => $step,
                        'progress' => $progress,
                    ],
                ]
            );
        }
        // For uploading file Keep-Alive should not be used.
        $response->headers->set('Connection', 'close');

        return $response;
    }

    /**
     * Returns line count from the session.
     *
     * @param string $object
     *
     * @return int
     */
    protected function getLineCount($object)
    {
        $progress = $this->session->get('mautic.'.$object.'.import.progress', [0, 0]);

        return $progress[1] ?? 0;
    }

    /**
     * Decide whether the import will be processed in client's browser.
     *
     * @param FormInterface<mixed> $form
     * @param string               $object
     */
    protected function importInBrowser(FormInterface $form, $object): bool
    {
        $browserImportLimit = $this->getLineCountLimit();

        if ($browserImportLimit && $this->getLineCount($object) < $browserImportLimit) {
            return true;
        } elseif (!$browserImportLimit && $this->getFormButton($form, ['buttons', 'save'])->isClicked()) {
            return true;
        }

        return false;
    }

    protected function getLineCountLimit()
    {
        return $this->coreParametersHelper->get('background_import_if_more_rows_than', 0);
    }

    /**
     * Decide whether the import will be queued to be processed by the CLI command in the background.
     *
     * @param FormInterface<mixed> $form
     * @param string               $object
     */
    protected function importInCli(FormInterface $form, $object): bool
    {
        $browserImportLimit = $this->getLineCountLimit();

        if ($browserImportLimit && $this->getLineCount($object) >= $browserImportLimit) {
            return true;
        } elseif (!$browserImportLimit && $this->getFormButton($form, ['buttons', 'apply'])->isClicked()) {
            return true;
        }

        return false;
    }

    /**
     * Generates import directory path.
     */
    protected function getImportDirName(): string
    {
        return $this->importModel->getImportDir();
    }

    /**
     * Generates unique import directory name inside the cache dir if not stored in the session.
     * If it exists in the session, returns that one.
     *
     * @param string $object
     *
     * @return string
     */
    protected function getImportFileName($object)
    {
        // Return the dir path from session if exists
        if ($fileName = $this->session->get('mautic.'.$object.'.import.file')) {
            return $fileName;
        }

        $fileName = $this->importModel->getUniqueFileName();

        // Set the dir path to session
        $this->session->set('mautic.'.$object.'.import.file', $fileName);

        return $fileName;
    }

    /**
     * Return full absolute path to the CSV file.
     *
     * @param string $object
     */
    protected function getFullCsvPath($object): string
    {
        return $this->getImportDirName().'/'.$this->getImportFileName($object);
    }

    private function resetImport(string $object): void
    {
        $this->session->set('mautic.'.$object.'.import.headers', []);
        $this->session->set('mautic.'.$object.'.import.file', null);
        $this->session->set('mautic.'.$object.'.import.step', self::STEP_UPLOAD_CSV);
        $this->session->set('mautic.'.$object.'.import.progress', [0, 0]);
        $this->session->set('mautic.'.$object.'.import.inprogress', false);
        $this->session->set('mautic.'.$object.'.import.importfields', []);
        $this->session->set('mautic.'.$object.'.import.original.file', null);
        $this->session->set('mautic.'.$object.'.import.id', null);
    }

    private function removeImportFile(string $filepath): void
    {
        if (file_exists($filepath) && is_readable($filepath)) {
            unlink($filepath);

            $this->logger->log(LogLevel::WARNING, "File {$filepath} was removed.");
        }
    }

    /**
     * @return mixed[]
     */
    public function getViewArguments(array $args, $action): array
    {
        switch ($action) {
            case 'view':
                /** @var Import $entity */
                $entity = $args['entity'];

                $args['viewParameters'] = array_merge(
                    $args['viewParameters'],
                    [
                        'failedRows'        => $this->importModel->getFailedRows($entity->getId(), $entity->getObject()),
                        'importedRowsChart' => $entity->getDateStarted() ? $this->importModel->getImportedRowsLineChartData(
                            'i',
                            $entity->getDateStarted(),
                            $entity->getDateEnded() ?: $entity->getDateModified(),
                            null,
                            [
                                'object_id' => $entity->getId(),
                            ]
                        ) : [],
                    ]
                );

                break;
        }

        return $args;
    }

    /**
     * Support non-index pages such as modal forms.
     */
    protected function generateUrl(string $route, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string
    {
        if (!isset($parameters['object'])) {
            $request = $this->getCurrentRequest();
            \assert(null !== $request);
            $parameters['object'] = $request->get('object', 'contacts');
        }

        return parent::generateUrl($route, $parameters, $referenceType);
    }

    protected function getModelName(): string
    {
        return 'lead.import';
    }

    protected function getSessionBase($objectId = null): string
    {
        $initEvent = $this->dispatchImportOnInit();
        $object    = $initEvent->objectSingular;

        return $object.'.import'.(($objectId) ? '.'.$objectId : '');
    }

    protected function getPermissionBase()
    {
        return $this->getModel($this->getModelName())->getPermissionBase();
    }

    protected function getRouteBase(): string
    {
        return 'import';
    }

    protected function getTemplateBase(): string
    {
        return '@MauticLead/Import';
    }

    /**
     * Provide the name of the column which is used for default ordering.
     */
    protected function getDefaultOrderColumn(): string
    {
        return 'dateAdded';
    }

    /**
     * Provide the direction for default ordering.
     */
    protected function getDefaultOrderDirection(): string
    {
        return 'DESC';
    }

    private function dispatchImportOnInit(): ImportInitEvent
    {
        $request = $this->getCurrentRequest();
        \assert(null !== $request);
        $event = new ImportInitEvent($request->get('object'));

        $this->dispatcher->dispatch($event, LeadEvents::IMPORT_ON_INITIALIZE);

        return $event;
    }
}