Completed
Pull Request — master (#248)
by Pascale
03:56
created

CalMigrationUpdate::migrateDate()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 2
nc 3
nop 1
1
<?php
2
3
/**
4
 * CalMigrationUpdate.
5
 */
6
declare(strict_types=1);
7
8
namespace HDNET\Calendarize\Updates;
9
10
use HDNET\Calendarize\Service\IndexerService;
11
use HDNET\Calendarize\Utility\HelperUtility;
12
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
13
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
14
use TYPO3\CMS\Core\Utility\GeneralUtility;
15
use TYPO3\CMS\Install\Updates\AbstractUpdate;
16
17
/**
18
 * CalMigrationUpdate.
19
 *
20
 * If using the slots please use the m with func_get_args!
21
 * Example:
22
 * /**
23
 *  * @signalClass \HDNET\Calendarize\Updates\CalMigrationUpdate
24
 *  * @signalName getCalendarizeEventUid
25
 *  *
26
 *
27
 *  *@return array
28
 *  *
29
 * public function getCalendarizeEventUid()
30
 * {
31
 *    $args = func_get_args();
32
 *    list($table, $dbQueries, $call) = $args;
33
 *
34
 *    $variables = [
35
 *        'table'     => self::EVENT_TABLE,
36
 *        'dbQueries' => $dbQueries
37
 *    ];
38
 *
39
 *    return $variables;
40
 * }
41
 */
42
class CalMigrationUpdate extends AbstractUpdate
43
{
44
    /**
45
     * Import prefix.
46
     */
47
    const IMPORT_PREFIX = 'calMigration:';
48
49
    /**
50
     * Event table.
51
     */
52
    const EVENT_TABLE = 'tx_calendarize_domain_model_event';
53
54
    /**
55
     * Configuration table.
56
     */
57
    const CONFIGURATION_TABLE = 'tx_calendarize_domain_model_configuration';
58
59
    /**
60
     * ConfigurationGroup table.
61
     */
62
    const CONFIGURATION_GROUP_TABLE = 'tx_calendarize_domain_model_configurationgroup';
63
64
    /**
65
     * The human-readable title of the upgrade wizard.
66
     *
67
     * @var string
68
     */
69
    protected $title = 'Migrate cal event structures to the new calendarize event structures. 
70
    Try to migrate all cal information and place the new calendarize event models in the same folder 
71
    as the cal-records. Please note: the migration will be create calendarize default models.';
72
73
    /**
74
     * Checks whether updates are required.
75
     *
76
     * @param string &$description The description for the update
77
     *
78
     * @return bool Whether an update is required (TRUE) or not (FALSE)
79
     */
80
    public function checkForUpdate(&$description)
81
    {
82
        $nonMigratedCalIds = $this->getNonMigratedCalIds();
83
        $count = \count($nonMigratedCalIds);
84
        if (0 === $count) {
85
            return false;
86
        }
87
        $description = 'There ' . ($count > 1 ? 'are ' . $count : 'is ' . $count) . ' non migrated EXT:cal event
88
        ' . ($count > 1 ? 's' : '') . '. Run the update process to migrate the events to EXT:calendarize events.';
89
90
        return true;
91
    }
92
93
    /**
94
     * Performs the accordant updates.
95
     *
96
     * @param array &$dbQueries      Queries done in this update
97
     * @param mixed &$customMessages Custom messages
98
     *
99
     * @return bool Whether everything went smoothly or not
100
     */
101
    public function performUpdate(array &$dbQueries, &$customMessages)
102
    {
103
        $calIds = $this->getNonMigratedCalIds();
104
        $this->performSysCategoryUpdate($calIds, $dbQueries, $customMessages);
105
        $this->performSysFileReferenceUpdate($calIds, $dbQueries, $customMessages);
106
        $this->performExceptionEventUpdate($calIds, $dbQueries, $customMessages);
107
        $this->performCalEventUpdate($calIds, $dbQueries, $customMessages);
108
        $this->performLinkEventToCategory($calIds, $dbQueries, $customMessages);
109
        $this->performLinkEventToConfigurationGroup($calIds, $dbQueries, $customMessages);
110
111
        return true;
112
    }
113
114
    /**
115
     * @param       $calIds
116
     * @param array $dbQueries
117
     * @param       $customMessages
118
     *
119
     * @return bool
120
     */
121
    public function performCalEventUpdate($calIds, array &$dbQueries, &$customMessages)
122
    {
123
        $table = 'tx_cal_event';
124
        $db = HelperUtility::getDatabaseConnection($table);
125
        $q = $db->createQueryBuilder();
126
127
        $events = $q->select('*')->from($table)->where(
128
            $q->expr()->in('uid', $calIds)
129
        )->execute()->fetchAll();
130
131
        foreach ($events as $event) {
132
            $calendarizeEventRecord = [
133
                'pid' => $event['pid'],
134
                'import_id' => self::IMPORT_PREFIX . (int) $event['uid'],
135
                'tstamp' => $event['tstamp'],
136
                'crdate' => $event['crdate'],
137
                'hidden' => $event['hidden'],
138
                'starttime' => $event['starttime'],
139
                'endtime' => $event['endtime'],
140
                'title' => $event['title'],
141
                'organizer' => $event['organizer'],
142
                'location' => $event['location'],
143
                'abstract' => $event['teaser'],
144
                'description' => $event['description'],
145
                'images' => $event['image'],
146
                'downloads' => $event['attachment'],
147
                'calendarize' => $this->buildConfigurations($event, $dbQueries),
148
            ];
149
150
            $variables = [
151
                'calendarizeEventRecord' => $calendarizeEventRecord,
152
                'event' => $event,
153
                'table' => self::EVENT_TABLE,
154
                'dbQueries' => $dbQueries,
155
            ];
156
157
            $dispatcher = HelperUtility::getSignalSlotDispatcher();
158
            $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__ . 'PreInsert', $variables);
159
160
            $q->insert($variables['table'])->values($variables['calendarizeEventRecord']);
161
            $dbQueries[] = $q->getSQL();
162
163
            $q->execute();
164
165
            $variablesPostInsert = [
166
                'calendarizeEventRecord' => $calendarizeEventRecord,
167
                'event' => $event,
168
                'table' => $variables['table'],
169
                'recordId' => $db->lastInsertId($variables['table']),
170
                'dbQueries' => $dbQueries,
171
            ];
172
173
            $dispatcher = HelperUtility::getSignalSlotDispatcher();
174
            $dispatcher->dispatch(__CLASS__, __FUNCTION__ . 'PostInsert', $variablesPostInsert);
175
        }
176
177
        $indexer = GeneralUtility::makeInstance(IndexerService::class);
178
        $indexer->reindexAll();
179
180
        return true;
181
    }
182
183
    /**
184
     * @param       $calIds
185
     * @param array $dbQueries
186
     * @param array $customMessages
187
     *
188
     * @return bool
189
     */
190
    public function performExceptionEventUpdate($calIds, &$dbQueries, &$customMessages)
191
    {
192
        $table = 'tx_cal_exception_event_group';
193
        // ConfigurationGroup für jede ExceptionGroup
194
        $db = HelperUtility::getDatabaseConnection($table);
195
        $q = $db->createQueryBuilder();
196
        $variables = [
197
            'table' => $table,
198
            'dbQueries' => $dbQueries,
199
            'calIds' => $calIds,
200
        ];
201
202
        $q->getRestrictions()
203
            ->removeAll()
204
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
205
206
        $q->select('*')->from($variables['table']);
207
208
        $selectResults = $q->execute()->fetchAll();
209
        $dbQueries[] = $q->getSQL();
210
211
        foreach ($selectResults as $selectResult) {
212
            $group = [
213
                'pid' => $selectResult['pid'],
214
                'tstamp' => $selectResult['tstamp'],
215
                'crdate' => $selectResult['crdate'],
216
                'cruser_id' => $selectResult['cruser_id'],
217
                'title' => $selectResult['title'],
218
                'configurations' => $this->getExceptionConfigurationForExceptionGroup($selectResult['uid']), // get Configuration
219
                'hidden' => $selectResult['hidden'],
220
                'import_id' => self::IMPORT_PREFIX . $selectResult['uid'],
221
            ];
222
223
            $q->insert(self::CONFIGURATION_GROUP_TABLE)->values($group);
224
            $dbQueries[] = $q->getSQL();
225
226
            $q->execute();
227
        }
228
229
        return true;
230
    }
231
232
    /**
233
     * @TODO
234
     *
235
     * @param $calIds
236
     * @param $dbQueries
237
     * @param $customMessages
238
     *
239
     * @return bool
240
     */
241
    public function performLinkEventToConfigurationGroup($calIds, &$dbQueries, &$customMessages)
242
    {
243
        $db = HelperUtility::getDatabaseConnection(self::CONFIGURATION_GROUP_TABLE);
244
        $q = $db->createQueryBuilder();
245
        $now = new \DateTime();
246
247
        $variables = [
248
            'table' => self::CONFIGURATION_GROUP_TABLE,
249
            'dbQueries' => $dbQueries,
250
            'calIds' => $calIds,
251
        ];
252
253
        $selectResults = $q->select('*')->from($variables['table'])->execute()->fetchAll();
254
        $dbQueries[] = $q->getSQL();
255
256
        foreach ($selectResults as $group) {
257
            $importId = \explode(':', $group['import_id']);
258
            $groupId = (int) $importId[1];
259
260
            $variables = [
261
                'table' => 'tx_cal_exception_event_mm',
262
                'dbQueries' => $dbQueries,
263
                'calIds' => $calIds,
264
            ];
265
266
            $q->resetQueryParts()->resetRestrictions();
267
268
            $q->select('uid_local')
269
                ->from($variables['table'])
270
                ->where(
271
                    $q->expr()->andX(
272
                        $q->expr()->eq('tablenames', 'tx_cal_exception_event_group'),
273
                        $q->expr()->eq('uid_foreign', $q->createNamedParameter((int) $groupId, \PDO::PARAM_INT))
274
                    )
275
                );
276
277
            $dbQueries[] = $q->getSQL();
278
            $selectResults = $q->execute()->fetchAll();
279
280
            foreach ($selectResults as $eventUid) {
281
                $eventImportId = self::IMPORT_PREFIX . (int) $eventUid['uid_local'];
282
                $configurationRow = [
283
                    'pid' => (int) $group['pid'],
284
                    'tstamp' => $now->getTimestamp(),
285
                    'crdate' => $now->getTimestamp(),
286
                    'type' => 'group',
287
                    'handling' => 'exclude',
288
                    'groups' => $group['uid'],
289
                ];
290
291
                $this->updateEventWithConfiguration($eventImportId, $configurationRow, $dbQueries, $customMessages);
292
            }
293
        }
294
295
        return true;
296
    }
297
298
    /**
299
     * Migrate the 'sys_file_reference' entries from 'tx_cal_event' to 'tx_calendarize_domain_model_event'.
300
     * Mark the imported entries with the import-id.
301
     *
302
     * @param       $calIds
303
     * @param array $dbQueries
304
     * @param       $customMessages
305
     */
306
    public function performSysFileReferenceUpdate($calIds, array &$dbQueries, &$customMessages)
307
    {
308
        $db = HelperUtility::getDatabaseConnection('tx_cal_event');
309
        $q = $db->createQueryBuilder();
310
311
        $variables = [
312
            'table' => 'tx_cal_event',
313
            'fieldnames' => ['image', 'attachment'],
314
            'dbQueries' => $dbQueries,
315
            'calIds' => $calIds,
316
        ];
317
318
        // select all not migrated entries
319
        $fieldnames = 'fieldname = \'' . \implode('\' OR fieldname = \'', $variables['fieldnames']) . '\'';
320
        $selectWhere = 'tablenames = \'' . $variables['table'] . '\' AND (' . $fieldnames . ')';
321
        $selectWhere .= ' AND NOT EXISTS (SELECT NULL FROM sys_file_reference sfr2 WHERE sfr2.import_id = CONCAT(\'' . self::IMPORT_PREFIX . '\', sfr1.uid))';
322
323
        /* @todo */
324
        $q->select('*')
325
            ->from('sys_file_reference', 'sfr1')
326
            ->where($selectWhere);
327
328
        $dbQueries[] = $q->getSQL();
329
        $selectResults = $q->execute()->fetchAll();
330
331
        $variables = [
332
            'table' => self::EVENT_TABLE,
333
            'fieldnames' => $variables['fieldnames'],
334
            'dbQueries' => $dbQueries,
335
            'calIds' => $calIds,
336
            'selectResults' => $selectResults,
337
        ];
338
339
        // create new entry with import_id
340
        foreach ($variables['selectResults'] as $selectResult) {
341
            $selectResult['tablenames'] = $variables['table'];
342
            $selectResult['import_id'] = self::IMPORT_PREFIX . $selectResult['uid'];
343
            $selectResult['fieldname'] = ('image' === $selectResult['fieldname']) ? 'images' : 'downloads';
344
            unset($selectResult['uid_foreign'], $selectResult['uid']);
345
346
            $q->resetQueryParts()->resetRestrictions();
347
            $q->insert('sys_file_reference')->values($selectResult);
348
349
            $dbQueries[] = $q->getSQL();
350
351
            $q->execute();
352
        }
353
    }
354
355
    /**
356
     * Link the Events to the migrated Categories.
357
     * This build up the 'sys_category_record_mm' table on base of the 'tx_cal_event_category_mm' table.
358
     *
359
     * @param       $calIds
360
     * @param array $dbQueries
361
     * @param array $customMessages
362
     */
363
    public function performLinkEventToCategory($calIds, &$dbQueries, &$customMessages)
364
    {
365
        $table = 'tx_cal_event_category_mm';
366
367
        $db = HelperUtility::getDatabaseConnection($table);
368
        $q = $db->createQueryBuilder();
369
370
        $q->select('*')->from($table);
371
        $dbQueries[] = $q->getSQL();
372
373
        $selectResults = $q->execute()->fetchAll();
374
375
        $variables = [
376
            'tablenames' => self::EVENT_TABLE,
377
            'fieldname' => 'categories',
378
            'dbQueries' => $dbQueries,
379
        ];
380
381
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
382
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__, $variables);
383
384
        foreach ($selectResults as $mm) {
385
            $eventUid = $this->getCalendarizeEventUid(self::IMPORT_PREFIX . $mm['uid_local'], $dbQueries, $customMessages);
386
            $categoryUid = $this->getCalendarizeCategoryUid(
387
                self::IMPORT_PREFIX . $mm['uid_foreign'],
388
                $dbQueries,
389
                $customMessages
390
            );
391
392
            $insertValues = [
393
                'uid_local' => $categoryUid,
394
                'uid_foreign' => $eventUid,
395
                'tablenames' => $variables['tablenames'],
396
                'fieldname' => $variables['fieldname'],
397
            ];
398
399
            $q->insert('sys_category_record_mm')->values($insertValues);
400
            $dbQueries[] = $q->getSQL();
401
402
            $q->execute();
403
        }
404
    }
