Passed
Pull Request — master (#123)
by
unknown
06:03 queued 21s
created

ToolboxController::getPageLink()   B

Complexity

Conditions 10
Paths 32

Size

Total Lines 38
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 2 Features 0
Metric Value
cc 10
eloc 25
c 5
b 2
f 0
nc 32
nop 0
dl 0
loc 38
rs 7.6666

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
294
        $imageArray = [];
295
        // Get left or single page download.
296
        $image = $this->getImage($this->requestData['page']);
297
        if (Helper::filterFilesByMimeType($image, ['image'])) {
298
            $imageArray[0] = $image;
299
        }
300
301
        if ($this->requestData['double'] == 1) {
302
            $image = $this->getImage($this->requestData['page'] + 1);
303
            if (Helper::filterFilesByMimeType($image, ['image'])) {
304
                $imageArray[1] = $image;
305
            }
306
        }
307
308
        $this->view->assign('imageDownload', $imageArray);
309
    }
310
311
    /**
312
     * Get file's URL and MIME type
313
     *
314
     * @access private
315
     *
316
     * @param int $page Page number
317
     *
318
     * @return array Array of file information
319
     */
320
    private function getFile(int $page, array $fileGrps): array
321
    {
322
        $file = [];
323
        while ($fileGrp = @array_pop($fileGrps)) {
324
            $physicalStructureInfo = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[$page]];
325
            $fileId = $physicalStructureInfo['files'][$fileGrp];
326
            if (!empty($fileId)) {
327
                $file['url'] = $this->currentDocument->getDownloadLocation($fileId);
328
                $file['mimetype'] = $this->currentDocument->getFileMimeType($fileId);
329
            } else {
330
                $this->logger->warning('File not found in fileGrp "' . $fileGrp . '"');
331
            }
332
        }
333
        return $file;
334
    }
335
336
    /**
337
     * Renders the image manipulation tool (used in template)
338
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
339
     *
340
     * @access private
341
     *
342
     * @return void
343
     */
344
    private function renderImageManipulationTool(): void
345
    {
346
        // Set parent element for initialization.
347
        $parentContainer = !empty($this->settings['parentContainer']) ? $this->settings['parentContainer'] : '.tx-dlf-imagemanipulationtool';
348
349
        $this->view->assign('imageManipulation', true);
350
        $this->view->assign('parentContainer', $parentContainer);
351
    }
352
353
    /**
354
     * Renders the model download tool
355
     * Renders the model download tool (used in template)
356
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
357
     *
358
     * @access private
359
     *
360
     * @return void
361
     */
362
    private function renderModelDownloadTool(): void
363
    {
364
        if (
365
            $this->isDocMissingOrEmpty()
366
            || empty($this->settings['fileGrpsModelDownload'])
367
        ) {
368
            // Quit without doing anything if required variables are not set.
369
            return;
370
        }
371
372
        $this->setPage();
373
374
        $this->view->assign('modelDownload', $this->getFile($this->requestData['page'], GeneralUtility::trimExplode(',', $this->settings['fileGrpsModelDownload'])));
375
    }
376
377
    /**
378
     * Renders the PDF download tool (used in template)
379
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
380
     *
381
     * @access private
382
     *
383
     * @return void
384
     */
385
    private function renderPdfDownloadTool(): void
386
    {
387
        if (
388
            $this->isDocMissingOrEmpty()
389
            || empty($this->extConf['files']['fileGrpDownload'])
390
        ) {
391
            // Quit without doing anything if required variables are not set.
392
            return;
393
        }
394
395
        $this->setPage();
396
397
        // Get single page downloads.
398
        $this->view->assign('pageLinks', $this->getPageLink());
399
        // Get work download.
400
        $this->view->assign('workLink', $this->getWorkLink());
401
    }
402
403
    /**
404
     * Get page's download link
405
     *
406
     * @access private
407
     *
408
     * @return array Link to downloadable page
409
     */
410
    private function getPageLink(): array
