Passed
Pull Request — master (#123)
by
unknown
05:29
created

ToolboxController::renderTools()   D

Complexity

Conditions 20
Paths 20

Size

Total Lines 45
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 20
eloc 41
c 1
b 0
f 0
nc 20
nop 0
dl 0
loc 45
rs 4.1666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
4
 *
5
 * This file is part of the Kitodo and TYPO3 projects.
6
 *
7
 * @license GNU General Public License version 3 or later.
8
 * For the full copyright and license information, please read the
9
 * LICENSE.txt file that was distributed with this source code.
10
 */
11
12
namespace Kitodo\Dlf\Controller;
13
14
use Kitodo\Dlf\Common\AbstractDocument;
15
use Kitodo\Dlf\Common\Helper;
16
use Psr\Http\Message\ResponseInterface;
17
use TYPO3\CMS\Core\Utility\GeneralUtility;
18
use TYPO3\CMS\Core\Utility\MathUtility;
19
20
/**
21
 * Controller class for plugin 'Toolbox'.
22
 *
23
 * @package TYPO3
24
 * @subpackage dlf
25
 *
26
 * @access public
27
 */
28
class ToolboxController extends AbstractController
29
{
30
31
    /**
32
     * @access private
33
     * @var AbstractDocument This holds the current document
34
     */
35
    private AbstractDocument $currentDocument;
36
37
    /**
38
     * The main method of the plugin
39
     *
40
     * @access public
41
     *
42
     * @return ResponseInterface the response
43
     */
44
    public function mainAction(): ResponseInterface
45
    {
46
        // Load current document.
47
        $this->loadDocument();
48
49
        $this->view->assign('double', $this->requestData['double']);
50
51
        if (!$this->isDocMissingOrEmpty()) {
52
            $this->currentDocument = $this->document->getCurrentDocument();
53
        }
54
55
        $this->renderTools();
56
        $this->view->assign('viewData', $this->viewData);
57
58
        return $this->htmlResponse();
59
    }
60
61
    /**
62
     * Renders tool in the toolbox.
63
     *
64
     * @access private
65
     *
66
     * @return void
67
     */
68
    private function renderTools(): void
69
    {
70
        if (!empty($this->settings['tools'])) {
71
72
            $tools = explode(',', $this->settings['tools']);
73
74
            foreach ($tools as $tool) {
75
                switch ($tool) {
76
                    case 'tx_dlf_annotationtool':
77
                    case 'annotationtool':
78
                        $this->renderToolByName('renderAnnotationTool');
79
                        break;
80
                    case 'tx_dlf_fulltextdownloadtool':
81
                    case 'fulltextdownloadtool':
82
                        $this->renderToolByName('renderFulltextDownloadTool');
83
                        break;
84
                    case 'tx_dlf_fulltexttool':
85
                    case 'fulltexttool':
86
                        $this->renderToolByName('renderFulltextTool');
87
                        break;
88
                    case 'tx_dlf_imagedownloadtool':
89
                    case 'imagedownloadtool':
90
                        $this->renderToolByName('renderImageDownloadTool');
91
                        break;
92
                    case 'tx_dlf_imagemanipulationtool':
93
                    case 'imagemanipulationtool':
94
                        $this->renderToolByName('renderImageManipulationTool');
95
                        break;
96
                    case 'tx_dlf_modeldownloadtool':
97
                    case 'modeldownloadtool':
98
                        $this->renderToolByName('renderModelDownloadTool');
99
                        break;
100
                    case 'tx_dlf_pdfdownloadtool':
101
                    case 'pdfdownloadtool':
102
                        $this->renderToolByName('renderPdfDownloadTool');
103
                        break;
104
                    case 'tx_dlf_searchindocumenttool':
105
                    case 'searchindocumenttool':
106
                        $this->renderToolByName('renderSearchInDocumentTool');
107
                        break;
108
                    case 'scoretool':
109
                        $this->renderToolByName('renderScoreTool');
110
                        break;
111
                    default:
112
                        $this->logger->warning('Incorrect tool configuration: "' . $this->settings['tools'] . '". Tool "' . $tool . '" does not exist.');
0 ignored issues
show
Bug introduced by
The method warning() does not exist on null. ( Ignorable by Annotation )

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

112
                        $this->logger->/** @scrutinizer ignore-call */ 
113
                                       warning('Incorrect tool configuration: "' . $this->settings['tools'] . '". Tool "' . $tool . '" does not exist.');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
113
                }
114
            }
115
        }
116
    }
117
118
    /**
119
     * Renders tool by the name in the toolbox.
120
     *
121
     * @access private
122
     *
123
     * @param string $tool name
124
     *
125
     * @return void
126
     */
127
    private function renderToolByName(string $tool): void
128
    {
129
        $this->$tool();
130
        $this->view->assign($tool, true);
131
    }
132
133
    /**
134
     * Get image's URL and MIME type information's.
135
     *
136
     * @access private
137
     *
138
     * @param int $page Page number
139
     *
140
     * @return array Array of image information's.
141
     */
142
    public function getImage(int $page): array
143
    {
144
        // Get @USE value of METS fileGroup.
145
        $image = $this->getFile($page, GeneralUtility::trimExplode(',', $this->settings['fileGrpsImageDownload']));
146
        switch ($image['mimetype']) {
147
            case 'image/jpeg':
148
                $image['mimetypeLabel'] = ' (JPG)';
149
                break;
150
            case 'image/tiff':
151
                $image['mimetypeLabel'] = ' (TIFF)';
152
                break;
153
            default:
154
                $image['mimetypeLabel'] = '';
155
        }
156
        return $image;
157
    }
158
159
    /**
160
     * Renders the annotation tool (used in template)
161
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
162
     *
163
     * @access private
164
     *
165
     * @return void
166
     */
167
    private function renderAnnotationTool(): void
168
    {
169
        if ($this->isDocMissingOrEmpty()) {
170
            // Quit without doing anything if required variables are not set.
171
            return;
172
        }
173
174
        $this->setPage();
175
176
        $annotationContainers = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[$this->requestData['page']]]['annotationContainers'];
177
        if (
178
            $annotationContainers != null
179
            && count($annotationContainers) > 0
180
        ) {
181
            $this->view->assign('annotationTool', true);
182
        } else {
183
            $this->view->assign('annotationTool', false);
184
        }
185
    }
186
187
    /**
188
     * Renders the fulltext download tool (used in template)
189
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
190
     *
191
     * @access private
192
     *
193
     * @return void
194
     */
195
    private function renderFulltextDownloadTool(): void
196
    {
197
        if (
198
            $this->isDocMissingOrEmpty()
199
            || empty($this->extConf['files']['fileGrpFulltext'])
200
        ) {
201
            // Quit without doing anything if required variables are not set.
202
            return;
203
        }
204
205
        $this->setPage();
206
207
        // Get text download.
208
        $this->view->assign('fulltextDownload', !$this->isFullTextEmpty());
209
    }
210
211
    /**
212
     * Renders the fulltext tool (used in template)
213
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
214
     *
215
     * @access private
216
     *
217
     * @return void
218
     */
219
    private function renderFulltextTool(): void
220
    {
221
        if (
222
            $this->isDocMissingOrEmpty()
223
            || empty($this->extConf['files']['fileGrpFulltext'])
224
        ) {
225
            // Quit without doing anything if required variables are not set.
226
            return;
227
        }
228
229
        $this->setPage();
230
231
        if (!$this->isFullTextEmpty()) {
232
            $this->view->assign('fulltext', true);
233
            $this->view->assign('activateFullTextInitially', MathUtility::forceIntegerInRange($this->settings['activateFullTextInitially'], 0, 1, 0));
234
        } else {
235
            $this->view->assign('fulltext', false);
236
        }
237
    }
238
239
    /**
240
     * Renders the score tool
241
     *
242
     * @return void
243
     */
244
    public function renderScoreTool()
245
    {
246
        if (
247
            $this->isDocMissingOrEmpty()
248
            || empty($this->extConf['files']['fileGrpScore'])
249
        ) {
250
            // Quit without doing anything if required variables are not set.
251
            return;
252
        }
253
254
        if ($this->requestData['page']) {
255
            $currentPhysPage = $this->document->getCurrentDocument()->physicalStructure[$this->requestData['page']];
256
        } else {
257
            $currentPhysPage = $this->document->getCurrentDocument()->physicalStructure[1];
258
        }
259
260
        $fileGrpsScores = GeneralUtility::trimExplode(',', $this->extConf['files']['fileGrpScore']);
261
        foreach ($fileGrpsScores as $fileGrpScore) {
262
            if ($this->document->getCurrentDocument()->physicalStructureInfo[$currentPhysPage]['files'][$fileGrpScore]) {
263
                $scoreFile = $this->document->getCurrentDocument()->physicalStructureInfo[$currentPhysPage]['files'][$fileGrpScore];
264
            }
265
        }
266
        if (!empty($scoreFile)) {
267
            $this->view->assign('score', true);
268
            $this->view->assign('activateScoreInitially', MathUtility::forceIntegerInRange($this->settings['activateScoreInitially'], 0, 1, 0));
269
        } else {
270
            $this->view->assign('score', false);
271
        }
272
    }
273
274
    /**
275
     * Renders the image download tool (used in template)
276
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
277
     *
278
     * @access private
279
     *
280
     * @return void
281
     */
282
    private function renderImageDownloadTool(): void
283
    {
284
        if (
285
            $this->isDocMissingOrEmpty()
286
            || empty($this->settings['fileGrpsImageDownload'])
287
        ) {
288
            // Quit without doing anything if required variables are not set.
289
            return;
290
        }
291
292
        $this->setPage();
293
        $page = $this->requestData['page'] ?? 0;
294
295
        $imageArray = [];
296
        // Get left or single page download.
297
        $image = $this->getImage($page);
298
        if (Helper::filterFilesByMimeType($image, ['image'])) {
299
            $imageArray[0] = $image;
300
        }
301
302
        if ($this->requestData['double'] == 1) {
303
            $image = $this->getImage($page + 1);
304
            if (Helper::filterFilesByMimeType($image, ['image'])) {
305
                $imageArray[1] = $image;
306
            }
307
        }
308
309
        $this->view->assign('imageDownload', $imageArray);
310
    }
311
312
    /**
313
     * Get file's URL and MIME type
314
     *
315
     * @access private
316
     *
317
     * @param int $page Page number
318
     *
319
     * @return array Array of file information
320
     */
321
    private function getFile(int $page, array $fileGrps): array
322
    {
323
        $file = [];
324
        while ($fileGrp = @array_pop($fileGrps)) {
325
            $physicalStructureInfo = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[$page]];
326
            $fileId = $physicalStructureInfo['files'][$fileGrp];
327
            if (!empty($fileId)) {
328
                $file['url'] = $this->currentDocument->getDownloadLocation($fileId);
329
                $file['mimetype'] = $this->currentDocument->getFileMimeType($fileId);
330
            } else {
331
                $this->logger->warning('File not found in fileGrp "' . $fileGrp . '"');
332
            }
333
        }
334
        return $file;
335
    }
