Passed
Pull Request — master (#123)
by
unknown
07:53 queued 02:59
created

ToolboxController::renderTools()   C

Complexity

Conditions 17
Paths 17

Size

Total Lines 38
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 17
eloc 34
c 1
b 0
f 0
nc 17
nop 0
dl 0
loc 38
rs 5.2166

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 TYPO3\CMS\Core\Utility\GeneralUtility;
17
use TYPO3\CMS\Core\Utility\MathUtility;
18
19
/**
20
 * Controller class for plugin 'Toolbox'.
21
 *
22
 * @package TYPO3
23
 * @subpackage dlf
24
 *
25
 * @access public
26
 */
27
class ToolboxController extends AbstractController
28
{
29
30
    /**
31
     * @access private
32
     * @var AbstractDocument This holds the current document
33
     */
34
    private AbstractDocument $currentDocument;
35
36
    /**
37
     * The main method of the plugin
38
     *
39
     * @access public
40
     *
41
     * @return void
42
     */
43
    public function mainAction(): void
44
    {
45
        // Load current document.
46
        $this->loadDocument();
47
48
        $this->view->assign('double', $this->requestData['double']);
49
50
        if (!$this->isDocMissingOrEmpty()) {
51
            $this->currentDocument = $this->document->getCurrentDocument();
52
        }
53
54
        $this->renderTools();
55
        $this->view->assign('viewData', $this->viewData);
56
    }
57
58
    /**
59
     * Renders tool in the toolbox.
60
     *
61
     * @access private
62
     *
63
     * @return void
64
     */
65
    private function renderTools(): void
66
    {
67
        if (!empty($this->settings['tools'])) {
68
69
            $tools = explode(',', $this->settings['tools']);
70
71
            foreach ($tools as $tool) {
72
                switch ($tool) {
73
                    case 'tx_dlf_annotationtool':
74
                    case 'annotationtool':
75
                        $this->renderToolByName('renderAnnotationTool');
76
                        break;
77
                    case 'tx_dlf_fulltextdownloadtool':
78
                    case 'fulltextdownloadtool':
79
                        $this->renderToolByName('renderFulltextDownloadTool');
80
                        break;
81
                    case 'tx_dlf_fulltexttool':
82
                    case 'fulltexttool':
83
                        $this->renderToolByName('renderFulltextTool');
84
                        break;
85
                    case 'tx_dlf_imagedownloadtool':
86
                    case 'imagedownloadtool':
87
                        $this->renderToolByName('renderImageDownloadTool');
88
                        break;
89
                    case 'tx_dlf_imagemanipulationtool':
90
                    case 'imagemanipulationtool':
91
                        $this->renderToolByName('renderImageManipulationTool');
92
                        break;
93
                    case 'tx_dlf_pdfdownloadtool':
94
                    case 'pdfdownloadtool':
95
                        $this->renderToolByName('renderPdfDownloadTool');
96
                        break;
97
                    case 'tx_dlf_searchindocumenttool':
98
                    case 'searchindocumenttool':
99
                        $this->renderToolByName('renderSearchInDocumentTool');
100
                        break;
101
                    default:
102
                        $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

102
                        $this->logger->/** @scrutinizer ignore-call */ 
103
                                       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...
103
                }
104
            }
105
        }
106
    }
107
108
    /**
109
     * Renders tool by the name in the toolbox.
110
     *
111
     * @access private
112
     *
113
     * @param string $tool name
114
     *
115
     * @return void
116
     */
117
    private function renderToolByName(string $tool): void
118
    {
119
        $this->$tool();
120
        $this->view->assign($tool, true);
121
    }
122
123
    /**
124
     * Renders the annotation tool (used in template)
125
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
126
     *
127
     * @access private
128
     *
129
     * @return void
130
     */
131
    private function renderAnnotationTool(): void
132
    {
133
        if ($this->isDocMissingOrEmpty()) {
134
            // Quit without doing anything if required variables are not set.
135
            return;
136
        }
137
138
        $this->setPage();
139
140
        $annotationContainers = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[$this->requestData['page']]]['annotationContainers'];
141
        if (
142
            $annotationContainers != null
143
            && count($annotationContainers) > 0
144
        ) {
145
            $this->view->assign('annotationTool', true);
146
        } else {
147
            $this->view->assign('annotationTool', false);
148
        }
149
    }
150
151
    /**
152
     * Renders the fulltext download tool (used in template)
153
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
154
     *
155
     * @access private
156
     *
157
     * @return void
158
     */
159
    private function renderFulltextDownloadTool(): void
160
    {
161
        if (
162
            $this->isDocMissingOrEmpty()
163
            || empty($this->extConf['files']['fileGrpFulltext'])
164
        ) {
165
            // Quit without doing anything if required variables are not set.
166
            return;
167
        }
168
169
        $this->setPage();
170
171
        // Get text download.
172
        $this->view->assign('fulltextDownload', !$this->isFullTextEmpty());
173
    }
174
175
    /**
176
     * Renders the fulltext tool (used in template)
177
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
178
     *
179
     * @access private
180
     *
181
     * @return void
182
     */
183
    private function renderFulltextTool(): void
184
    {
185
        if (
186
            $this->isDocMissingOrEmpty()
187
            || empty($this->extConf['files']['fileGrpFulltext'])
188
        ) {
189
            // Quit without doing anything if required variables are not set.
190
            return;
191
        }
192
193
        $this->setPage();
194
195
        if (!$this->isFullTextEmpty()) {
196
            $this->view->assign('fulltext', true);
197
            $this->view->assign('activateFullTextInitially', MathUtility::forceIntegerInRange($this->settings['activateFullTextInitially'], 0, 1, 0));
198
        } else {
199
            $this->view->assign('fulltext', false);
200
        }
201
    }
202
203
    /**
204
     * Renders the image download tool (used in template)
205
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
206
     *
207
     * @access private
208
     *
209
     * @return void
210
     */
211
    private function renderImageDownloadTool(): void
212
    {
213
        if (
214
            $this->isDocMissingOrEmpty()
215
            || empty($this->settings['fileGrpsImageDownload'])
216
        ) {
217
            // Quit without doing anything if required variables are not set.
218
            return;
219
        }
220
221
        $this->setPage();
222
223
        $imageArray = [];
224
        // Get left or single page download.
225
        $imageArray[0] = $this->getImage($this->requestData['page']);
226
        if ($this->requestData['double'] == 1) {
227
            $imageArray[1] = $this->getImage($this->requestData['page'] + 1);
228
        }
229
        $this->view->assign('imageDownload', $imageArray);
230
    }
231
232
    /**
233
     * Get image's URL and MIME type
234
     *
235
     * @access private
236
     *
237
     * @param int $page Page number
238
     *
239
     * @return array Array of image links and image format information
240
     */
241
    private function getImage(int $page): array
242
    {
243
        $image = [];
244
        // Get @USE value of METS fileGrp.
245
        $fileGrps = GeneralUtility::trimExplode(',', $this->settings['fileGrpsImageDownload']);
246
        while ($fileGrp = @array_pop($fileGrps)) {
247
            // Get image link.
248
            $physicalStructureInfo = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[$page]];
249
            $fileId = $physicalStructureInfo['files'][$fileGrp];
250
            if (!empty($fileId)) {
251
                $image['url'] = $this->currentDocument->getDownloadLocation($fileId);
252
                $image['mimetype'] = $this->currentDocument->getFileMimeType($fileId);
253
                switch ($image['mimetype']) {
254
                    case 'image/jpeg':
255
                        $image['mimetypeLabel']  = ' (JPG)';
256
                        break;
257
                    case 'image/tiff':
258
                        $image['mimetypeLabel']  = ' (TIFF)';
259
                        break;
260
                    default:
261
                        $image['mimetypeLabel']  = '';
262
                }
263
                break;
264
            } else {
265
                $this->logger->warning('File not found in fileGrp "' . $fileGrp . '"');
266
            }
267
        }
268
        return $image;
269
    }