411
    {
412
        $firstPageLink = '';
413
        $secondPageLink = '';
414
        $pageLinkArray = [];
415
        $pageNumber = $this->requestData['page'];
416
        $fileGrpsDownload = GeneralUtility::trimExplode(',', $this->extConf['files']['fileGrpDownload']);
417
        // Get image link.
418
        while ($fileGrpDownload = array_shift($fileGrpsDownload)) {
419
            $firstFileGroupDownload = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[$pageNumber]]['files'][$fileGrpDownload];
420
            if (!empty($firstFileGroupDownload)) {
421
                $firstPageLink = $this->currentDocument->getFileLocation($firstFileGroupDownload);
422
                // Get second page, too, if double page view is activated.
423
                $secondFileGroupDownload = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[$pageNumber + 1]]['files'][$fileGrpDownload];
424
                if (
425
                    $this->requestData['double']
426
                    && $pageNumber < $this->currentDocument->numPages
427
                    && !empty($secondFileGroupDownload)
428
                ) {
429
                    $secondPageLink = $this->currentDocument->getFileLocation($secondFileGroupDownload);
430
                }
431
                break;
432
            }
433
        }
434
        if (
435
            empty($firstPageLink)
436
            && empty($secondPageLink)
437
        ) {
438
            $this->logger->warning('File not found in fileGrps "' . $this->extConf['files']['fileGrpDownload'] . '"');
439
        }
440
441
        if (!empty($firstPageLink)) {
442
            $pageLinkArray[0] = $firstPageLink;
443
        }
444
        if (!empty($secondPageLink)) {
445
            $pageLinkArray[1] = $secondPageLink;
446
        }
447
        return $pageLinkArray;
448
    }
449
450
    /**
451
     * Get work's download link
452
     *
453
     * @access private
454
     *
455
     * @return string Link to downloadable work
456
     */
457
    private function getWorkLink(): string
458
    {
459
        $workLink = '';
460
        $fileGrpsDownload = GeneralUtility::trimExplode(',', $this->extConf['files']['fileGrpDownload']);
461
        // Get work link.
462
        while ($fileGrpDownload = array_shift($fileGrpsDownload)) {
463
            $fileGroupDownload = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[0]]['files'][$fileGrpDownload];
464
            if (!empty($fileGroupDownload)) {
465
                $workLink = $this->currentDocument->getFileLocation($fileGroupDownload);
466
                break;
467
            } else {
468
                $details = $this->currentDocument->getLogicalStructure($this->currentDocument->toplevelId);
469
                if (!empty($details['files'][$fileGrpDownload])) {
470
                    $workLink = $this->currentDocument->getFileLocation($details['files'][$fileGrpDownload]);
471
                    break;
472
                }
473
            }
474
        }
475
        if (empty($workLink)) {
476
            $this->logger->warning('File not found in fileGrps "' . $this->extConf['files']['fileGrpDownload'] . '"');
477
        }
478
        return $workLink;
479
    }
480
481
    /**
482
     * Renders the searchInDocument tool (used in template)
483
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
484
     *
485
     * @access private
486
     *
487
     * @return void
488
     */
489
    private function renderSearchInDocumentTool(): void
490
    {
491
        if (
492
            $this->isDocMissingOrEmpty()
493
            || empty($this->extConf['files']['fileGrpFulltext'])
494
            || empty($this->settings['solrcore'])
495
        ) {
496
            // Quit without doing anything if required variables are not set.
497
            return;
498
        }
499
500
        $this->setPage();
501
502
        // Quit if no fulltext file is present
503
        if ($this->isFullTextEmpty()) {
504
            return;
505
        }
506
507
        $viewArray = [
508
            'labelQueryUrl' => $this->settings['queryInputName'],
509
            'labelStart' => $this->settings['startInputName'],
510
            'labelId' => $this->settings['idInputName'],
511
            'labelPid' => $this->settings['pidInputName'],
512
            'labelPageUrl' => $this->settings['pageInputName'],
513
            'labelHighlightWord' => $this->settings['highlightWordInputName'],
514
            'labelEncrypted' => $this->settings['encryptedInputName'],
515
            'documentId' => $this->getCurrentDocumentId(),
516
            'documentPageId' => $this->document->getPid(),
517
            'solrEncrypted' => $this->getEncryptedCoreName() ? : ''
518
        ];
519
520
        $this->view->assign('searchInDocument', $viewArray);
521
    }
522
523
    /**
524
     * Get current document id. As default the uid will be used.
525
     * In case there is defined documentIdUrlSchema then the id will
526
     * extracted from this URL.
527
     *
528
     * @access private
529
     *
530
     * @return string with current document id
531
     */
532
    private function getCurrentDocumentId(): string
533
    {
534
        $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

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