336
337
    /**
338
     * Renders the image manipulation tool (used in template)
339
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
340
     *
341
     * @access private
342
     *
343
     * @return void
344
     */
345
    private function renderImageManipulationTool(): void
346
    {
347
        // Set parent element for initialization.
348
        $parentContainer = !empty($this->settings['parentContainer']) ? $this->settings['parentContainer'] : '.tx-dlf-imagemanipulationtool';
349
350
        $this->view->assign('imageManipulation', true);
351
        $this->view->assign('parentContainer', $parentContainer);
352
    }
353
354
    /**
355
     * Renders the model download tool
356
     * Renders the model download tool (used in template)
357
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
358
     *
359
     * @access private
360
     *
361
     * @return void
362
     */
363
    private function renderModelDownloadTool(): void
364
    {
365
        if (
366
            $this->isDocMissingOrEmpty()
367
            || empty($this->settings['fileGrpsModelDownload'])
368
        ) {
369
            // Quit without doing anything if required variables are not set.
370
            return;
371
        }
372
373
        $this->setPage();
374
375
        $this->view->assign('modelDownload', $this->getFile($this->requestData['page'], GeneralUtility::trimExplode(',', $this->settings['fileGrpsModelDownload'])));
376
    }
377
378
    /**
379
     * Renders the PDF download tool (used in template)
380
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
381
     *
382
     * @access private
383
     *
384
     * @return void
385
     */