405
406
    /**
407
     * @param $eventImportId
408
     * @param $configuration
409
     * @param $dbQueries
410
     * @param $customMessages
411
     *
412
     * @return bool|\mysqli_result|object
413
     */
414
    protected function updateEventWithConfiguration($eventImportId, $configuration, &$dbQueries, &$customMessages)
415
    {
416
        $db = HelperUtility::getDatabaseConnection(self::CONFIGURATION_TABLE);
417
        $q = $db->createQueryBuilder();
418
419
        $configurationRow = $this->findEventExcludeConfiguration($eventImportId, $dbQueries, $customMessages);
420
        if ($configurationRow) {
421
            $configurationRow['groups'] = $this->addValueToCsv($configurationRow['groups'], $configuration['groups']);
422
423
            unset($configurationRow['uid']);
424
425
            $q->update(self::CONFIGURATION_GROUP_TABLE)
426
                ->where('uid', $q->createNamedParameter((int) $configuration['uid'], \PDO::PARAM_INT))
427
                ->values($configurationRow);
428
429
            $dbQueries[] = $q->getSQL();
430
            $results = $q->execute();
431
        } else {
432
            $q->insert(self::CONFIGURATION_TABLE)->values($configuration);
433
            $dbQueries[] = $q->getSQL();
434
435
            $configurationId = $db->lastInsertId(self::CONFIGURATION_TABLE);
436
437
            $results = $this->addConfigurationIdToEvent($eventImportId, $configurationId, $dbQueries, $customMessages);
438
        }
439
440
        return $results;
441
    }
