Passed
Pull Request — master (#123)
by Sebastian
03:21
created

TableOfContentsController::makeMenuFor3DObjects()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
cc 3
eloc 6
nc 3
nop 0
dl 0
loc 12
rs 10
c 5
b 1
f 0
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\Helper;
15
use Kitodo\Dlf\Common\MetsDocument;
16
use TYPO3\CMS\Core\Utility\MathUtility;
17
use TYPO3\CMS\Core\Utility\GeneralUtility;
18
19
/**
20
 * Controller class for plugin 'Table Of Contents'.
21
 *
22
 * @author Sebastian Meyer <[email protected]>
23
 * @package TYPO3
24
 * @subpackage dlf
25
 * @access public
26
 */
27
class TableOfContentsController extends AbstractController
28
{
29
    /**
30
     * This holds the active entries according to the currently selected page
31
     *
32
     * @var array
33
     * @access protected
34
     */
35
    protected $activeEntries = [];
36
37
    /**
38
     * @var array $this->filterParams: The current filter parameter
39
     * @access protected
40
     */
41
    protected $filterParams;
42
43
    /**
44
     * Filter Action
45
     *
46
     * @return void
47
     */
48
    public function filterAction()
49
    {
50
        // if filter was triggered, get filter parameters from POST variables
51
        $this->filterParams = $this->getParametersSafely('filterParameter');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getParametersSafely('filterParameter') can also be of type string. However, the property $filterParams is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
52
53
        // output is done by main action
54
        $this->forward('main', null, null, ['filterParameter' => $this->filterParams]);
55
    }
56
57
    /**
58
     * The main method of the plugin
59
     *
60
     * @return void
61
     */
62
    public function mainAction()
63
    {
64
        // Load current document.
65
        $this->loadDocument($this->requestData);
66
        if (
67
            $this->document === null
68
            || $this->document->getDoc() === null
69
        ) {
70
            // Quit without doing anything if required variables are not set.
71
            return;
72
        } else {
73
            if (!empty($this->requestData['logicalPage'])) {
74
                $this->requestData['page'] = $this->document->getDoc()->getPhysicalPage($this->requestData['logicalPage']);
75
                // The logical page parameter should not appear again
76
                unset($this->requestData['logicalPage']);
77
            }
78
            if ($this->document->getDoc()->tableOfContents[0]['type'] == 'collection') {
79
                $this->view->assign('type', 'collection');
80
                $this->view->assign('toc', $this->makeMenuFor3DObjects());
81
            } else {
82
                $this->view->assign('type', 'other');
83
                $this->view->assign('toc', $this->makeMenuArray());
84
            }
85
        }
86
    }
87
88
    /**
89
     * This builds a menu array for HMENU
90
     *
91
     * @access protected
92
     * @return array HMENU array
93
     */
94
    protected function makeMenuArray()
95
    {
96
        // Set default values for page if not set.
97
        // $this->requestData['page'] may be integer or string (physical structure @ID)
98
        if (
99
            (int) $this->requestData['page'] > 0
100
            || empty($this->requestData['page'])
101
        ) {
102
            $this->requestData['page'] = MathUtility::forceIntegerInRange((int) $this->requestData['page'], 1, $this->document->getDoc()->numPages, 1);
103
        } else {
104
            $this->requestData['page'] = array_search($this->requestData['page'], $this->document->getDoc()->physicalStructure);
105
        }
106
        $this->requestData['double'] = MathUtility::forceIntegerInRange($this->requestData['double'], 0, 1, 0);
107
        $menuArray = [];
108
        // Does the document have physical elements or is it an external file?
109
        if (
110
            !empty($this->document->getDoc()->physicalStructure)
111
            || !MathUtility::canBeInterpretedAsInteger($this->requestData['id'])
112
        ) {
113
            // Get all logical units the current page or track is a part of.
114
            if (
115
                !empty($this->requestData['page'])
116
                && !empty($this->document->getDoc()->physicalStructure)
117
            ) {
118
                $this->activeEntries = array_merge((array) $this->document->getDoc()->smLinks['p2l'][$this->document->getDoc()->physicalStructure[0]],
119
                    (array) $this->document->getDoc()->smLinks['p2l'][$this->document->getDoc()->physicalStructure[$this->requestData['page']]]);
120
                if (
121
                    !empty($this->requestData['double'])
122
                    && $this->requestData['page'] < $this->document->getDoc()->numPages
123
                ) {
124
                    $this->activeEntries = array_merge($this->activeEntries,
125
                        (array) $this->document->getDoc()->smLinks['p2l'][$this->document->getDoc()->physicalStructure[$this->requestData['page'] + 1]]);
126
                }
127
            }
128
            // Go through table of contents and create all menu entries.
129
            foreach ($this->document->getDoc()->tableOfContents as $entry) {
130
                $menuArray[] = $this->getMenuEntry($entry, true);
131
            }
132
        } else {
133
            // Go through table of contents and create top-level menu entries.
134
            foreach ($this->document->getDoc()->tableOfContents as $entry) {
135
                $menuArray[] = $this->getMenuEntry($entry, false);
136
            }
137
            // Build table of contents from database.
138
            $result = $this->documentRepository->getTableOfContentsFromDb($this->document->getUid(), $this->document->getPid(), $this->settings);
139
140
            $allResults = $result->fetchAll();
0 ignored issues
show
Bug introduced by
The method fetchAll() does not exist on TYPO3\CMS\Extbase\Persistence\QueryResultInterface. ( Ignorable by Annotation )

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

140
            /** @scrutinizer ignore-call */ 
141
            $allResults = $result->fetchAll();

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...
141
142
            if (count($allResults) > 0) {
143
                $menuArray[0]['ITEM_STATE'] = 'CURIFSUB';
144
                $menuArray[0]['_SUB_MENU'] = [];
145
                foreach ($allResults as $resArray) {
146
                    $entry = [
147
                        'label' => !empty($resArray['mets_label']) ? $resArray['mets_label'] : $resArray['title'],
148
                        'type' => $resArray['type'],
149
                        'volume' => $resArray['volume'],
150
                        'orderlabel' => $resArray['mets_orderlabel'],
151
                        'pagination' => '',
152
                        'targetUid' => $resArray['uid']
153
                    ];
154
                    $menuArray[0]['_SUB_MENU'][] = $this->getMenuEntry($entry, false);
155
                }
156
            }
157
        }
158
        return $menuArray;
159
    }
160
161
    /**
162
     * This builds a menu for list of 3D objects
163
     *
164
     * @access protected
165
     *
166
     * @param string $content: The PlugIn content
167
     * @param array $conf: The PlugIn configuration
168
     *
169
     * @return array HMENU array
170
     */
171
    protected function makeMenuFor3DObjects()
172
    {
173
        $menuArray = [];
174
175
        // Go through table of contents and create all menu entries.
176
        foreach ($this->document->getDoc()->tableOfContents as $entry) {
177
            $menuEntry = $this->getMenuEntryWithImage($entry, true);
178
            if (!empty($menuEntry)) {
179
                $menuArray[] = $menuEntry;
180
            }
181
        }
182
        return $menuArray;
183
    }
184
185
    /**
186
     * This builds an array for one menu entry
187
     *
188
     * @access protected
189
     *
190
     * @param array $entry : The entry's array from \Kitodo\Dlf\Common\Doc->getLogicalStructure
191
     * @param bool $recursive : Whether to include the child entries
192
     *
193
     * @return array HMENU array for menu entry
194
     */
195
    protected function getMenuEntry(array $entry, $recursive = false)
196
    {
197
        $entry = $this->resolveMenuEntry($entry);
198
199
        $entryArray = [];
200
        // Set "title", "volume", "type" and "pagination" from $entry array.
201
        $entryArray['title'] = !empty($entry['label']) ? $entry['label'] : $entry['orderlabel'];
202
        $entryArray['volume'] = $entry['volume'];
203
        $entryArray['orderlabel'] = $entry['orderlabel'];
204
        $entryArray['type'] = Helper::translate($entry['type'], 'tx_dlf_structures', $this->settings['storagePid']);
205
        $entryArray['pagination'] = htmlspecialchars($entry['pagination']);
206
        $entryArray['_OVERRIDE_HREF'] = '';
207
        $entryArray['doNotLinkIt'] = 1;
208
        $entryArray['ITEM_STATE'] = 'NO';
209
        // Build menu links based on the $entry['points'] array.
210
        if (
211
            !empty($entry['points'])
212
            && MathUtility::canBeInterpretedAsInteger($entry['points'])
213
        ) {
214
            $entryArray['page'] = $entry['points'];
215
216
            $entryArray['doNotLinkIt'] = 0;
217
            if ($this->settings['basketButton']) {
218
                $entryArray['basketButton'] = [
219
                    'logId' => $entry['id'],
220
                    'startpage' => $entry['points']
221
                ];
222
            }
223
        } elseif (
224
            !empty($entry['points'])
225
            && is_string($entry['points'])
226
        ) {
227
            $entryArray['id'] = $entry['points'];
228
            $entryArray['page'] = 1;
229
            $entryArray['doNotLinkIt'] = 0;
230
            if ($this->settings['basketButton']) {
231
                $entryArray['basketButton'] = [
232
                    'logId' => $entry['id'],
233
                    'startpage' => $entry['points']
234
                ];
235
            }
236
        } elseif (!empty($entry['targetUid'])) {
237
            $entryArray['id'] = $entry['targetUid'];
238
            $entryArray['page'] = 1;
239
            $entryArray['doNotLinkIt'] = 0;
240
            if ($this->settings['basketButton']) {
241
                $entryArray['basketButton'] = [
242
                    'logId' => $entry['id'],
243
                    'startpage' => $entry['targetUid']
244
                ];
245
            }
246
        }
247
        // Set "ITEM_STATE" to "CUR" if this entry points to current page.
248
        if (in_array($entry['id'], $this->activeEntries)) {
249
            $entryArray['ITEM_STATE'] = 'CUR';
250
        }
251
        // Build sub-menu if available and called recursively.
252
        if (
253
            $recursive === true
254
            && !empty($entry['children'])
255
        ) {
256
            // Build sub-menu only if one of the following conditions apply:
257
            // 1. Current menu node is in rootline
258
            // 2. Current menu node points to another file
259
            // 3. Current menu node has no corresponding images
260
            if (
261
                $entryArray['ITEM_STATE'] == 'CUR'
262
                || is_string($entry['points'])
263
                || empty($this->document->getDoc()->smLinks['l2p'][$entry['id']])
264
            ) {
265
                $entryArray['_SUB_MENU'] = [];
266
                foreach ($entry['children'] as $child) {
267
                    // Set "ITEM_STATE" to "ACT" if this entry points to current page and has sub-entries pointing to the same page.
268
                    if (in_array($child['id'], $this->activeEntries)) {
269
                        $entryArray['ITEM_STATE'] = 'ACT';
270
                    }
271
                    $entryArray['_SUB_MENU'][] = $this->getMenuEntry($child, true);
272
                }
273
            }
274
            // Append "IFSUB" to "ITEM_STATE" if this entry has sub-entries.
275
            $entryArray['ITEM_STATE'] = ($entryArray['ITEM_STATE'] == 'NO' ? 'IFSUB' : $entryArray['ITEM_STATE'] . 'IFSUB');
276
        }
277
        return $entryArray;
278
    }
279
280
    /**
281
     * If $entry references an external METS file (as mptr),
282
     * try to resolve its database UID and return an updated $entry.
283
     *
284
     * This is so that when linking from a child document back to its parent,
285
     * that link is via UID, so that subsequently the parent's TOC is built from database.
286
     *
287
     * @param array $entry
288
     * @return array
289
     */
290
    protected function resolveMenuEntry($entry)
291
    {
292
        // If the menu entry points to the parent document,
293
        // resolve to the parent UID set on indexation.
294
        $doc = $this->document->getDoc();
295
        if (
296
            $doc instanceof MetsDocument
297
            && $entry['points'] === $doc->parentHref
298
            && !empty($this->document->getPartof())
299
        ) {
300
            unset($entry['points']);
301
            $entry['targetUid'] = $this->document->getPartof();
302
        }
303
304
        return $entry;
305
    }
306
307
    protected function getMenuEntryWithImage(array $entry, $recursive = false)
308
    {
309
        $entryArray = [];
310
311
        // don't filter if the entry type is collection or search params are empty
312
        if ($entry['type'] !== 'collection' && is_array($this->filterParams) && !empty($this->filterParams)) {
313
            // currently only title filtering is defined
314
            // TODO: add more logic here after another fields are defined
315
            if (!str_contains($entry['label'], $this->filterParams[0])) {
316
                return $entryArray;
317
            }
318
        }
319
320
        // Set "title", "volume", "type" and "pagination" from $entry array.
321
        $entryArray['title'] = !empty($entry['label']) ? $entry['label'] : $entry['orderlabel'];
322
        $entryArray['orderlabel'] = $entry['orderlabel'];
323
        $entryArray['type'] = Helper::translate($entry['type'], 'tx_dlf_structures', $this->settings['storagePid']);
324
        $entryArray['pagination'] = htmlspecialchars($entry['pagination']);
325
        $entryArray['doNotLinkIt'] = 1;
326
        $entryArray['ITEM_STATE'] = 'HEADER';
327
328
        if ($entry['children'] === null) {
329
            $entryArray['description'] = $entry['description'];
330
            $id = $this->document->getDoc()->smLinks['l2p'][$entry['id']][0];
331
            $entryArray['image'] = $this->document->getDoc()->getFileLocation($this->document->getDoc()->physicalStructureInfo[$id]['files']['THUMBS']);
332
            $entryArray['doNotLinkIt'] = 0;
333
            // index.php?tx_dlf%5Bid%5D=http%3A%2F%2Flink_to_METS_file.xml
334
            $entryArray['urlId'] = GeneralUtility::_GET('id');
335
            $entryArray['urlXml'] = $entry['points'];
336
            $entryArray['ITEM_STATE'] = 'ITEM';
337
        }
338
339
        // Build sub-menu if available and called recursively.
340
        if (
341
            $recursive == true
342
            && !empty($entry['children'])
343
        ) {
344
            // Build sub-menu only if one of the following conditions apply:
345
            // 1. Current menu node points to another file
346
            // 2. Current menu node has no corresponding images
347
            if (
348
                is_string($entry['points'])
349
                || empty($this->document->getDoc()->smLinks['l2p'][$entry['id']])
350
            ) {
351
                $entryArray['_SUB_MENU'] = [];
352
                foreach ($entry['children'] as $child) {
353
                    $entryArray['_SUB_MENU'][] = $this->getMenuEntryWithImage($child);
354
                }
355
            }
356
        }
357
        return $entryArray;
358
    }
359
}
360