386
    private function renderPdfDownloadTool(): void
387
    {
388
        if (
389
            $this->isDocMissingOrEmpty()
390
            || empty($this->extConf['files']['fileGrpDownload'])
391
        ) {
392
            // Quit without doing anything if required variables are not set.
393
            return;
394
        }
395
396
        $this->setPage();
397
398
        // Get single page downloads.
399
        $this->view->assign('pageLinks', $this->getPageLink());
400
        // Get work download.
401
        $this->view->assign('workLink', $this->getWorkLink());
402
    }
403
404
    /**
405
     * Get page's download link
406
     *
407
     * @access private
408
     *
409
     * @return array Link to downloadable page
410
     */
411
    private function getPageLink(): array
412
    {
413
        $firstPageLink = '';
414
        $secondPageLink = '';
415
        $pageLinkArray = [];
416
        $pageNumber = $this->requestData['page'] ?? 0;
417
        $fileGrpsDownload = GeneralUtility::trimExplode(',', $this->extConf['files']['fileGrpDownload']);
418
        // Get image link.
419
        while ($fileGrpDownload = array_shift($fileGrpsDownload)) {
420
            $firstFileGroupDownload = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[$pageNumber]]['files'][$fileGrpDownload];
421
            if (!empty($firstFileGroupDownload)) {
422
                $firstPageLink = $this->currentDocument->getFileLocation($firstFileGroupDownload);
423
                // Get second page, too, if double page view is activated.
424
                $secondFileGroupDownload = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[$pageNumber + 1]]['files'][$fileGrpDownload];
425
                if (
426
                    $this->requestData['double']
427
                    && $pageNumber < $this->currentDocument->numPages
428
                    && !empty($secondFileGroupDownload)
429
                ) {
430
                    $secondPageLink = $this->currentDocument->getFileLocation($secondFileGroupDownload);
431
                }
432
                break;
433
            }