442
443
    /**
444
     * @param string $csv
445
     * @param string $value
446
     *
447
     * @return string
448
     */
449
    protected function addValueToCsv($csv, $value)
450
    {
451
        $csvArray = GeneralUtility::trimExplode(',', $csv);
452
453
        // check for doubles
454
        $values = \array_flip($csvArray);
455
        if (isset($values[$value])) {
456
            return $csv;
457
        }
458
        $csvArray[] = $value;
459
        $csv = \implode(',', $csvArray);
460
461
        return $csv;
462
    }
463
464
    /**
465
     * @param string $eventImportId
466
     * @param int    $configurationId
467
     * @param array  $dbQueries
468
     * @param array  $customMessages
469
     *
470
     * @return bool|\mysqli_result|object
471
     */
472
    protected function addConfigurationIdToEvent($eventImportId, $configurationId, &$dbQueries, &$customMessages)
473
    {
474
        $event = $this->findEventByImportId($eventImportId, $dbQueries, $customMessages);
475
        if (!$event) {
476
            return false;
477
        }
478
479
        $event['calendarize'] = $this->addValueToCsv($event['calendarize'], $configurationId);
480
481
        return $this->updateEvent($event['uid'], $event, $dbQueries, $customMessages);
482
    }
483
484
    /**
485
     * @param int   $eventId
486
     * @param array $values
487
     * @param array $dbQueries
488
     * @param array $customMessages
489
     *
490
     * @return bool|\mysqli_result|object
491
     */
