Completed
Push — master ( 7caedd...869cdb )
by Tim
13:15
created

CalendarController::shortcutAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
/**
4
 * Calendar.
5
 */
6
declare(strict_types=1);
7
8
namespace HDNET\Calendarize\Controller;
9
10
use HDNET\Calendarize\Domain\Model\Index;
11
use HDNET\Calendarize\Register;
12
use HDNET\Calendarize\Utility\DateTimeUtility;
13
use HDNET\Calendarize\Utility\EventUtility;
14
use HDNET\Calendarize\Utility\ExtensionConfigurationUtility;
15
use HDNET\Calendarize\Utility\TranslateUtility;
16
use TYPO3\CMS\Backend\Utility\BackendUtility;
17
use TYPO3\CMS\Core\Utility\GeneralUtility;
18
use TYPO3\CMS\Core\Utility\MathUtility;
19
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
20
use TYPO3\CMS\Extbase\Property\TypeConverter\DateTimeConverter;
21
use TYPO3\CMS\Extbase\SignalSlot\Dispatcher;
22
23
/**
24
 * Calendar.
25
 */
26
class CalendarController extends AbstractController
27
{
28
    /**
29
     * Init all actions.
30
     */
31
    public function initializeAction()
32
    {
33
        parent::initializeAction();
34
        $this->indexRepository->setIndexTypes(GeneralUtility::trimExplode(',', $this->settings['configuration'], true));
35
        $additionalSlotArguments = [
36
            'contentRecord' => $this->configurationManager->getContentObject()->data,
37
            'settings' => $this->settings,
38
        ];
39
        $this->indexRepository->setAdditionalSlotArguments($additionalSlotArguments);
40
41
        if (isset($this->settings['sorting'])) {
42
            if (isset($this->settings['sortBy'])) {
43
                $this->indexRepository->setDefaultSortingDirection($this->settings['sorting'], $this->settings['sortBy']);
44
            } else {
45
                $this->indexRepository->setDefaultSortingDirection($this->settings['sorting']);
46
            }
47
        }
48
49
        if (isset($this->arguments['startDate'])) {
50
            $this->arguments['startDate']->getPropertyMappingConfiguration()
51
                ->setTypeConverterOption(
52
                    DateTimeConverter::class,
53
                    DateTimeConverter::CONFIGURATION_DATE_FORMAT,
54
                    $this->settings['dateFormat']
55
                );
56
        }
57
        if (isset($this->arguments['endDate'])) {
58
            $this->arguments['endDate']->getPropertyMappingConfiguration()
59
                ->setTypeConverterOption(
60
                    DateTimeConverter::class,
61
                    DateTimeConverter::CONFIGURATION_DATE_FORMAT,
62
                    $this->settings['dateFormat']
63
                );
64
        }
65
        if ($this->request->hasArgument('event') && 'detailAction' === $this->actionMethodName) {
66
            // default configuration
67
            $configurationName = $this->settings['configuration'];
68
            // configuration overwritten by argument?
69
            if ($this->request->hasArgument('extensionConfiguration')) {
70
                $configurationName = $this->request->getArgument('extensionConfiguration');
71
            }
72
            // get the configuration
73
            $configuration = ExtensionConfigurationUtility::get($configurationName);
74
75
            // get Event by Configuration and Uid
76
            $event = EventUtility::getOriginalRecordByConfiguration($configuration, (int) $this->request->getArgument('event'));
77
            $index = $this->indexRepository->findByEventTraversing($event, true, false, 1)->getFirst();
78
79
            // if there is a valid index in the event
80
            if ($index) {
81
                $this->redirect('detail', null, null, ['index' => $index]);
82
            }
83
        }
84
    }
85
86
    /**
87
     * Latest action.
88
     *
89
     * @param \HDNET\Calendarize\Domain\Model\Index $index
90
     * @param \DateTime                             $startDate
91
     * @param \DateTime                             $endDate
92
     * @param array                                 $customSearch *
93
     * @param int                                   $year
94
     * @param int                                   $month
95
     * @param int                                   $week
96
     *
97
     * @ignorevalidation $startDate
98
     * @ignorevalidation $endDate
99
     * @ignorevalidation $customSearch
100
     *
101
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
102
     */
103
    public function latestAction(
104
        Index $index = null,
105
        \DateTime $startDate = null,
106
        \DateTime $endDate = null,
107
        array $customSearch = [],
108
        $year = null,
109
        $month = null,
110
        $week = null
111
    ) {
112
        $this->checkStaticTemplateIsIncluded();
113
        if (($index instanceof Index) && \in_array('detail', $this->getAllowedActions(), true)) {
114
            $this->forward('detail');
115
        }
116
117
        $search = $this->determineSearch($startDate, $endDate, $customSearch, $year, $month, null, $week);
118
119
        $this->slotExtendedAssignMultiple([
120
            'indices' => $search['indices'],
121
            'searchMode' => $search['searchMode'],
122
            'searchParameter' => [
123
                'startDate' => $startDate,
124
                'endDate' => $endDate,
125
                'customSearch' => $customSearch,
126
                'year' => $year,
127
                'month' => $month,
128
                'week' => $week,
129
            ],
130
        ], __CLASS__, __FUNCTION__);
131
    }
132
133
    /**
134
     * Result action.
135
     *
136
     * @param \HDNET\Calendarize\Domain\Model\Index $index
137
     * @param \DateTime                             $startDate
138
     * @param \DateTime                             $endDate
139
     * @param array                                 $customSearch
140
     * @param int                                   $year
141
     * @param int                                   $month
142
     * @param int                                   $week
143
     *
144
     * @ignorevalidation $startDate
145
     * @ignorevalidation $endDate
146
     * @ignorevalidation $customSearch
147
     *
148
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
149
     */
150
    public function resultAction(
151
        Index $index = null,
152
        \DateTime $startDate = null,
153
        \DateTime $endDate = null,
154
        array $customSearch = [],
155
        $year = null,
156
        $month = null,
157
        $week = null
158
    ) {
159
        $this->checkStaticTemplateIsIncluded();
160
        if (($index instanceof Index) && \in_array('detail', $this->getAllowedActions(), true)) {
161
            $this->forward('detail');
162
        }
163
164
        $search = $this->determineSearch($startDate, $endDate, $customSearch, $year, $month, null, $week);
165
166
        $this->slotExtendedAssignMultiple([
167
            'indices' => $search['indices'],
168
            'searchMode' => $search['searchMode'],
169
            'searchParameter' => [
170
                'startDate' => $startDate,
171
                'endDate' => $endDate,
172
                'customSearch' => $customSearch,
173
                'year' => $year,
174
                'month' => $month,
175
                'week' => $week,
176
            ],
177
        ], __CLASS__, __FUNCTION__);
178
    }
179
180
    /**
181
     * List action.
182
     *
183
     * @param \HDNET\Calendarize\Domain\Model\Index $index
184
     * @param \DateTime                             $startDate
185
     * @param \DateTime                             $endDate
186
     * @param array                                 $customSearch *
187
     * @param int                                   $year
188
     * @param int                                   $month
189
     * @param int                                   $day
190
     * @param int                                   $week
191
     *
192
     * @ignorevalidation $startDate
193
     * @ignorevalidation $endDate
194
     * @ignorevalidation $customSearch
195
     *
196
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
197
     */
198
    public function listAction(
199
        Index $index = null,
200
        \DateTime $startDate = null,
201
        \DateTime $endDate = null,
202
        array $customSearch = [],
203
        $year = null,
204
        $month = null,
205
        $day = null,
206
        $week = null
207
    ) {
208
        $this->checkStaticTemplateIsIncluded();
209
        if (($index instanceof Index) && \in_array('detail', $this->getAllowedActions(), true)) {
210
            $this->forward('detail');
211
        }
212
213
        $search = $this->determineSearch($startDate, $endDate, $customSearch, $year, $month, $day, $week);
214
215
        $this->slotExtendedAssignMultiple([
216
            'indices' => $search['indices'],
217
            'searchMode' => $search['searchMode'],
218
            'searchParameter' => [
219
                'startDate' => $startDate,
220
                'endDate' => $endDate,
221
                'customSearch' => $customSearch,
222
                'year' => $year,
223
                'month' => $month,
224
                'day' => $day,
225
                'week' => $week,
226
            ],
227
        ], __CLASS__, __FUNCTION__);
228
    }
229
230
    /**
231
     * Shortcut.
232
     */
233
    public function shortcutAction()
234
    {
235
        // @todo fetch the right event
236
237
        $this->view->assignMultiple([
238
            'indices' => $this->indexRepository->findAll(),
239
        ]);
240
    }
241
242
    /**
243
     * Past action.
244
     *
245
     * @param int    $limit
246
     * @param string $sort
247
     *
248
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
249
     */
250
    public function pastAction(
251
        $limit = 100,
0 ignored issues
show
Unused Code introduced by
The parameter $limit is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
252
        $sort = 'ASC'
0 ignored issues
show
Unused Code introduced by
The parameter $sort is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
253
    ) {
254
        $limit = (int) ($this->settings['limit']);
255
        $sort = $this->settings['sorting'];
256
        $this->checkStaticTemplateIsIncluded();
257
        $this->slotExtendedAssignMultiple([
258
           'indices' => $this->indexRepository->findByPast($limit, $sort),
259
        ], __CLASS__, __FUNCTION__);
260
    }
261
262
    /**
263
     * Year action.
264
     *
265
     * @param int $year
266
     */
267
    public function yearAction($year = null)
268
    {
269
        $date = DateTimeUtility::normalizeDateTime(1, 1, $year);
270
271
        $this->slotExtendedAssignMultiple([
272
            'indices' => $this->indexRepository->findYear((int) $date->format('Y')),
273
            'date' => $date,
274
        ], __CLASS__, __FUNCTION__);
275
    }
276
277
    /**
278
     * Month action.
279
     *
280
     * @param int $year
281
     * @param int $month
282
     * @param int $day
283
     */
284
    public function monthAction($year = null, $month = null, $day = null)
285
    {
286
        $date = DateTimeUtility::normalizeDateTime($day, $month, $year);
287
288
        $this->slotExtendedAssignMultiple([
289
            'date' => $date,
290
            'indices' => $this->indexRepository->findMonth((int) $date->format('Y'), (int) $date->format('n')),
291
        ], __CLASS__, __FUNCTION__);
292
    }
293
294
    /**
295
     * Week action.
296
     *
297
     * @param int $year
298
     * @param int $week
299
     */
300
    public function weekAction($year = null, $week = null)
301
    {
302
        $now = DateTimeUtility::getNow();
303
        if (null === $year) {
304
            $year = $now->format('o'); // 'o' instead of 'Y': http://php.net/manual/en/function.date.php#106974
305
        }
306
        if (null === $week) {
307
            $week = $now->format('W');
308
        }
309
        $weekStart = (int) $this->settings['weekStart'];
310
        $firstDay = DateTimeUtility::convertWeekYear2DayMonthYear((int) $week, $year, $weekStart);
311
        $timezone = DateTimeUtility::getTimeZone();
312
        $firstDay->setTimezone($timezone);
313
        $firstDay->setTime(0, 0, 0);
314
315
        $weekConfiguration = [
316
            '+0 day' => 2,
317
            '+1 days' => 2,
318
            '+2 days' => 2,
319
            '+3 days' => 2,
320
            '+4 days' => 2,
321
            '+5 days' => 1,
322
            '+6 days' => 1,
323
        ];
324
325
        $this->slotExtendedAssignMultiple([
326
            'firstDay' => $firstDay,
327
            'indices' => $this->indexRepository->findWeek($year, $week, $this->settings['weekStart']),
328
            'weekConfiguration' => $weekConfiguration,
329
        ], __CLASS__, __FUNCTION__);
330
    }
331
332
    /**
333
     * Day action.
334
     *
335
     * @param int $year
336
     * @param int $month
337
     * @param int $day
338
     */
339
    public function dayAction($year = null, $month = null, $day = null)
340
    {
341
        $date = DateTimeUtility::normalizeDateTime($day, $month, $year);
342
        $date->modify('+12 hours');
343
344
        $previous = clone $date;
345
        $previous->modify('-1 day');
346
347
        $next = clone $date;
348
        $next->modify('+1 day');
349
350
        $this->slotExtendedAssignMultiple([
351
            'indices' => $this->indexRepository->findDay((int) $date->format('Y'), (int) $date->format('n'), (int) $date->format('j')),
352
            'today' => $date,
353
            'previous' => $previous,
354
            'next' => $next,
355
        ], __CLASS__, __FUNCTION__);
356
    }
357
358
    /**
359
     * Detail action.
360
     *
361
     * @param \HDNET\Calendarize\Domain\Model\Index $index
362
     *
363
     * @return string
364
     */
365
    public function detailAction(Index $index = null)
366
    {
367
        if (null === $index) {
368
            // handle fallback for "strange language settings"
369
            if ($this->request->hasArgument('index')) {
370
                $indexId = (int) $this->request->getArgument('index');
371
                if ($indexId > 0) {
372
                    $index = $this->indexRepository->findByUid($indexId);
373
                }
374
            }
375
376
            if (null === $index) {
377
                if (!MathUtility::canBeInterpretedAsInteger($this->settings['listPid'])) {
378
                    return (string) TranslateUtility::get('noEventDetailView');
379
                }
380
                $this->slottedRedirect(__CLASS__, __FUNCTION__ . 'noEvent');
381
            }
382
        }
383
384
        $this->slotExtendedAssignMultiple([
385
            'index' => $index,
386
            'domain' => GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY'),
387
        ], __CLASS__, __FUNCTION__);
388
389
        return $this->view->render();
390
    }
391
392
    /**
393
     * Render the search view.
394
     *
395
     * @param \DateTime $startDate
396
     * @param \DateTime $endDate
397
     * @param array     $customSearch
398
     *
399
     * @ignorevalidation $startDate
400
     * @ignorevalidation $endDate
401
     * @ignorevalidation $customSearch
402
     */
403
    public function searchAction(\DateTime $startDate = null, \DateTime $endDate = null, array $customSearch = [])
404
    {
405
        $baseDate = DateTimeUtility::getNow();
406
        if (!($startDate instanceof \DateTimeInterface)) {
407
            $startDate = clone $baseDate;
408
        }
409
        if (!($endDate instanceof \DateTimeInterface)) {
410
            $baseDate->modify($this->settings['searchEndModifier']);
411
            $endDate = $baseDate;
412
        }
413
414
        $this->slotExtendedAssignMultiple([
415
            'startDate' => $startDate,
416
            'endDate' => $endDate,
417
            'customSearch' => $customSearch,
418
            'configurations' => $this->getCurrentConfigurations(),
419
        ], __CLASS__, __FUNCTION__);
420
    }
421
422
    /**
423
     * Render single items.
424
     */
425
    public function singleAction()
426
    {
427
        $indicies = [];
428
429
        // prepare selection
430
        $selections = [];
431
        $configurations = $this->getCurrentConfigurations();
432
        foreach (GeneralUtility::trimExplode(',', $this->settings['singleItems']) as $item) {
433
            list($table, $uid) = BackendUtility::splitTable_Uid($item);
434
            foreach ($configurations as $configuration) {
435
                if ($configuration['tableName'] === $table) {
436
                    $selections[] = [
437
                        'configuration' => $configuration,
438
                        'uid' => $uid,
439
                    ];
440
                    break;
441
                }
442
            }
443
        }
444
445
        // fetch index
446
        foreach ($selections as $selection) {
447
            $this->indexRepository->setIndexTypes([$selection['configuration']['uniqueRegisterKey']]);
448
            $dummyIndex = new Index();
449
            $dummyIndex->setForeignTable($selection['configuration']['tableName']);
450
            $dummyIndex->setForeignUid($selection['uid']);
451
452
            $result = $this->indexRepository->findByTraversing($dummyIndex);
453
            $index = $result->getQuery()->setLimit(1)->execute()->getFirst();
454
            if (\is_object($index)) {
455
                $indicies[] = $index;
456
            }
457
        }
458
459
        $this->slotExtendedAssignMultiple([
460
            'indicies' => $indicies,
461
            'configurations' => $configurations,
462
        ], __CLASS__, __FUNCTION__);
463
    }
464
465
    /**
466
     * Build the search structure.
467
     *
468
     * @param \DateTime|null $startDate
469
     * @param \DateTime|null $endDate
470
     * @param array          $customSearch
471
     * @param int            $year
472
     * @param int            $month
473
     * @param int            $day
474
     * @param int            $week
475
     *
476
     * @return array
477
     */
478
    protected function determineSearch(
479
        \DateTime $startDate = null,
480
        \DateTime $endDate = null,
481
        array $customSearch = [],
482
        $year = null,
483
        $month = null,
484
        $day = null,
485
        $week = null
486
    ) {
487
        $searchMode = false;
488
        if ($startDate || $endDate || !empty($customSearch)) {
489
            $searchMode = true;
490
            $indices = $this->indexRepository->findBySearch($startDate, $endDate, $customSearch);
491
        } elseif (MathUtility::canBeInterpretedAsInteger($year) && MathUtility::canBeInterpretedAsInteger($month) && MathUtility::canBeInterpretedAsInteger($day)) {
492
            $indices = $this->indexRepository->findDay((int) $year, (int) $month, (int) $day);
493
        } elseif (MathUtility::canBeInterpretedAsInteger($year) && MathUtility::canBeInterpretedAsInteger($month)) {
494
            $indices = $this->indexRepository->findMonth((int) $year, (int) $month);
495
        } elseif (MathUtility::canBeInterpretedAsInteger($year) && MathUtility::canBeInterpretedAsInteger($week)) {
496
            $indices = $this->indexRepository->findWeek($year, $week, $this->settings['weekStart']);
497
        } elseif (MathUtility::canBeInterpretedAsInteger($year)) {
498
            $indices = $this->indexRepository->findYear((int) $year);
499
        } else {
500
            $overrideStartDate = (int) $this->settings['overrideStartdate'];
501
            $overrideEndDate = (int) $this->settings['overrideEnddate'];
502
            $indices = $this->indexRepository->findList(
503
                (int) $this->settings['limit'],
504
                $this->settings['listStartTime'],
505
                (int) $this->settings['listStartTimeOffsetHours'],
506
                $overrideStartDate,
507
                $overrideEndDate
508
            );
509
        }
510
511
        // use this variable in your extension to add more custom variables
512
        $variables = [
513
            'extended' => [
514
                'indices' => $indices,
515
                'searchMode' => $searchMode,
516
                'parameters' => [
517
                    'startDate' => $startDate,
518
                    'endDate' => $endDate,
519
                    'customSearch' => $customSearch,
520
                    'year' => $year,
521
                    'month' => $month,
522
                    'day' => $day,
523
                    'week' => $week,
524
                ],
525
            ],
526
        ];
527
        $variables['settings'] = $this->settings;
528
529
        $dispatcher = $this->objectManager->get(Dispatcher::class);
530
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__, $variables);
531
532
        return $variables['extended'];
533
    }