434
        }
435
        if (
436
            empty($firstPageLink)
437
            && empty($secondPageLink)
438
        ) {
439
            $this->logger->warning('File not found in fileGrps "' . $this->extConf['files']['fileGrpDownload'] . '"');
440
        }
441
442
        if (!empty($firstPageLink)) {
443
            $pageLinkArray[0] = $firstPageLink;
444
        }
445
        if (!empty($secondPageLink)) {
446
            $pageLinkArray[1] = $secondPageLink;
447
        }
448
        return $pageLinkArray;
449
    }
450
451
    /**
452
     * Get work's download link
453
     *
454
     * @access private
455
     *
456
     * @return string Link to downloadable work
457
     */
458
    private function getWorkLink(): string
459
    {
460
        $workLink = '';
461
        $fileGrpsDownload = GeneralUtility::trimExplode(',', $this->extConf['files']['fileGrpDownload']);
462
        // Get work link.
463
        while ($fileGrpDownload = array_shift($fileGrpsDownload)) {
464
            $fileGroupDownload = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[0]]['files'][$fileGrpDownload];
465
            if (!empty($fileGroupDownload)) {
466
                $workLink = $this->currentDocument->getFileLocation($fileGroupDownload);
467
                break;
468
            } else {
469
                $details = $this->currentDocument->getLogicalStructure($this->currentDocument->toplevelId);
470
                if (!empty($details['files'][$fileGrpDownload])) {
471
                    $workLink = $this->currentDocument->getFileLocation($details['files'][$fileGrpDownload]);
472
                    break;
473
                }
474
            }
475
        }
476
        if (empty($workLink)) {
477
            $this->logger->warning('File not found in fileGrps "' . $this->extConf['files']['fileGrpDownload'] . '"');
478
        }
479
        return $workLink;
480
    }
481
482
    /**
483
     * Renders the searchInDocument tool (used in template)
484
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
485
     *
486
     * @access private
487
     *
488
     * @return void
489
     */