492
    protected function updateEvent($eventId, $values, &$dbQueries, &$customMessages)
493
    {
494
        $db = HelperUtility::getDatabaseConnection(self::EVENT_TABLE);
495
        $q = $db->createQueryBuilder();
496
497
        $variables = [
498
            'table' => self::EVENT_TABLE,
499
            'eventId' => (int) $eventId,
500
            'values' => $values,
501
            'dbQueries' => $dbQueries,
502
        ];
503
504
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
505
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__, $variables);
506
507
        $q->update($variables['table'])
508
            ->where(
509
                $q->expr()->eq('uid', $q->createNamedParameter((int) $eventId, \PDO::PARAM_INT))
510
            )
511
            ->values($variables['values']);
512
513
        unset($values['uid']);
514
515
        $dbQueries[] = $q->getSQL();
516
517
        return $q->execute()->fetchAll();
518
    }
519
520
    /**
521
     * @param $eventImportId
522
     * @param $dbQueries
523
     * @param $customMessages
524
     *
525
     * @return array|bool
526
     */
527
    protected function findEventByImportId($eventImportId, &$dbQueries, &$customMessages)
528
    {
529
        $db = HelperUtility::getDatabaseConnection(self::EVENT_TABLE);
530
        $q = $db->createQueryBuilder();
531
532
        $variables = [
533
            'table' => self::EVENT_TABLE,
534
            'dbQueries' => $dbQueries,
535
            'eventImportId' => $eventImportId,
536
        ];
537
538
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
539
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__, $variables);
540
541
        $q->select('*')->from($variables['table'])