270
271
    /**
272
     * Renders the image manipulation tool (used in template)
273
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
274
     *
275
     * @access private
276
     *
277
     * @return void
278
     */
279
    private function renderImageManipulationTool(): void
280
    {
281
        // Set parent element for initialization.
282
        $parentContainer = !empty($this->settings['parentContainer']) ? $this->settings['parentContainer'] : '.tx-dlf-imagemanipulationtool';
283
284
        $this->view->assign('imageManipulation', true);
285
        $this->view->assign('parentContainer', $parentContainer);
286
    }
287
288
    /**
289
     * Renders the PDF download tool (used in template)
290
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
291
     *
292
     * @access private
293
     *
294
     * @return void
295
     */
296
    private function renderPdfDownloadTool(): void
297
    {
298
        if (
299
            $this->isDocMissingOrEmpty()
300
            || empty($this->extConf['files']['fileGrpDownload'])
301
        ) {
302
            // Quit without doing anything if required variables are not set.
303
            return;
304
        }
305
306
        $this->setPage();
307
308
        // Get single page downloads.
309
        $this->view->assign('pageLinks', $this->getPageLink());
310
        // Get work download.
311
        $this->view->assign('workLink', $this->getWorkLink());
312
    }
313
314
    /**
315
     * Get page's download link
316
     *
317
     * @access private
318
     *
319
     * @return array Link to downloadable page
320
     */