490
    private function renderSearchInDocumentTool(): void
491
    {
492
        if (
493
            $this->isDocMissingOrEmpty()
494
            || empty($this->extConf['files']['fileGrpFulltext'])
495
            || empty($this->settings['solrcore'])
496
        ) {
497
            // Quit without doing anything if required variables are not set.
498
            return;
499
        }
500
501
        $this->setPage();
502
503
        // Quit if no fulltext file is present
504
        if ($this->isFullTextEmpty()) {
505
            return;
506
        }
507
508
        $viewArray = [
509
            'labelQueryUrl' => $this->settings['queryInputName'],
510
            'labelStart' => $this->settings['startInputName'],
511
            'labelId' => $this->settings['idInputName'],
512
            'labelPid' => $this->settings['pidInputName'],
513
            'labelPageUrl' => $this->settings['pageInputName'],
514
            'labelHighlightWord' => $this->settings['highlightWordInputName'],
515
            'labelEncrypted' => $this->settings['encryptedInputName'],
516
            'documentId' => $this->getCurrentDocumentId(),
517
            'documentPageId' => $this->document->getPid(),
518
            'solrEncrypted' => $this->getEncryptedCoreName() ? : ''
519
        ];
520
521
        $this->view->assign('searchInDocument', $viewArray);
522
    }
523
524
    /**
525
     * Get current document id. As default the uid will be used.
526
     * In case there is defined documentIdUrlSchema then the id will
527
     * extracted from this URL.
528
     *
529
     * @access private
530
     *
531
     * @return string with current document id
532
     */
533
    private function getCurrentDocumentId(): string
534
    {
535
        $id = $this->document->getUid();
0 ignored issues
show
Bug introduced by
The method getUid() does not exist on null. ( Ignorable by Annotation )

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

535
        /** @scrutinizer ignore-call */ 
536
        $id = $this->document->getUid();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
536
537
        if ($id !== null && $id > 0) {
538
            // we found the document uid
539
            return (string) $id;
540
        } else {
541
            $id = $this->requestData['id'];
542
            if (!GeneralUtility::isValidUrl($id)) {
543
                // we found no valid URI --> something unexpected we cannot search within.
544
                return '';
545
            }
546
        }
547
548
        // example: https://host.de/items/*id*/record
549
        if (!empty($this->settings['documentIdUrlSchema'])) {
550
            $arr = explode('*', $this->settings['documentIdUrlSchema']);
551
552
            if (count($arr) == 2) {
553
                $id = explode($arr[0], $id)[0];
554
            } else if (count($arr) == 3) {
555
                $sub = substr($id, strpos($id, $arr[0]) + strlen($arr[0]), strlen($id));
556
                $id = substr($sub, 0, strpos($sub, $arr[2]));
557
            }
558
        }
559
        return $id;
560
    }
561
562
    /**
563
     * Get the encrypted Solr core name
564
     *
565
     * @access private
566
     *
567
     * @return string with encrypted core name
568
     */
569
    private function getEncryptedCoreName(): string
570
    {
571
        // Get core name.
572
        $name = Helper::getIndexNameFromUid($this->settings['solrcore'], 'tx_dlf_solrcores');
573
        // Encrypt core name.
574
        if (!empty($name)) {
575
            $name = Helper::encrypt($name);
576
        }
577
        return $name;
578
    }
579
580
    /**
581
     * Check if the full text is empty.
582
     *
583
     * @access private
584
     *
585
     * @return bool true if empty, false otherwise
586
     */
587
    private function isFullTextEmpty(): bool
588
    {
589
        $fileGrpsFulltext = GeneralUtility::trimExplode(',', $this->extConf['files']['fileGrpFulltext']);
590
        while ($fileGrpFulltext = array_shift($fileGrpsFulltext)) {
591
            if (isset($this->requestData['page'])) {
592
                $files = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[$this->requestData['page']]]['files'];
593
                if (!empty($files[$fileGrpFulltext])) {
594
                    return false;
595
                }
596
            }
597
        }
598
        return true;
599
    }
600
}
601