542
            ->where(
543
                $q->expr()->eq('import_id', $q->createNamedParameter($eventImportId))
544
            );
545
546
        $dbQueries[] = $q->getSQL();
547
548
        return $q->execute()->fetchAll();
549
    }
550
551
    /**
552
     * @param string $eventImportId
553
     * @param array  $dbQueries
554
     * @param array  $customMessages
555
     *
556
     * @return array|bool
557
     */
558
    protected function findEventExcludeConfiguration($eventImportId, &$dbQueries, &$customMessages)
559
    {
560
        $event = $this->findEventByImportId($eventImportId, $dbQueries, $customMessages);
561
562
        if (!$event) {
563
            return false;
564
        }
565
566
        $variables = [
567
            'table' => self::CONFIGURATION_TABLE,
568
            'dbQueries' => $dbQueries,
569
            'event' => $event,
570
        ];
571
572
        $db = HelperUtility::getDatabaseConnection($variables['table']);
573
        $q = $db->createQueryBuilder();
574
575
        $q->select('*')
576
            ->from($variables['table'])
577
            ->where(
578
                $q->expr()->andX(
579
                    $q->expr()->eq('type', 'group'),
580
                    $q->expr()->eq('handling', 'exclude'),
581
                    $q->expr()->in('uid', $variables['event']['calendarize'])
582
                )
583
            );
584
585
        $dbQueries[] = $q->getSQL();
586
587
        return $q->execute()->fetchAll();
588
    }
589
590
    /**
591
     * @param       $groupId
592
     * @param array $dbQueries
593
     * @param array $customMessages
594
     *
595
     * @return string
596
     */
597
    protected function getExceptionConfigurationForExceptionGroup($groupId, &$dbQueries, &$customMessages)
598
    {
599
        $recordIds = [];
600
        $variables = [
601
            'table' => ' tx_cal_exception_event_group_mm',
602
            'dbQueries' => $dbQueries,
603
        ];
604
605
        $db = HelperUtility::getDatabaseConnection($variables['table']);
606
        $q = $db->createQueryBuilder();
607
608
        $q->select('*')
609
            ->from($variables['table'])
610
            ->where('uid_local', $q->createNamedParameter((int) $groupId, \PDO::PARAM_INT));
611
612
        $dbQueries[] = $q->getSQL();
613
614
        $mmResults = $q->execute()->fetchAll();
615
        foreach ($mmResults as $mmResult) {
616
            $variables = [
617
                'table' => ' tx_cal_exception_event',
618
                'dbQueries' => $dbQueries,
619
            ];
620
621
            $q->resetQueryParts()->resetRestrictions();
622
            $q->select('*')
623
                ->from($variables['table'])
624
                ->where(
625
                    $q->expr()->eq('uid', $q->createNamedParameter((int) $mmResult['uid_foreign'], \PDO::PARAM_INT))
626
                );
627
628
            $dbQueries[] = $q->getSQL();
629
630
            $selectResults = $q->execute()->fetchAll();
631
632
            foreach ($selectResults as $selectResult) {
633
                $configurationRow = [
634
                    'pid' => $selectResult['pid'],
635
                    'tstamp' => $selectResult['tstamp'],
636
                    'crdate' => $selectResult['crdate'],
637
                    'type' => 'time',
638
                    'handling' => 'include',
639
                    'start_date' => $this->migrateDate($selectResult['start_date']),
640
                    'end_date' => $this->migrateDate($selectResult['end_date']),
641
                    'start_time' => (int) $selectResult['start_time'],
642
                    'end_time' => (int) $selectResult['end_time'],
643
                    'all_day' => (null === $selectResult['start_time'] && null === $selectResult['end_time']) ? 1 : 0,
644
                    'frequency' => $this->mapFrequency($selectResult['freq']),
645
                    'till_date' => $this->migrateDate($selectResult['until']),
646
                    'counter_amount' => (int) $selectResult['cnt'],
647
                    'counter_interval' => (int) $selectResult['interval'],
648
                    'import_id' => self::IMPORT_PREFIX . $selectResult['uid'],
649
                ];
650
651
                $variables = [
652
                    'table' => self::CONFIGURATION_TABLE,
653
                    'configurationRow' => $configurationRow,
654
                ];
655
656
                $dispatcher = HelperUtility::getSignalSlotDispatcher();
657
                $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__ . 'PreInsert', $variables);
658
659
                $q->resetQueryParts()->resetRestrictions();
660
                $q->insert($variables['table'])->values($variables['configurationRow']);
661
662
                $dbQueries[] = $q->getSQL();
663
664
                $q->execute();
665
666
                $recordIds[] = $db->lastInsertId($variables['table']);
667
            }
668
        }