321
    private function getPageLink(): array
322
    {
323
        $firstPageLink = '';
324
        $secondPageLink = '';
325
        $pageLinkArray = [];
326
        $pageNumber = $this->requestData['page'];
327
        $fileGrpsDownload = GeneralUtility::trimExplode(',', $this->extConf['files']['fileGrpDownload']);
328
        // Get image link.
329
        while ($fileGrpDownload = array_shift($fileGrpsDownload)) {
330
            $firstFileGroupDownload = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[$pageNumber]]['files'][$fileGrpDownload];
331
            if (!empty($firstFileGroupDownload)) {
332
                $firstPageLink = $this->currentDocument->getFileLocation($firstFileGroupDownload);
333
                // Get second page, too, if double page view is activated.
334
                $secondFileGroupDownload = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[$pageNumber + 1]]['files'][$fileGrpDownload];
335
                if (
336
                    $this->requestData['double']
337
                    && $pageNumber < $this->currentDocument->numPages
338
                    && !empty($secondFileGroupDownload)
339
                ) {
340
                    $secondPageLink = $this->currentDocument->getFileLocation($secondFileGroupDownload);
341
                }
342
                break;
343
            }
344
        }
345
        if (
346
            empty($firstPageLink)
347
            && empty($secondPageLink)
348
        ) {
349
            $this->logger->warning('File not found in fileGrps "' . $this->extConf['files']['fileGrpDownload'] . '"');
350
        }
351
352
        if (!empty($firstPageLink)) {
353
            $pageLinkArray[0] = $firstPageLink;
354
        }
355
        if (!empty($secondPageLink)) {
356
            $pageLinkArray[1] = $secondPageLink;
357
        }
358
        return $pageLinkArray;
359
    }
360
361
    /**
362
     * Get work's download link
363
     *
364
     * @access private
365
     *
366
     * @return string Link to downloadable work
367
     */
368
    private function getWorkLink(): string
369
    {
370
        $workLink = '';
371
        $fileGrpsDownload = GeneralUtility::trimExplode(',', $this->extConf['files']['fileGrpDownload']);
372
        // Get work link.
373
        while ($fileGrpDownload = array_shift($fileGrpsDownload)) {
374
            $fileGroupDownload = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[0]]['files'][$fileGrpDownload];
375
            if (!empty($fileGroupDownload)) {
376
                $workLink = $this->currentDocument->getFileLocation($fileGroupDownload);
377
                break;
378
            } else {
379
                $details = $this->currentDocument->getLogicalStructure($this->currentDocument->toplevelId);
380
                if (!empty($details['files'][$fileGrpDownload])) {
381
                    $workLink = $this->currentDocument->getFileLocation($details['files'][$fileGrpDownload]);
382
                    break;
383
                }
384
            }
385
        }
386
        if (empty($workLink)) {
387
            $this->logger->warning('File not found in fileGrps "' . $this->extConf['files']['fileGrpDownload'] . '"');
388
        }
389
        return $workLink;
390
    }