534
535
    /**
536
     * Get the allowed actions.
537
     *
538
     * @return array
539
     */
540
    protected function getAllowedActions(): array
541
    {
542
        $configuration = $this->configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
543
        $allowedActions = [];
544
        foreach ($configuration['controllerConfiguration'] as $controllerName => $controllerActions) {
545
            $allowedActions[$controllerName] = $controllerActions['actions'];
546
        }
547
548
        return \is_array($allowedActions['Calendar']) ? $allowedActions['Calendar'] : [];
549
    }
550
551
    /**
552
     * Get the current configurations.
553
     *
554
     * @return array
555
     */
556
    protected function getCurrentConfigurations()
557
    {
558
        $configurations = GeneralUtility::trimExplode(',', $this->settings['configuration'], true);
559
        $return = [];
560
        foreach (Register::getRegister() as $key => $configuration) {
561
            if (\in_array($key, $configurations, true)) {
562
                $return[] = $configuration;
563
            }
564
        }
565
566
        return $return;
567
    }
568
569
    /**
570
     * A redirect that have a slot included.
571
     *
572
     * @param string $signalClassName name of the signal class: __CLASS__
573
     * @param string $signalName      name of the signal: __FUNCTION__
574
     * @param array  $variables       optional: if not set use the defaults
575
     */
576
    protected function slottedRedirect($signalClassName, $signalName, $variables = null)
577
    {
578
        // set default variables for the redirect
579
        if (null === $variables) {
580
            $variables['extended'] = [
581
                'actionName' => 'list',
582
                'controllerName' => null,
583
                'extensionName' => null,
584
                'arguments' => [],
585
                'pageUid' => $this->settings['listPid'],
586
                'delay' => 0,
587
                'statusCode' => 301,
588
            ];
589
            $variables['extended']['pluginHmac'] = $this->calculatePluginHmac();
590
            $variables['settings'] = $this->settings;
591
        }
592
593
        $dispatcher = $this->objectManager->get(Dispatcher::class);
594
        $variables = $dispatcher->dispatch($signalClassName, $signalName, $variables);
595
596
        $this->redirect(
597
            $variables['extended']['actionName'],
598
            $variables['extended']['controllerName'],
599
            $variables['extended']['extensionName'],
600
            $variables['extended']['arguments'],
601
            $variables['extended']['pageUid'],
602
            $variables['extended']['delay'],
603
            $variables['extended']['statusCode']
604
        );
605
    }
606
}
607