669
670
        return \implode(',', $recordIds);
671
    }
672
673
    /**
674
     * @param string $calFrequency
675
     *
676
     * @return string
677
     */
678
    protected function mapFrequency($calFrequency)
679
    {
680
        $freq = [
681
            'none' => null,
682
            'day' => 'daily',
683
            'week' => 'weekly',
684
            'month' => 'monthly',
685
            'year' => 'yearly',
686
        ];
687
688
        if (!isset($freq[$calFrequency])) {
689
            return '';
690
        }
691
692
        return $freq[$calFrequency];
693
    }
694
695
    /**
696
     * Migrate the 'tx_cal_category' table to the 'sys_category' table.
697
     *
698
     * @param       $calIds
699
     * @param array $dbQueries
700
     * @param       $customMessages
701
     */
702
    protected function performSysCategoryUpdate($calIds, array &$dbQueries, &$customMessages)
703
    {
704
        // first migrate from tx_cal_category to sys_category
705
        $variables = [
706
            'table' => 'tx_cal_category',
707
            'dbQueries' => $dbQueries,
708
            'calIds' => $calIds,
709
        ];
710
711
        $db = HelperUtility::getDatabaseConnection($variables['table']);
712
        $q = $db->createQueryBuilder();
713
        $q->getRestrictions()
714
            ->removeAll()
715
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
716
717
        $q->select('*')
718
            ->from($variables['table']);
719
720
        $dbQueries[] = $q->getSQL();
721
722
        $selectResults = $q->execute()->fetchAll();
723
724
        foreach ($selectResults as $category) {
725
            $sysCategoryRecord = [
726
                'pid' => $category['pid'],
727
                'tstamp' => $category['tstamp'],
728
                'crdate' => $category['crdate'],
729
                'cruser_id' => $category['cruser_id'],
730
                'deleted' => $category['deleted'],
731
                'hidden' => $category['hidden'],
732
                'starttime' => $category['starttime'],
733
                'endtime' => $category['endtime'],
734
                'sys_language_uid' => $category['sys_language_uid'],
735
                'l10n_parent' => $category['l18n_parent'],
736
                'l10n_diffsource' => $category['l18n_diffsource'],
737
                'title' => $category['title'],
738
                'parent' => (int) $category['parent_category'],
739
                'import_id' => self::IMPORT_PREFIX . (int) $category['uid'],
740
                'sorting' => $category['sorting'],
741
            ];
742
743
            $q->resetQueryParts()->resetRestrictions();
744
745
            $q->insert('sys_category')->values($sysCategoryRecord);
746
            $dbQueries[] = $q->getSQL();
747
748
            $q->execute();
749
        }
750
751
        // second rewrite the tree
752
        $variables = [
753
            'table' => 'sys_category',
754
            'dbQueries' => $dbQueries,
755
            'calIds' => $calIds,
756
        ];
757
758
        $q->resetQueryParts()->resetRestrictions();
759
760
        $q->select('*')
761
            ->from($variables['table'])
762
            ->where(
763
                $q->expr()->neq('import_id', '')
764
            );
765
766
        $dbQueries[] = $q->getSQL();
767
        $selectResults = $q->execute()->fetchAll();
768
769
        foreach ($selectResults as $sysCategory) {
770
            // update parent, because there are just the old uids
771
            $updateRecord = [
772
                'parent' => $this->getSysCategoryParentUid(self::IMPORT_PREFIX . (int) $sysCategory['parent']),
773
            ];
774
775
            $q->resetQueryParts()->resetRestrictions();
776
            $q->update('sys_category')
777
                ->where(
778
                    $q->expr()->eq('uid', $q->createNamedParameter((int) $sysCategory['uid'], \PDO::PARAM_INT))
779
                )
780
                ->values($updateRecord);
781
782
            $dbQueries[] = $q->getSQL();
783
784
            $q->execute();
785
        }
786
    }