391
392
    /**
393
     * Renders the searchInDocument tool (used in template)
394
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
395
     *
396
     * @access private
397
     *
398
     * @return void
399
     */
400
    private function renderSearchInDocumentTool(): void
401
    {
402
        if (
403
            $this->isDocMissingOrEmpty()
404
            || empty($this->extConf['files']['fileGrpFulltext'])
405
            || empty($this->settings['solrcore'])
406
        ) {
407
            // Quit without doing anything if required variables are not set.
408
            return;
409
        }
410
411
        $this->setPage();
412
413
        // Quit if no fulltext file is present
414
        if ($this->isFullTextEmpty()) {
415
            return;
416
        }
417
418
        // Fill markers.
419
        $viewArray = [
420
            'LABEL_QUERY_URL' => $this->settings['queryInputName'],
421
            'LABEL_START' => $this->settings['startInputName'],
422
            'LABEL_ID' => $this->settings['idInputName'],
423
            'LABEL_PID' => $this->settings['pidInputName'],
424
            'LABEL_PAGE_URL' => $this->settings['pageInputName'],
425
            'LABEL_HIGHLIGHT_WORD' => $this->settings['highlightWordInputName'],
426
            'LABEL_ENCRYPTED' => $this->settings['encryptedInputName'],
427
            'CURRENT_DOCUMENT' => $this->getCurrentDocumentId(),
428
            'SOLR_ENCRYPTED' => $this->getEncryptedCoreName() ? : ''
429
        ];
430
431
        $this->view->assign('searchInDocument', $viewArray);
432
    }
433
434
    /**
435
     * Get current document id. As default the uid will be used.
436
     * In case there is defined documentIdUrlSchema then the id will
437
     * extracted from this URL.
438
     *
439
     * @access private
440
     *
441
     * @return string with current document id
442
     */
443
    private function getCurrentDocumentId(): string
444
    {
445
        $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

445
        /** @scrutinizer ignore-call */ 
446
        $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...
446
447
        if ($id !== null && $id > 0) {
448
            // we found the document uid
449
            return (string) $id;
450
        } else {
451
            $id = $this->requestData['id'];
452
            if (!GeneralUtility::isValidUrl($id)) {
453
                // we found no valid URI --> something unexpected we cannot search within.
454
                return '';
455
            }
456
        }
457
458
        // example: https://host.de/items/*id*/record
459
        if (!empty($this->settings['documentIdUrlSchema'])) {
460
            $arr = explode('*', $this->settings['documentIdUrlSchema']);
461
462
            if (count($arr) == 2) {
463
                $id = explode($arr[0], $id)[0];
464
            } else if (count($arr) == 3) {
465
                $sub = substr($id, strpos($id, $arr[0]) + strlen($arr[0]), strlen($id));
466
                $id = substr($sub, 0, strpos($sub, $arr[2]));
467
            }
468
        }
469
        return $id;
470
    }
471
472
    /**
473
     * Get the encrypted Solr core name
474
     *
475
     * @access private
476
     *
477
     * @return string with encrypted core name
478
     */
479
    private function getEncryptedCoreName(): string
480
    {
481
        // Get core name.
482
        $name = Helper::getIndexNameFromUid($this->settings['solrcore'], 'tx_dlf_solrcores');
483
        // Encrypt core name.
484
        if (!empty($name)) {
485
            $name = Helper::encrypt($name);
486
        }
487
        return $name;
488
    }
489
490
    /**
491
     * Check if the full text is empty.
492
     *
493
     * @access private
494
     *
495
     * @return bool true if empty, false otherwise
496
     */
497
    private function isFullTextEmpty(): bool
498
    {
499
        $fileGrpsFulltext = GeneralUtility::trimExplode(',', $this->extConf['files']['fileGrpFulltext']);
500
        while ($fileGrpFulltext = array_shift($fileGrpsFulltext)) {
501
            $files = $this->currentDocument->physicalStructureInfo[$this->currentDocument->physicalStructure[$this->requestData['page']]]['files'];
502
            if (!empty($files[$fileGrpFulltext])) {
503
                return false;
504
            }
505
        }
506
        return true;
507
    }
508
}
509