787
788
    /**
789
     * Return the parentUid for the 'sys_category' entry on base of the import_id.
790
     *
791
     * @param string $importId
792
     *
793
     * @return int
794
     */
795
    protected function getSysCategoryParentUid($importId)
796
    {
797
        $table = 'sys_category';
798
        $db = HelperUtility::getDatabaseConnection($table);
799
        $q = $db->createQueryBuilder();
800
801
        $q->select('uid')
802
            ->from($table)
803
            ->where(
804
                $q->expr()->eq('import_id', $q->createNamedParameter($importId))
805
            );
806
807
        $dbQueries[] = $q->getSQL();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$dbQueries was never initialized. Although not strictly required by PHP, it is generally a good practice to add $dbQueries = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
808
809
        $result = $q->execute()->fetchAll();
810
811
        return (int) $result['uid'];
812
    }
813
814
    /**
815
     * Get the event uid on base of the given import_id.
816
     * The import_id is the original tx_cal_event id prefixed with the IMPORT_PREFIX.
817
     *
818
     * @param string $importId
819
     * @param array  $dbQueries
820
     * @param array  $customMessages
821
     *
822
     * @return int
823
     */
824
    protected function getCalendarizeEventUid($importId, &$dbQueries, &$customMessages)
825
    {
826
        $variables = [
827
            'table' => self::EVENT_TABLE,
828
            'dbQueries' => $dbQueries,
829
        ];
830
831
        $q = HelperUtility::getDatabaseConnection($variables['table'])->createQueryBuilder();
832
833
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
834
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__, $variables);
835
836
        $q->select('uid')
837
            ->from($variables['table'])
838
            ->where(
839
                $q->expr()->eq('import_id', $q->createNamedParameter($importId))
840
            );
841
842
        $dbQueries[] = $q->getSQL();
843
844
        $result = $q->execute()->fetchAll();
845
        $uid = (int) $result['uid'];
846
847
        return $uid;
848
    }
849
850
    /**
851
     * Get the sys_category uid on base of the given import_id.
852
     * The import_id is the original tx_cal_category id prefixed with the IMPORT_PREFIX.
853
     *
854
     * @see CalMigrationUpdate::IMPORT_PREFIX
855
     *
856
     * @param string $importId
857
     * @param array  $dbQueries
858
     * @param array  $customMessages
859
     *
860
     * @return int
861
     */
862
    protected function getCalendarizeCategoryUid($importId, &$dbQueries, &$customMessages)
863
    {
864
        $variables = [
865
            'table' => 'sys_category',
866
            'dbQueries' => $dbQueries,
867
        ];
868
869
        $q = HelperUtility::getDatabaseConnection($variables['table'])->createQueryBuilder();
870
871
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
872
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__, $variables);
873
874
        $q->select('uid')
875
            ->from($variables['table'])
876
            ->where(
877
                $q->expr()->eq('import_id', $q->createNamedParameter($importId))
878
            );
879
880
        $dbQueries[] = $q->getSQL();
881
882
        $result = $q->execute()->fetchAll();
883
        $uid = (int) $result['uid'];
884
885
        return $uid;
886
    }
887
888
    /**
889
     * @param $calEventRow
890
     * @param $dbQueries
891
     *
892
     * @return int
893
     */
894
    protected function buildConfigurations($calEventRow, &$dbQueries)
895
    {
896
        $configurationRow = [
897
            'pid' => $calEventRow['pid'],
898
            'tstamp' => $calEventRow['tstamp'],
899
            'crdate' => $calEventRow['crdate'],
900
            'type' => 'time',
901
            'handling' => 'include',
902
            'start_date' => $this->migrateDate($calEventRow['start_date']),
903
            'end_date' => $this->migrateDate($calEventRow['end_date']),
904
            'start_time' => $calEventRow['start_time'],
905
            'end_time' => $calEventRow['end_time'],
906
            'all_day' => $calEventRow['allday'],
907
            'frequency' => $this->mapFrequency($calEventRow['freq']),
908
            'till_date' => $this->migrateDate($calEventRow['until']),
909
            'counter_amount' => (int) $calEventRow['cnt'],
910
            'counter_interval' => (int) $calEventRow['interval'],
911
        ];
912
913
        $variables = [
914
            'table' => self::CONFIGURATION_TABLE,
915
            'configurationRow' => $configurationRow,
916
            'calEventRow' => $calEventRow,
917
            'dbQueries' => $dbQueries,
918
        ];
919
920
        $db = HelperUtility::getDatabaseConnection($variables['table']);
921
        $q = $db->createQueryBuilder();
922
923
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
924
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__ . 'PreInsert', $variables);
925
926
        $q->insert($variables['table'])
927
            ->values($variables['configurationRow']);
928
929
        $dbQueries[] = $q->getSQL();
930
        $q->execute();
931
        $recordId = $db->lastInsertId($variables['table']);
932
933
        $variables = [
934
            'table' => $variables['table'],
935
            'configurationRow' => $configurationRow,
936
            'calEventRow' => $calEventRow,
937
            'recordId' => $recordId,
938
            'dbQueries' => $dbQueries,
939
        ];
940
941
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
942
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__ . 'PostInsert', $variables);
943
944
        return $variables['recordId'];
945
946
        /*
947
         *
948
         * @todo
949
950
        recurrence	text NULL
951
        day	text NULL
952
953
954
                 * ["freq"]=>
955
                 * string(4) "none"
956
                 * ["until"]=>
957
                 * string(1) "0"
958
                 * ["cnt"]=>
959
                 * string(1) "0"
960
                 * ["byday"]=>
961
                 * string(0) ""
962
                 * ["bymonthday"]=>
963
                 * string(0) ""
964
                 * ["bymonth"]=>
965
                 * string(0) ""
966
                 * ["intrval"]=>
967
                 * string(1) "1"
968
                 * ["rdate"]=>
969
                 * NULL
970
                 * ["rdate_type"]=>
971
                 * string(1) "0"
972
                 * ["deviation"]=>
973
                 * string(1) "0"
974
                 * ["monitor_cnt"]=>
975
                 * string(1) "0"
976
                 * ["exception_cnt"]=>
977
                 */
978
    }
979
980
    /**
981
     * @param $oldFormat
982
     *
983
     * @return int|string
984
     */
985
    protected function migrateDate($oldFormat)
986
    {
987
        try {
988
            $date = new \DateTime($oldFormat);
989
990
            return $date->getTimestamp();
991
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
992
        }
993
994
        return '';
995
    }
996
997
    /**
998
     * Get the non migrated cal IDs.
999
     *
1000
     * @return array
1001
     */
1002
    protected function getNonMigratedCalIds()
1003
    {
1004
        if (!ExtensionManagementUtility::isLoaded('cal')) {
1005
            return [];
1006
        }
1007
1008
        $checkImportIds = [];
1009
        $nonMigrated = [];
1010
1011
        $table = 'tx_cal_event';
1012
        $q = HelperUtility::getDatabaseConnection($table)->createQueryBuilder();
1013
        $q->getRestrictions()
1014
            ->removeAll()
1015
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1016
1017
        $events = $q->select('uid')
1018
            ->from($table)
1019
            ->execute()
1020
            ->fetchAll();
1021
1022
        foreach ($events as $event) {
1023
            $checkImportIds[] = '"' . self::IMPORT_PREFIX . $event['uid'] . '"';
1024
            $nonMigrated[(int) $event['uid']] = (int) $event['uid'];
1025
        }
1026
1027
        $countOriginal = \count($checkImportIds);
1028
        if (0 === $countOriginal) {
1029
            return [];
1030
        }
1031
1032
        $variables = [
1033
            'table' => self::EVENT_TABLE,
1034
        ];
1035
1036
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
1037
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__ . 'PreSelect', $variables);
1038
1039
        $q->resetQueryParts();
1040
1041
        $migratedRows = $q->select('uid', 'import_id')
1042
            ->from($variables['table'])
1043
            ->where(
1044
                $q->expr()->in('import_id', $checkImportIds)
1045
            );
1046
1047
        foreach ($migratedRows as $migratedRow) {
1048
            $importId = (int) \str_replace(self::IMPORT_PREFIX, '', $migratedRow['import_id']);
1049
            if (isset($nonMigrated[$importId])) {
1050
                unset($nonMigrated[$importId]);
1051
            }
1052
        }
1053
1054
        $variables = [
1055
            'table' => $variables['table'],
1056
            'migratedRows' => $migratedRows,
1057
            'nonMigrated' => $nonMigrated,
1058
        ];
1059
1060
        $dispatcher = HelperUtility::getSignalSlotDispatcher();
1061
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__ . 'ReadyParsed', $variables);
1062
1063
        return $variables['nonMigrated'];
1064
    }
1065
}
1066