Passed
Push — testing/dev-master ( 8973ee...2d4718 )
by Tomas Norre
15:27
created

PageRepository::getSubpagesForPages()   B

Complexity

Conditions 8
Paths 24

Size

Total Lines 65
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 34
c 1
b 0
f 0
nc 24
nop 6
dl 0
loc 65
rs 8.1315

How to fix   Long Method   

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
declare(strict_types=1);
4
5
namespace AOE\Crawler\Domain\Repository;
6
7
/*
8
 * (c) 2020 AOE GmbH <[email protected]>
9
 *
10
 * This file is part of the TYPO3 Crawler Extension.
11
 *
12
 * It is free software; you can redistribute it and/or modify it under
13
 * the terms of the GNU General Public License, either version 2
14
 * of the License, or any later version.
15
 *
16
 * For the full copyright and license information, please read the
17
 * LICENSE.txt file that was distributed with this source code.
18
 *
19
 * The TYPO3 project - inspiring people to share!
20
 */
21
22
use Psr\Log\LoggerAwareInterface;
23
use Psr\Log\LoggerAwareTrait;
24
use TYPO3\CMS\Core\Cache\CacheManager;
25
use TYPO3\CMS\Core\Cache\Frontend\VariableFrontend;
26
use TYPO3\CMS\Core\Context\Context;
27
use TYPO3\CMS\Core\Database\ConnectionPool;
28
use TYPO3\CMS\Core\Database\Query\QueryHelper;
29
use TYPO3\CMS\Core\Utility\GeneralUtility;
30
use TYPO3\CMS\Core\Versioning\VersionState;
31
32
/**
33
 * This is partly a copy from the TYPO3 Core PageRepository, so keep support for
34
 * 9 LTS, 10LTS and 11.0+. This can be dropped in favor of the Core PageRepository,
35
 * when support for TYPO3 9LTS is dropped.
36
 * @codeCoverageIgnore
37
 * @internal Will be removed without any warning
38
 */
39
final class PageRepository implements LoggerAwareInterface
40
{
41
    use LoggerAwareTrait;
42
43
    /**
44
     * This is not the final clauses. There will normally be conditions for the
45
     * hidden, starttime and endtime fields as well. You MUST initialize the object
46
     * by the init() function
47
     *
48
     * @var string
49
     */
50
    public $where_hid_del = ' AND pages.deleted=0';
51
52
    /**
53
     * Clause for fe_group access
54
     *
55
     * @var string
56
     */
57
    public $where_groupAccess = '';
58
59
    /**
60
     * Can be migrated away later to use context API directly.
61
     *
62
     * @var int
63
     */
64
    protected $sys_language_uid = 0;
65
66
    /**
67
     * Can be migrated away later to use context API directly.
68
     * Workspace ID for preview
69
     * If > 0, versioning preview of other record versions is allowed. THIS MUST
70
     * ONLY BE SET IF the page is not cached and truly previewed by a backend
71
     * user!
72
     *
73
     * @var int
74
     */
75
    protected $versioningWorkspaceId = 0;
76
77
    /**
78
     * Computed properties that are added to database rows.
79
     *
80
     * @var array
81
     */
82
    protected $computedPropertyNames = [
83
        '_LOCALIZED_UID',
84
        '_MP_PARAM',
85
        '_ORIG_uid',
86
        '_ORIG_pid',
87
        '_PAGES_OVERLAY',
88
        '_PAGES_OVERLAY_UID',
89
        '_PAGES_OVERLAY_LANGUAGE',
90
        '_PAGES_OVERLAY_REQUESTEDLANGUAGE',
91
    ];
92
93
    /**
94
     * Named constants for "magic numbers" of the field doktype
95
     */
96
    const DOKTYPE_DEFAULT = 1;
97
    const DOKTYPE_LINK = 3;
98
    const DOKTYPE_SHORTCUT = 4;
99
    const DOKTYPE_BE_USER_SECTION = 6;
100
    const DOKTYPE_MOUNTPOINT = 7;
101
    const DOKTYPE_SPACER = 199;
102
    const DOKTYPE_SYSFOLDER = 254;
103
    const DOKTYPE_RECYCLER = 255;
104
105
    /**
106
     * Named constants for "magic numbers" of the field shortcut_mode
107
     */
108
    const SHORTCUT_MODE_NONE = 0;
109
    const SHORTCUT_MODE_FIRST_SUBPAGE = 1;
110
    const SHORTCUT_MODE_RANDOM_SUBPAGE = 2;
111
    const SHORTCUT_MODE_PARENT_PAGE = 3;
112
113
    /**
114
     * @var Context
115
     */
116
    protected $context;
117
118
    /**
119
     * PageRepository constructor to set the base context, this will effectively remove the necessity for
120
     * setting properties from the outside.
121
     *
122
     * @param Context $context
123
     */
124
    public function __construct(Context $context = null)
125
    {
126
        $this->context = $context ?? GeneralUtility::makeInstance(Context::class);
127
        $this->versioningWorkspaceId = $this->context->getPropertyFromAspect('workspace', 'id');
128
        // Only set up the where clauses for pages when TCA is set. This usually happens only in tests.
129
        // Once all tests are written very well, this can be removed again
130
        if (isset($GLOBALS['TCA']['pages'])) {
131
            $this->init($this->context->getPropertyFromAspect('visibility', 'includeHiddenPages'));
132
            $this->where_groupAccess = $this->getMultipleGroupsWhereClause('pages.fe_group', 'pages');
133
            $this->sys_language_uid = (int)$this->context->getPropertyFromAspect('language', 'id', 0);
134
        }
135
    }
136
137
    /**
138
     * init() MUST be run directly after creating a new template-object
139
     * This sets the internal variable $this->where_hid_del to the correct where
140
     * clause for page records taking deleted/hidden/starttime/endtime/t3ver_state
141
     * into account
142
     *
143
     * @param bool $show_hidden If $show_hidden is TRUE, the hidden-field is ignored!! Normally this should be FALSE. Is used for previewing.
144
     * @internal
145
     */
146
    protected function init($show_hidden)
147
    {
148
        $this->where_groupAccess = '';
149
        // As PageRepository may be used multiple times during the frontend request, and may
150
        // actually be used before the usergroups have been resolved, self::getMultipleGroupsWhereClause()
151
        // and the hook in ->enableFields() need to be reconsidered when the usergroup state changes.
152
        // When something changes in the context, a second runtime cache entry is built.
153
        // However, the PageRepository is generally in use for generating e.g. hundreds of links, so they would all use
154
        // the same cache identifier.
155
        $userAspect = $this->context->getAspect('frontend.user');
156
        $frontendUserIdentifier = 'user_' . (int)$userAspect->get('id') . '_groups_' . md5(implode(',', $userAspect->getGroupIds()));
0 ignored issues
show
Bug introduced by
The method getGroupIds() does not exist on TYPO3\CMS\Core\Context\AspectInterface. It seems like you code against a sub-type of TYPO3\CMS\Core\Context\AspectInterface such as TYPO3\CMS\Core\Context\UserAspect. ( Ignorable by Annotation )

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

156
        $frontendUserIdentifier = 'user_' . (int)$userAspect->get('id') . '_groups_' . md5(implode(',', $userAspect->/** @scrutinizer ignore-call */ getGroupIds()));
Loading history...
157
158
        $cache = $this->getRuntimeCache();
159
        $cacheIdentifier = 'PageRepository_hidDelWhere' . ($show_hidden ? 'ShowHidden' : '') . '_' . (int)$this->versioningWorkspaceId . '_' . $frontendUserIdentifier;
160
        $cacheEntry = $cache->get($cacheIdentifier);
161
        if ($cacheEntry) {
162
            $this->where_hid_del = $cacheEntry;
163
        } else {
164
            $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
165
                ->getQueryBuilderForTable('pages')
166
                ->expr();
167
            if ($this->versioningWorkspaceId > 0) {
168
                // For version previewing, make sure that enable-fields are not
169
                // de-selecting hidden pages - we need versionOL() to unset them only
170
                // if the overlay record instructs us to.
171
                // Clear where_hid_del and restrict to live and current workspaces
172
                $this->where_hid_del = ' AND ' . $expressionBuilder->andX(
173
                        $expressionBuilder->eq('pages.deleted', 0),
174
                        $expressionBuilder->orX(
175
                            $expressionBuilder->eq('pages.t3ver_wsid', 0),
176
                            $expressionBuilder->eq('pages.t3ver_wsid', (int)$this->versioningWorkspaceId)
177
                        ),
178
                        $expressionBuilder->neq('pages.doktype', self::DOKTYPE_RECYCLER)
179
                    );
180
            } else {
181
                // add starttime / endtime, and check for hidden/deleted
182
                // Filter out new/deleted place-holder pages in case we are NOT in a
183
                // versioning preview (that means we are online!)
184
                $this->where_hid_del = ' AND ' . (string)$expressionBuilder->andX(
185
                        QueryHelper::stripLogicalOperatorPrefix(
186
                            $this->enableFields('pages', (int)$show_hidden, ['fe_group' => true])
187
                        ),
188
                        $expressionBuilder->neq('pages.doktype', self::DOKTYPE_RECYCLER)
189
                    );
190
            }
191
            $cache->set($cacheIdentifier, $this->where_hid_del);
192
        }
193
194
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['init'] ?? false)) {
195
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['init'] as $classRef) {
196
                $hookObject = GeneralUtility::makeInstance($classRef);
197
                if (!$hookObject instanceof PageRepositoryInitHookInterface) {
0 ignored issues
show
Bug introduced by
The type AOE\Crawler\Domain\Repos...sitoryInitHookInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
198
                    throw new \UnexpectedValueException($classRef . ' must implement interface ' . PageRepositoryInitHookInterface::class, 1379579812);
199
                }
200
                $hookObject->init_postProcess($this);
201
            }
202
        }
203
    }
204
205
    /**************************
206
     *
207
     * Selecting page records
208
     *
209
     **************************/
210
211
    /**
212
     * Loads the full page record for the given page ID.
213
     *
214
     * The page record is either served from a first-level cache or loaded from the
215
     * database. If no page can be found, an empty array is returned.
216
     *
217
     * Language overlay and versioning overlay are applied. Mount Point
218
     * handling is not done, an overlaid Mount Point is not replaced.
219
     *
220
     * The result is conditioned by the public properties where_groupAccess
221
     * and where_hid_del that are preset by the init() method.
222
     *
223
     * @see PageRepository::where_groupAccess
224
     * @see PageRepository::where_hid_del
225
     *
226
     * By default the usergroup access check is enabled. Use the second method argument
227
     * to disable the usergroup access check.
228
     *
229
     * The given UID can be preprocessed by registering a hook class that is
230
     * implementing the PageRepositoryGetPageHookInterface into the configuration array
231
     * $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPage'].
232
     *
233
     * @param int $uid The page id to look up
234
     * @param bool $disableGroupAccessCheck set to true to disable group access check
235
     * @return array The resulting page record with overlays or empty array
236
     * @throws \UnexpectedValueException
237
     * @see PageRepository::getPage_noCheck()
238
     */
239
    public function getPage($uid, $disableGroupAccessCheck = false)
240
    {
241
        // Hook to manipulate the page uid for special overlay handling
242
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPage'] ?? [] as $className) {
243
            $hookObject = GeneralUtility::makeInstance($className);
244
            if (!$hookObject instanceof PageRepositoryGetPageHookInterface) {
245
                throw new \UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetPageHookInterface::class, 1251476766);
246
            }
247
            $hookObject->getPage_preProcess($uid, $disableGroupAccessCheck, $this);
248
        }
249
        $cacheIdentifier = 'PageRepository_getPage_' . md5(
250
                implode(
251
                    '-',
252
                    [
253
                        $uid,
254
                        $disableGroupAccessCheck ? '' : $this->where_groupAccess,
255
                        $this->where_hid_del,
256
                        $this->sys_language_uid
257
                    ]
258
                )
259
            );
260
        $cache = $this->getRuntimeCache();
261
        $cacheEntry = $cache->get($cacheIdentifier);
262
        if (is_array($cacheEntry)) {
263
            return $cacheEntry;
264
        }
265
        $result = [];
266
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
267
        $queryBuilder->getRestrictions()->removeAll();
268
        $queryBuilder->select('*')
269
            ->from('pages')
270
            ->where(
271
                $queryBuilder->expr()->eq('uid', (int)$uid),
272
                QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del)
273
            );
274
275
        $originalWhereGroupAccess = '';
276
        if (!$disableGroupAccessCheck) {
277
            $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess));
278
        } else {
279
            $originalWhereGroupAccess = $this->where_groupAccess;
280
            $this->where_groupAccess = '';
281
        }
282
283
        $row = $queryBuilder->execute()->fetch();
284
        if ($row) {
285
            $this->versionOL('pages', $row);
286
            if (is_array($row)) {
287
                $result = $this->getPageOverlay($row);
288
            }
289
        }
290
291
        if ($disableGroupAccessCheck) {
292
            $this->where_groupAccess = $originalWhereGroupAccess;
293
        }
294
295
        $cache->set($cacheIdentifier, $result);
296
        return $result;
297
    }
298
299
    /**
300
     * Return the $row for the page with uid = $uid WITHOUT checking for
301
     * ->where_hid_del (start- and endtime or hidden). Only "deleted" is checked!
302
     *
303
     * @param int $uid The page id to look up
304
     * @return array The page row with overlaid localized fields. Empty array if no page.
305
     * @see getPage()
306
     */
307
    private function getPage_noCheck($uid)
0 ignored issues
show
Unused Code introduced by
The method getPage_noCheck() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
308
    {
309
        $cache = $this->getRuntimeCache();
310
        $cacheIdentifier = 'PageRepository_getPage_noCheck_' . $uid . '_' . $this->sys_language_uid . '_' . $this->versioningWorkspaceId;
311
        $cacheEntry = $cache->get($cacheIdentifier);
312
        if ($cacheEntry !== false) {
313
            return $cacheEntry;
314
        }
315
316
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
317
        $queryBuilder->getRestrictions()
318
            ->removeAll()
319
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
0 ignored issues
show
Bug introduced by
The type AOE\Crawler\Domain\Repository\DeletedRestriction was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
320
        $row = $queryBuilder->select('*')
321
            ->from('pages')
322
            ->where($queryBuilder->expr()->eq('uid', (int)$uid))
323
            ->execute()
324
            ->fetch();
325
326
        $result = [];
327
        if ($row) {
328
            $this->versionOL('pages', $row);
329
            if (is_array($row)) {
330
                $result = $this->getPageOverlay($row);
331
            }
332
        }
333
        $cache->set($cacheIdentifier, $result);
334
        return $result;
335
    }
336
337
    /**
338
     * Returns the relevant page overlay record fields
339
     *
340
     * @param mixed $pageInput If $pageInput is an integer, it's the pid of the pageOverlay record and thus the page overlay record is returned. If $pageInput is an array, it's a page-record and based on this page record the language record is found and OVERLAID before the page record is returned.
341
     * @param int $languageUid Language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
342
     * @throws \UnexpectedValueException
343
     * @return array Page row which is overlaid with language_overlay record (or the overlay record alone)
344
     */
345
    private function getPageOverlay($pageInput, $languageUid = null)
346
    {
347
        $rows = $this->getPagesOverlay([$pageInput], $languageUid);
348
        // Always an array in return
349
        return $rows[0] ?? [];
350
    }
351
352
    /**
353
     * Returns the relevant page overlay record fields
354
     *
355
     * @param array $pagesInput Array of integers or array of arrays. If each value is an integer, it's the pids of the pageOverlay records and thus the page overlay records are returned. If each value is an array, it's page-records and based on this page records the language records are found and OVERLAID before the page records are returned.
356
     * @param int $languageUid Language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
357
     * @throws \UnexpectedValueException
358
     * @return array Page rows which are overlaid with language_overlay record.
359
     *               If the input was an array of integers, missing records are not
360
     *               included. If the input were page rows, untranslated pages
361
     *               are returned.
362
     */
363
    private function getPagesOverlay(array $pagesInput, $languageUid = null)
364
    {
365
        if (empty($pagesInput)) {
366
            return [];
367
        }
368
        if ($languageUid === null) {
369
            $languageUid = $this->sys_language_uid;
370
        }
371
        foreach ($pagesInput as &$origPage) {
372
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPageOverlay'] ?? [] as $className) {
373
                $hookObject = GeneralUtility::makeInstance($className);
374
                if (!$hookObject instanceof PageRepositoryGetPageOverlayHookInterface) {
0 ignored issues
show
Bug introduced by
The type AOE\Crawler\Domain\Repos...ageOverlayHookInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
375
                    throw new \UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetPageOverlayHookInterface::class, 1269878881);
376
                }
377
                $hookObject->getPageOverlay_preProcess($origPage, $languageUid, $this);
378
            }
379
        }
380
        unset($origPage);
381
382
        $overlays = [];
383
        // If language UID is different from zero, do overlay:
384
        if ($languageUid) {
385
            $languageUids = array_merge([$languageUid], $this->getLanguageFallbackChain(null));
386
387
            $pageIds = [];
388
            foreach ($pagesInput as $origPage) {
389
                if (is_array($origPage)) {
390
                    // Was the whole record
391
                    $pageIds[] = (int)$origPage['uid'];
392
                } else {
393
                    // Was the id
394
                    $pageIds[] = (int)$origPage;
395
                }
396
            }
397
            $overlays = $this->getPageOverlaysForLanguageUids($pageIds, $languageUids);
398
        }
399
400
        // Create output:
401
        $pagesOutput = [];
402
        foreach ($pagesInput as $key => $origPage) {
403
            if (is_array($origPage)) {
404
                $pagesOutput[$key] = $origPage;
405
                if (isset($overlays[$origPage['uid']])) {
406
                    // Overwrite the original field with the overlay
407
                    foreach ($overlays[$origPage['uid']] as $fieldName => $fieldValue) {
408
                        if ($fieldName !== 'uid' && $fieldName !== 'pid') {
409
                            $pagesOutput[$key][$fieldName] = $fieldValue;
410
                        }
411
                    }
412
                }
413
            } else {
414
                if (isset($overlays[$origPage])) {
415
                    $pagesOutput[$key] = $overlays[$origPage];
416
                }
417
            }
418
        }
419
        return $pagesOutput;
420
    }
421
422
    /**
423
     * Returns the cleaned fallback chain from the current language aspect, if there is one.
424
     *
425
     * @param LanguageAspect|null $languageAspect
426
     * @return int[]
427
     */
428
    private function getLanguageFallbackChain(?LanguageAspect $languageAspect): array
0 ignored issues
show
Bug introduced by
The type AOE\Crawler\Domain\Repository\LanguageAspect was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
429
    {
430
        $languageAspect = $languageAspect ?? $this->context->getAspect('language');
431
        return array_filter($languageAspect->getFallbackChain(), function ($item) {
0 ignored issues
show
Bug introduced by
The method getFallbackChain() does not exist on TYPO3\CMS\Core\Context\AspectInterface. It seems like you code against a sub-type of TYPO3\CMS\Core\Context\AspectInterface such as TYPO3\CMS\Core\Context\LanguageAspect. ( Ignorable by Annotation )

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

431
        return array_filter($languageAspect->/** @scrutinizer ignore-call */ getFallbackChain(), function ($item) {
Loading history...
432
            return MathUtility::canBeInterpretedAsInteger($item);
0 ignored issues
show
Bug introduced by
The type AOE\Crawler\Domain\Repository\MathUtility was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
433
        });
434
    }
435
436
    /**
437
     * Returns the first match of overlays for pages in the passed languages.
438
     *
439
     * NOTE regarding the query restrictions:
440
     * Currently the visibility aspect within the FrontendRestrictionContainer will allow
441
     * page translation records to be selected as they are child-records of a page.
442
     * However you may argue that the visibility flag should determine this.
443
     * But that's not how it's done right now.
444
     *
445
     * @param array $pageUids
446
     * @param array $languageUids uid of sys_language, please note that the order is important here.
447
     * @return array
448
     */
449
    private function getPageOverlaysForLanguageUids(array $pageUids, array $languageUids): array
450
    {
451
        // Remove default language ("0")
452
        $languageUids = array_filter($languageUids);
453
        $languageField = $GLOBALS['TCA']['pages']['ctrl']['languageField'];
454
        $overlays = [];
455
456
        foreach ($pageUids as $pageId) {
457
            // Create a map based on the order of values in $languageUids. Those entries reflect the order of the language + fallback chain.
458
            // We can't work with database ordering since there is no common SQL clause to order by e.g. [7, 1, 2].
459
            $orderedListByLanguages = array_flip($languageUids);
460
461
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
462
            $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class, $this->context));
0 ignored issues
show
Bug introduced by
The type AOE\Crawler\Domain\Repos...endRestrictionContainer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
463
            // Because "fe_group" is an exclude field, so it is synced between overlays, the group restriction is removed for language overlays of pages
464
            $queryBuilder->getRestrictions()->removeByType(FrontendGroupRestriction::class);
0 ignored issues
show
Bug introduced by
The type AOE\Crawler\Domain\Repos...rontendGroupRestriction was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
465
            $result = $queryBuilder->select('*')
466
                ->from('pages')
467
                ->where(
468
                    $queryBuilder->expr()->eq(
469
                        $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'],
470
                        $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT)
471
                    ),
472
                    $queryBuilder->expr()->in(
473
                        $GLOBALS['TCA']['pages']['ctrl']['languageField'],
474
                        $queryBuilder->createNamedParameter($languageUids, Connection::PARAM_INT_ARRAY)
0 ignored issues
show
Bug introduced by
The type AOE\Crawler\Domain\Repository\Connection was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
475
                    )
476
                )
477
                ->execute();
478
479
            // Create a list of rows ordered by values in $languageUids
480
            while ($row = $result->fetch()) {
481
                $orderedListByLanguages[$row[$languageField]] = $row;
482
            }
483
484
            foreach ($orderedListByLanguages as $languageUid => $row) {
485
                if (!is_array($row)) {
486
                    continue;
487
                }
488
489
                // Found a result for the current language id
490
                $this->versionOL('pages', $row);
491
                if (is_array($row)) {
492
                    $row['_PAGES_OVERLAY'] = true;
493
                    $row['_PAGES_OVERLAY_UID'] = $row['uid'];
494
                    $row['_PAGES_OVERLAY_LANGUAGE'] = $languageUid;
495
                    $row['_PAGES_OVERLAY_REQUESTEDLANGUAGE'] = $languageUids[0];
496
                    // Unset vital fields that are NOT allowed to be overlaid:
497
                    unset($row['uid'], $row['pid']);
498
                    $overlays[$pageId] = $row;
499
500
                    // Language fallback found, stop querying further languages
501
                    break;
502
                }
503
            }
504
        }
505
506
        return $overlays;
507
    }
508
509
    /**
510
     * Creates language-overlay for records in general (where translation is found
511
     * in records from the same table)
512
     *
513
     * @param string $table Table name
514
     * @param array $row Record to overlay. Must contain uid, pid and $table]['ctrl']['languageField']
515
     * @param int $sys_language_content Pointer to the sys_language uid for content on the site.
516
     * @param string $OLmode Overlay mode. If "hideNonTranslated" then records without translation will not be returned  un-translated but unset (and return value is NULL)
517
     * @throws \UnexpectedValueException
518
     * @return mixed Returns the input record, possibly overlaid with a translation.  But if $OLmode is "hideNonTranslated" then it will return NULL if no translation is found.
519
     */
520
    private function getRecordOverlay($table, $row, $sys_language_content, $OLmode = '')
0 ignored issues
show
Unused Code introduced by
The method getRecordOverlay() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
521
    {
522
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'] ?? [] as $className) {
523
            $hookObject = GeneralUtility::makeInstance($className);
524
            if (!$hookObject instanceof PageRepositoryGetRecordOverlayHookInterface) {
0 ignored issues
show
Bug introduced by
The type AOE\Crawler\Domain\Repos...ordOverlayHookInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
525
                throw new \UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetRecordOverlayHookInterface::class, 1269881658);
526
            }
527
            $hookObject->getRecordOverlay_preProcess($table, $row, $sys_language_content, $OLmode, $this);
528
        }
529
530
        $tableControl = $GLOBALS['TCA'][$table]['ctrl'] ?? [];
531
532
        if (!empty($tableControl['languageField'])
533
            // Return record for ALL languages untouched
534
            // TODO: Fix call stack to prevent this situation in the first place
535
            && (int)$row[$tableControl['languageField']] !== -1
536
            && !empty($tableControl['transOrigPointerField'])
537
            && $row['uid'] > 0
538
            && ($row['pid'] > 0 || in_array($tableControl['rootLevel'] ?? false, [true, 1, -1], true))) {
539
            // Will try to overlay a record only if the sys_language_content value is larger than zero.
540
            if ($sys_language_content > 0) {
541
                // Must be default language, otherwise no overlaying
542
                if ((int)$row[$tableControl['languageField']] === 0) {
543
                    // Select overlay record:
544
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
545
                        ->getQueryBuilderForTable($table);
546
                    $queryBuilder->setRestrictions(
547
                        GeneralUtility::makeInstance(FrontendRestrictionContainer::class, $this->context)
548
                    );
549
                    $olrow = $queryBuilder->select('*')
550
                        ->from($table)
551
                        ->where(
552
                            $queryBuilder->expr()->eq(
553
                                'pid',
554
                                $queryBuilder->createNamedParameter($row['pid'], \PDO::PARAM_INT)
555
                            ),
556
                            $queryBuilder->expr()->eq(
557
                                $tableControl['languageField'],
558
                                $queryBuilder->createNamedParameter($sys_language_content, \PDO::PARAM_INT)
559
                            ),
560
                            $queryBuilder->expr()->eq(
561
                                $tableControl['transOrigPointerField'],
562
                                $queryBuilder->createNamedParameter($row['uid'], \PDO::PARAM_INT)
563
                            )
564
                        )
565
                        ->setMaxResults(1)
566
                        ->execute()
567
                        ->fetch();
568
569
                    $this->versionOL($table, $olrow);
570
                    // Merge record content by traversing all fields:
571
                    if (is_array($olrow)) {
572
                        if (isset($olrow['_ORIG_uid'])) {
573
                            $row['_ORIG_uid'] = $olrow['_ORIG_uid'];
574
                        }
575
                        if (isset($olrow['_ORIG_pid'])) {
576
                            $row['_ORIG_pid'] = $olrow['_ORIG_pid'];
577
                        }
578
                        foreach ($row as $fN => $fV) {
579
                            if ($fN !== 'uid' && $fN !== 'pid' && isset($olrow[$fN])) {
580
                                $row[$fN] = $olrow[$fN];
581
                            } elseif ($fN === 'uid') {
582
                                $row['_LOCALIZED_UID'] = $olrow['uid'];
583
                            }
584
                        }
585
                    } elseif ($OLmode === 'hideNonTranslated' && (int)$row[$tableControl['languageField']] === 0) {
586
                        // Unset, if non-translated records should be hidden. ONLY done if the source
587
                        // record really is default language and not [All] in which case it is allowed.
588
                        $row = null;
589
                    }
590
                } elseif ($sys_language_content != $row[$tableControl['languageField']]) {
591
                    $row = null;
592
                }
593
            } else {
594
                // When default language is displayed, we never want to return a record carrying
595
                // another language!
596
                if ($row[$tableControl['languageField']] > 0) {
597
                    $row = null;
598
                }
599
            }
600
        }
601
602
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'] ?? [] as $className) {
603
            $hookObject = GeneralUtility::makeInstance($className);
604
            if (!$hookObject instanceof PageRepositoryGetRecordOverlayHookInterface) {
605
                throw new \UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetRecordOverlayHookInterface::class, 1269881659);
606
            }
607
            $hookObject->getRecordOverlay_postProcess($table, $row, $sys_language_content, $OLmode, $this);
608
        }
609
610
        return $row;
611
    }
612
613
    /************************************************
614
     *
615
     * Page related: Menu, Domain record, Root line
616
     *
617
     ************************************************/
618
619
    /**
620
     * Returns an array with page rows for subpages of a certain page ID. This is used for menus in the frontend.
621
     * If there are mount points in overlay mode the _MP_PARAM field is set to the correct MPvar.
622
     *
623
     * If the $pageId being input does in itself require MPvars to define a correct
624
     * rootline these must be handled externally to this function.
625
     *
626
     * @param int|int[] $pageId The page id (or array of page ids) for which to fetch subpages (PID)
627
     * @param string $fields Fields to select, `*` is the default - If a custom list is set, make sure the list
628
     *                       contains the `uid` field. It's mandatory for further processing of the result row.
629
     * @param string $sortField The field to sort by. Default is "sorting
630
     * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%some text%'" for instance.
631
     * @param bool $checkShortcuts Check if shortcuts exist, checks by default
632
     * @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlaid localized fields, if any)
633
     * @see getPageShortcut()
634
     * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::makeMenu()
635
     */
636
    private function getMenu($pageId, $fields = '*', $sortField = 'sorting', $additionalWhereClause = '', $checkShortcuts = true)
637
    {
638
        return $this->getSubpagesForPages((array)$pageId, $fields, $sortField, $additionalWhereClause, $checkShortcuts);
639
    }
640
641
    /**
642
     * Returns an array with page-rows for pages with uid in $pageIds.
643
     *
644
     * This is used for menus. If there are mount points in overlay mode
645
     * the _MP_PARAM field is set to the correct MPvar.
646
     *
647
     * @param int[] $pageIds Array of page ids to fetch
648
     * @param string $fields Fields to select, `*` is the default - If a custom list is set, make sure the list
649
     *                       contains the `uid` field. It's mandatory for further processing of the result row.
650
     * @param string $sortField The field to sort by. Default is "sorting"
651
     * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%some text%'" for instance.
652
     * @param bool $checkShortcuts Check if shortcuts exist, checks by default
653
     * @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlaid localized fields, if any)
654
     */
655
    private function getMenuForPages(array $pageIds, $fields = '*', $sortField = 'sorting', $additionalWhereClause = '', $checkShortcuts = true)
0 ignored issues
show
Unused Code introduced by
The method getMenuForPages() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
656
    {
657
        return $this->getSubpagesForPages($pageIds, $fields, $sortField, $additionalWhereClause, $checkShortcuts, false);
658
    }
659
660
    /**
661
     * Loads page records either by PIDs or by UIDs.
662
     *
663
     * By default the subpages of the given page IDs are loaded (as the method name suggests). If $parentPages is set
664
     * to FALSE, the page records for the given page IDs are loaded directly.
665
     *
666
     * Concerning the rationale, please see these two other methods:
667
     *
668
     * @see PageRepository::getMenu()
669
     * @see PageRepository::getMenuForPages()
670
     *
671
     * Version and language overlay are applied to the loaded records.
672
     *
673
     * If a record is a mount point in overlay mode, the the overlaying page record is returned in place of the
674
     * record. The record is enriched by the field _MP_PARAM containing the mount point mapping for the mount
675
     * point.
676
     *
677
     * The query can be customized by setting fields, sorting and additional WHERE clauses. If additional WHERE
678
     * clauses are given, the clause must start with an operator, i.e: "AND title like '%some text%'".
679
     *
680
     * The keys of the returned page records are the page UIDs.
681
     *
682
     * CAUTION: In case of an overlaid mount point, it is the original UID.
683
     *
684
     * @param int[] $pageIds PIDs or UIDs to load records for
685
     * @param string $fields Fields to select, `*` is the default - If a custom list is set, make sure the list
686
     *                       contains the `uid` field. It's mandatory for further processing of the result row.
687
     * @param string $sortField the field to sort by
688
     * @param string $additionalWhereClause optional additional WHERE clause
689
     * @param bool $checkShortcuts whether to check if shortcuts exist
690
     * @param bool $parentPages Switch to load pages (false) or child pages (true).
691
     * @return array page records
692
     *
693
     * @see self::getPageShortcut()
694
     * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::makeMenu()
695
     */
696
    private function getSubpagesForPages(
697
        array $pageIds,
698
        string $fields = '*',
699
        string $sortField = 'sorting',
700
        string $additionalWhereClause = '',
701
        bool $checkShortcuts = true,
702
        bool $parentPages = true
703
    ): array {
704
        $relationField = $parentPages ? 'pid' : 'uid';
705
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
706
        $queryBuilder->getRestrictions()
707
            ->removeAll()
708
            ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, $this->versioningWorkspaceId));
0 ignored issues
show
Bug introduced by
The type AOE\Crawler\Domain\Repository\WorkspaceRestriction was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
709
710
        $res = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
711
            ->from('pages')
712
            ->where(
713
                $queryBuilder->expr()->in(
714
                    $relationField,
715
                    $queryBuilder->createNamedParameter($pageIds, Connection::PARAM_INT_ARRAY)
716
                ),
717
                $queryBuilder->expr()->eq(
718
                    $GLOBALS['TCA']['pages']['ctrl']['languageField'],
719
                    $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
720
                ),
721
                QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del),
722
                QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess),
723
                QueryHelper::stripLogicalOperatorPrefix($additionalWhereClause)
724
            );
725
726
        if (!empty($sortField)) {
727
            $orderBy = QueryHelper::parseOrderBy($sortField);
728
            foreach ($orderBy as $order) {
729
                $res->addOrderBy($order[0], $order[1] ?? 'ASC');
730
            }
731
        }
732
        $result = $res->execute();
733
734
        $pages = [];
735
        while ($page = $result->fetch()) {
736
            $originalUid = $page['uid'];
737
738
            // Versioning Preview Overlay
739
            $this->versionOL('pages', $page, true);
740
            // Skip if page got disabled due to version overlay (might be delete placeholder)
741
            if (empty($page)) {
742
                continue;
743
            }
744
745
            // Add a mount point parameter if needed
746
            $page = $this->addMountPointParameterToPage((array)$page);
747
748
            // If shortcut, look up if the target exists and is currently visible
749
            if ($checkShortcuts) {
750
                $page = $this->checkValidShortcutOfPage((array)$page, $additionalWhereClause);
751
            }
752
753
            // If the page still is there, we add it to the output
754
            if (!empty($page)) {
755
                $pages[$originalUid] = $page;
756
            }
757
        }
758
759
        // Finally load language overlays
760
        return $this->getPagesOverlay($pages);
761
    }
762
763
    /**
764
     * Replaces the given page record with mounted page if required
765
     *
766
     * If the given page record is a mount point in overlay mode, the page
767
     * record is replaced by the record of the overlaying page. The overlay
768
     * record is enriched by setting the mount point mapping into the field
769
     * _MP_PARAM as string for example '23-14'.
770
     *
771
     * In all other cases the given page record is returned as is.
772
     *
773
     * @todo Find a better name. The current doesn't hit the point.
774
     *
775
     * @param array $page The page record to handle.
776
     * @return array The given page record or it's replacement.
777
     */
778
    private function addMountPointParameterToPage(array $page): array
779
    {
780
        if (empty($page)) {
781
            return [];
782
        }
783
784
        // $page MUST have "uid", "pid", "doktype", "mount_pid", "mount_pid_ol" fields in it
785
        $mountPointInfo = $this->getMountPointInfo($page['uid'], $page);
786
787
        // There is a valid mount point in overlay mode.
788
        if (is_array($mountPointInfo) && $mountPointInfo['overlay']) {
789
790
            // Using "getPage" is OK since we need the check for enableFields AND for type 2
791
            // of mount pids we DO require a doktype < 200!
792
            $mountPointPage = $this->getPage($mountPointInfo['mount_pid']);
793
794
            if (!empty($mountPointPage)) {
795
                $page = $mountPointPage;
796
                $page['_MP_PARAM'] = $mountPointInfo['MPvar'];
797
            } else {
798
                $page = [];
799
            }
800
        }
801
        return $page;
802
    }
803
804
    /**
805
     * If shortcut, look up if the target exists and is currently visible
806
     *
807
     * @param array $page The page to check
808
     * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%some text%'" for instance.
809
     * @return array
810
     */
811
    private function checkValidShortcutOfPage(array $page, $additionalWhereClause)
812
    {
813
        if (empty($page)) {
814
            return [];
815
        }
816
817
        $dokType = (int)$page['doktype'];
818
        $shortcutMode = (int)$page['shortcut_mode'];
819
820
        if ($dokType === self::DOKTYPE_SHORTCUT && ($page['shortcut'] || $shortcutMode)) {
821
            if ($shortcutMode === self::SHORTCUT_MODE_NONE) {
822
                // No shortcut_mode set, so target is directly set in $page['shortcut']
823
                $searchField = 'uid';
824
                $searchUid = (int)$page['shortcut'];
825
            } elseif ($shortcutMode === self::SHORTCUT_MODE_FIRST_SUBPAGE || $shortcutMode === self::SHORTCUT_MODE_RANDOM_SUBPAGE) {
826
                // Check subpages - first subpage or random subpage
827
                $searchField = 'pid';
828
                // If a shortcut mode is set and no valid page is given to select subpages
829
                // from use the actual page.
830
                $searchUid = (int)$page['shortcut'] ?: $page['uid'];
831
            } elseif ($shortcutMode === self::SHORTCUT_MODE_PARENT_PAGE) {
832
                // Shortcut to parent page
833
                $searchField = 'uid';
834
                $searchUid = $page['pid'];
835
            } else {
836
                $searchField = '';
837
                $searchUid = 0;
838
            }
839
840
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
841
            $queryBuilder->getRestrictions()->removeAll();
842
            $count = $queryBuilder->count('uid')
843
                ->from('pages')
844
                ->where(
845
                    $queryBuilder->expr()->eq(
846
                        $searchField,
847
                        $queryBuilder->createNamedParameter($searchUid, \PDO::PARAM_INT)
848
                    ),
849
                    QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del),
850
                    QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess),
851
                    QueryHelper::stripLogicalOperatorPrefix($additionalWhereClause)
852
                )
853
                ->execute()
854
                ->fetchColumn();
855
856
            if (!$count) {
857
                $page = [];
858
            }
859
        } elseif ($dokType === self::DOKTYPE_SHORTCUT) {
860
            // Neither shortcut target nor mode is set. Remove the page from the menu.
861
            $page = [];
862
        }
863
        return $page;
864
    }
865
866
    /**
867
     * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
868
     *
869
     * @param string $shortcutFieldValue The value of the "shortcut" field from the pages record
870
     * @param int $shortcutMode The shortcut mode: 1 will select first subpage, 2 a random subpage, 3 the parent page; default is the page pointed to by $SC
871
     * @param int $thisUid The current page UID of the page which is a shortcut
872
     * @param int $iteration Safety feature which makes sure that the function is calling itself recursively max 20 times (since this function can find shortcuts to other shortcuts to other shortcuts...)
873
     * @param array $pageLog An array filled with previous page uids tested by the function - new page uids are evaluated against this to avoid going in circles.
874
     * @param bool $disableGroupCheck If true, the group check is disabled when fetching the target page (needed e.g. for menu generation)
875
     *
876
     * @throws \RuntimeException
877
     * @throws ShortcutTargetPageNotFoundException
878
     * @return mixed Returns the page record of the page that the shortcut pointed to.
879
     * @internal
880
     * @see getPageAndRootline()
881
     */
882
    private function getPageShortcut($shortcutFieldValue, $shortcutMode, $thisUid, $iteration = 20, $pageLog = [], $disableGroupCheck = false)
883
    {
884
        $idArray = GeneralUtility::intExplode(',', $shortcutFieldValue);
885
        // Find $page record depending on shortcut mode:
886
        switch ($shortcutMode) {
887
            case self::SHORTCUT_MODE_FIRST_SUBPAGE:
888
            case self::SHORTCUT_MODE_RANDOM_SUBPAGE:
889
                $pageArray = $this->getMenu($idArray[0] ?: $thisUid, '*', 'sorting', 'AND pages.doktype<199 AND pages.doktype!=' . self::DOKTYPE_BE_USER_SECTION);
890
                $pO = 0;
891
                if ($shortcutMode == self::SHORTCUT_MODE_RANDOM_SUBPAGE && !empty($pageArray)) {
892
                    $pO = (int)random_int(0, count($pageArray) - 1);
893
                }
894
                $c = 0;
895
                $page = [];
896
                foreach ($pageArray as $pV) {
897
                    if ($c === $pO) {
898
                        $page = $pV;
899
                        break;
900
                    }
901
                    $c++;
902
                }
903
                if (empty($page)) {
904
                    $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a subpage. However, this page has no accessible subpages.';
905
                    throw new ShortcutTargetPageNotFoundException($message, 1301648328);
0 ignored issues
show
Bug introduced by
The type AOE\Crawler\Domain\Repos...etPageNotFoundException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
906
                }
907
                break;
908
            case self::SHORTCUT_MODE_PARENT_PAGE:
909
                $parent = $this->getPage($idArray[0] ?: $thisUid, $disableGroupCheck);
910
                $page = $this->getPage($parent['pid'], $disableGroupCheck);
911
                if (empty($page)) {
912
                    $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to its parent page. However, the parent page is not accessible.';
913
                    throw new ShortcutTargetPageNotFoundException($message, 1301648358);
914
                }
915
                break;
916
            default:
917
                $page = $this->getPage($idArray[0], $disableGroupCheck);
918
                if (empty($page)) {
919
                    $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a page, which is not accessible (ID ' . $idArray[0] . ').';
920
                    throw new ShortcutTargetPageNotFoundException($message, 1301648404);
921
                }
922
        }
923
        // Check if short cut page was a shortcut itself, if so look up recursively:
924
        if ($page['doktype'] == self::DOKTYPE_SHORTCUT) {
925
            if (!in_array($page['uid'], $pageLog) && $iteration > 0) {
926
                $pageLog[] = $page['uid'];
927
                $page = $this->getPageShortcut($page['shortcut'], $page['shortcut_mode'], $page['uid'], $iteration - 1, $pageLog, $disableGroupCheck);
928
            } else {
929
                $pageLog[] = $page['uid'];
930
                $message = 'Page shortcuts were looping in uids ' . implode(',', $pageLog) . '...!';
931
                $this->logger->error($message);
932
                throw new \RuntimeException($message, 1294587212);
933
            }
934
        }
935
        // Return resulting page:
936
        return $page;
937
    }
938
939
    /**
940
     * Returns a MountPoint array for the specified page
941
     *
942
     * Does a recursive search if the mounted page should be a mount page
943
     * itself.
944
     *
945
     * Note:
946
     *
947
     * Recursive mount points are not supported by all parts of the core.
948
     * The usage is discouraged. They may be removed from this method.
949
     *
950
     * @see https://decisions.typo3.org/t/supporting-or-prohibiting-recursive-mount-points/165/3
951
     *
952
     * An array will be returned if mount pages are enabled, the correct
953
     * doktype (7) is set for page and there IS a mount_pid with a valid
954
     * record.
955
     *
956
     * The optional page record must contain at least uid, pid, doktype,
957
     * mount_pid,mount_pid_ol. If it is not supplied it will be looked up by
958
     * the system at additional costs for the lookup.
959
     *
960
     * Returns FALSE if no mount point was found, "-1" if there should have been
961
     * one, but no connection to it, otherwise an array with information
962
     * about mount pid and modes.
963
     *
964
     * @param int $pageId Page id to do the lookup for.
965
     * @param array|bool $pageRec Optional page record for the given page.
966
     * @param array $prevMountPids Internal register to prevent lookup cycles.
967
     * @param int $firstPageUid The first page id.
968
     * @return mixed Mount point array or failure flags (-1, false).
969
     * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
970
     */
971
    private function getMountPointInfo($pageId, $pageRec = false, $prevMountPids = [], $firstPageUid = 0)
972
    {
973
        if (!$GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
974
            return false;
975
        }
976
        $cacheIdentifier = 'PageRepository_getMountPointInfo_' . $pageId;
977
        $cache = $this->getRuntimeCache();
978
        if ($cache->has($cacheIdentifier)) {
979
            return $cache->get($cacheIdentifier);
980
        }
981
        $result = false;
982
        // Get pageRec if not supplied:
983
        if (!is_array($pageRec)) {
984
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
985
            $queryBuilder->getRestrictions()
986
                ->removeAll()
987
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
988
989
            $pageRec = $queryBuilder->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol', 't3ver_state', 'l10n_parent')
990
                ->from('pages')
991
                ->where(
992
                    $queryBuilder->expr()->eq(
993
                        'uid',
994
                        $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT)
995
                    ),
996
                    $queryBuilder->expr()->neq(
997
                        'doktype',
998
                        $queryBuilder->createNamedParameter(self::DOKTYPE_RECYCLER, \PDO::PARAM_INT)
999
                    )
1000
                )
1001
                ->execute()
1002
                ->fetch();
1003
1004
            // Only look for version overlay if page record is not supplied; This assumes
1005
            // that the input record is overlaid with preview version, if any!
1006
            $this->versionOL('pages', $pageRec);
1007
        }
1008
        // Set first Page uid:
1009
        if (!$firstPageUid) {
1010
            $firstPageUid = (int)($pageRec['l10n_parent'] ?: $pageRec['uid']);
1011
        }
1012
        // Look for mount pid value plus other required circumstances:
1013
        $mount_pid = (int)$pageRec['mount_pid'];
1014
        if (is_array($pageRec) && (int)$pageRec['doktype'] === self::DOKTYPE_MOUNTPOINT && $mount_pid > 0 && !in_array($mount_pid, $prevMountPids, true)) {
1015
            // Get the mount point record (to verify its general existence):
1016
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1017
            $queryBuilder->getRestrictions()
1018
                ->removeAll()
1019
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1020
1021
            $mountRec = $queryBuilder->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol', 't3ver_state', 'l10n_parent')
1022
                ->from('pages')
1023
                ->where(
1024
                    $queryBuilder->expr()->eq(
1025
                        'uid',
1026
                        $queryBuilder->createNamedParameter($mount_pid, \PDO::PARAM_INT)
1027
                    ),
1028
                    $queryBuilder->expr()->neq(
1029
                        'doktype',
1030
                        $queryBuilder->createNamedParameter(self::DOKTYPE_RECYCLER, \PDO::PARAM_INT)
1031
                    )
1032
                )
1033
                ->execute()
1034
                ->fetch();
1035
1036
            $this->versionOL('pages', $mountRec);
1037
            if (is_array($mountRec)) {
1038
                // Look for recursive mount point:
1039
                $prevMountPids[] = $mount_pid;
1040
                $recursiveMountPid = $this->getMountPointInfo($mount_pid, $mountRec, $prevMountPids, $firstPageUid);
1041
                // Return mount point information:
1042
                $result = $recursiveMountPid ?: [
1043
                    'mount_pid' => $mount_pid,
1044
                    'overlay' => $pageRec['mount_pid_ol'],
1045
                    'MPvar' => $mount_pid . '-' . $firstPageUid,
1046
                    'mount_point_rec' => $pageRec,
1047
                    'mount_pid_rec' => $mountRec
1048
                ];
1049
            } else {
1050
                // Means, there SHOULD have been a mount point, but there was none!
1051
                $result = -1;
1052
            }
1053
        }
1054
        $cache->set($cacheIdentifier, $result);
1055
        return $result;
1056
    }
1057
1058
    /********************************
1059
     *
1060
     * Standard clauses
1061
     *
1062
     ********************************/
1063
1064
    /**
1065
     * Returns a part of a WHERE clause which will filter out records with start/end
1066
     * times or hidden/fe_groups fields set to values that should de-select them
1067
     * according to the current time, preview settings or user login. Definitely a
1068
     * frontend function.
1069
     *
1070
     * Is using the $GLOBALS['TCA'] arrays "ctrl" part where the key "enablefields"
1071
     * determines for each table which of these features applies to that table.
1072
     *
1073
     * @param string $table Table name found in the $GLOBALS['TCA'] array
1074
     * @param int $show_hidden If $show_hidden is set (0/1), any hidden-fields in records are ignored. NOTICE: If you call this function, consider what to do with the show_hidden parameter. Maybe it should be set? See ContentObjectRenderer->enableFields where it's implemented correctly.
1075
     * @param array $ignore_array Array you can pass where keys can be "disabled", "starttime", "endtime", "fe_group" (keys from "enablefields" in TCA) and if set they will make sure that part of the clause is not added. Thus disables the specific part of the clause. For previewing etc.
1076
     * @throws \InvalidArgumentException
1077
     * @return string The clause starting like " AND ...=... AND ...=...
1078
     */
1079
    private function enableFields($table, $show_hidden = -1, $ignore_array = [])
1080
    {
1081
        if ($show_hidden === -1) {
1082
            // If show_hidden was not set from outside, use the current context
1083
            $show_hidden = (int)$this->context->getPropertyFromAspect('visibility', $table === 'pages' ? 'includeHiddenPages' : 'includeHiddenContent', false);
1084
        }
1085
        // If show_hidden was not changed during the previous evaluation, do it here.
1086
        $ctrl = $GLOBALS['TCA'][$table]['ctrl'] ?? null;
1087
        $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1088
            ->getQueryBuilderForTable($table)
1089
            ->expr();
1090
        $constraints = [];
1091
        if (is_array($ctrl)) {
1092
            // Delete field check:
1093
            if ($ctrl['delete']) {
1094
                $constraints[] = $expressionBuilder->eq($table . '.' . $ctrl['delete'], 0);
1095
            }
1096
            if ($this->hasTableWorkspaceSupport($table)) {
1097
                // this should work exactly as WorkspaceRestriction and WorkspaceRestriction should be used instead
1098
                if ($this->versioningWorkspaceId === 0) {
1099
                    // Filter out placeholder records (new/deleted items)
1100
                    // in case we are NOT in a version preview (that means we are online!)
1101
                    $constraints[] = $expressionBuilder->lte(
1102
                        $table . '.t3ver_state',
1103
                        new VersionState(VersionState::DEFAULT_STATE)
1104
                    );
1105
                    $constraints[] = $expressionBuilder->eq($table . '.t3ver_wsid', 0);
1106
                } else {
1107
                    // show only records of live and of the current workspace
1108
                    // in case we are in a versioning preview
1109
                    $constraints[] = $expressionBuilder->orX(
1110
                        $expressionBuilder->eq($table . '.t3ver_wsid', 0),
1111
                        $expressionBuilder->eq($table . '.t3ver_wsid', (int)$this->versioningWorkspaceId)
1112
                    );
1113
                }
1114
1115
                // Filter out versioned records
1116
                if (empty($ignore_array['pid'])) {
1117
                    // Always filter out versioned records that have an "offline" record
1118
                    $constraints[] = $expressionBuilder->orX(
1119
                        $expressionBuilder->eq($table . '.t3ver_oid', 0),
1120
                        $expressionBuilder->eq($table . '.t3ver_state', VersionState::MOVE_POINTER)
1121
                    );
1122
                }
1123
            }
1124
1125
            // Enable fields:
1126
            if (is_array($ctrl['enablecolumns'])) {
1127
                // In case of versioning-preview, enableFields are ignored (checked in
1128
                // versionOL())
1129
                if ($this->versioningWorkspaceId === 0 || !$this->hasTableWorkspaceSupport($table)) {
1130
                    if (($ctrl['enablecolumns']['disabled'] ?? false) && !$show_hidden && !($ignore_array['disabled'] ?? false)) {
1131
                        $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
1132
                        $constraints[] = $expressionBuilder->eq($field, 0);
1133
                    }
1134
                    if (($ctrl['enablecolumns']['starttime'] ?? false) && !($ignore_array['starttime'] ?? false)) {
1135
                        $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
1136
                        $constraints[] = $expressionBuilder->lte(
1137
                            $field,
1138
                            $this->context->getPropertyFromAspect('date', 'accessTime', 0)
1139
                        );
1140
                    }
1141
                    if (($ctrl['enablecolumns']['endtime'] ?? false) && !($ignore_array['endtime'] ?? false)) {
1142
                        $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
1143
                        $constraints[] = $expressionBuilder->orX(
1144
                            $expressionBuilder->eq($field, 0),
1145
                            $expressionBuilder->gt(
1146
                                $field,
1147
                                $this->context->getPropertyFromAspect('date', 'accessTime', 0)
1148
                            )
1149
                        );
1150
                    }
1151
                    if (($ctrl['enablecolumns']['fe_group'] ?? false) && !($ignore_array['fe_group'] ?? false)) {
1152
                        $field = $table . '.' . $ctrl['enablecolumns']['fe_group'];
1153
                        $constraints[] = QueryHelper::stripLogicalOperatorPrefix(
1154
                            $this->getMultipleGroupsWhereClause($field, $table)
1155
                        );
1156
                    }
1157
                    // Call hook functions for additional enableColumns
1158
                    // It is used by the extension ingmar_accessctrl which enables assigning more
1159
                    // than one usergroup to content and page records
1160
                    $_params = [
1161
                        'table' => $table,
1162
                        'show_hidden' => $show_hidden,
1163
                        'ignore_array' => $ignore_array,
1164
                        'ctrl' => $ctrl
1165
                    ];
1166
                    foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'] ?? [] as $_funcRef) {
1167
                        $constraints[] = QueryHelper::stripLogicalOperatorPrefix(
1168
                            GeneralUtility::callUserFunction($_funcRef, $_params, $this)
1169
                        );
1170
                    }
1171
                }
1172
            }
1173
        } else {
1174
            throw new \InvalidArgumentException('There is no entry in the $TCA array for the table "' . $table . '". This means that the function enableFields() is called with an invalid table name as argument.', 1283790586);
1175
        }
1176
1177
        return empty($constraints) ? '' : ' AND ' . $expressionBuilder->andX(...$constraints);
1178
    }
1179
1180
    /**
1181
     * Creating where-clause for checking group access to elements in enableFields
1182
     * function
1183
     *
1184
     * @param string $field Field with group list
1185
     * @param string $table Table name
1186
     * @return string AND sql-clause
1187
     * @see enableFields()
1188
     */
1189
    private function getMultipleGroupsWhereClause($field, $table)
1190
    {
1191
        if (!$this->context->hasAspect('frontend.user')) {
1192
            return '';
1193
        }
1194
        /** @var UserAspect $userAspect */
1195
        $userAspect = $this->context->getAspect('frontend.user');
1196
        $memberGroups = $userAspect->getGroupIds();
1197
        $cache = $this->getRuntimeCache();
1198
        $cacheIdentifier = 'PageRepository_groupAccessWhere_' . md5($field . '_' . $table . '_' . implode('_', $memberGroups));
1199
        $cacheEntry = $cache->get($cacheIdentifier);
1200
        if ($cacheEntry) {
1201
            return $cacheEntry;
1202
        }
1203
1204
        $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1205
            ->getQueryBuilderForTable($table)
1206
            ->expr();
1207
        $orChecks = [];
1208
        // If the field is empty, then OK
1209
        $orChecks[] = $expressionBuilder->eq($field, $expressionBuilder->literal(''));
1210
        // If the field is NULL, then OK
1211
        $orChecks[] = $expressionBuilder->isNull($field);
1212
        // If the field contains zero, then OK
1213
        $orChecks[] = $expressionBuilder->eq($field, $expressionBuilder->literal('0'));
1214
        foreach ($memberGroups as $value) {
1215
            $orChecks[] = $expressionBuilder->inSet($field, $expressionBuilder->literal($value));
1216
        }
1217
1218
        $accessGroupWhere = ' AND (' . $expressionBuilder->orX(...$orChecks) . ')';
1219
        $cache->set($cacheIdentifier, $accessGroupWhere);
1220
        return $accessGroupWhere;
1221
    }
1222
1223
    /**********************
1224
     *
1225
     * Versioning Preview
1226
     *
1227
     **********************/
1228
1229
    /**
1230
     * Versioning Preview Overlay
1231
     *
1232
     * ONLY active when backend user is previewing records. MUST NEVER affect a site
1233
     * served which is not previewed by backend users!!!
1234
     *
1235
     * Generally ALWAYS used when records are selected based on uid or pid. If
1236
     * records are selected on other fields than uid or pid (eg. "email = ....") then
1237
     * usage might produce undesired results and that should be evaluated on
1238
     * individual basis.
1239
     *
1240
     * Principle; Record online! => Find offline?
1241
     *
1242
     * @param string $table Table name
1243
     * @param array $row Record array passed by reference. As minimum, the "uid", "pid" and "t3ver_state" fields must exist! The record MAY be set to FALSE in which case the calling function should act as if the record is forbidden to access!
1244
     * @param bool $unsetMovePointers If set, the $row is cleared in case it is a move-pointer. This is only for preview of moved records (to remove the record from the original location so it appears only in the new location)
1245
     * @param bool $bypassEnableFieldsCheck Unless this option is TRUE, the $row is unset if enablefields for BOTH the version AND the online record deselects it. This is because when versionOL() is called it is assumed that the online record is already selected with no regards to it's enablefields. However, after looking for a new version the online record enablefields must ALSO be evaluated of course. This is done all by this function!
1246
     * @see BackendUtility::workspaceOL()
1247
     */
1248
    private function versionOL($table, &$row, $unsetMovePointers = false, $bypassEnableFieldsCheck = false)
1249
    {
1250
        if ($this->versioningWorkspaceId > 0 && is_array($row)) {
1251
            // implode(',',array_keys($row)) = Using fields from original record to make
1252
            // sure no additional fields are selected. This is best for eg. getPageOverlay()
1253
            // Computed properties are excluded since those would lead to SQL errors.
1254
            $fieldNames = implode(',', array_keys($this->purgeComputedProperties($row)));
1255
            // will overlay any incoming moved record with the live record, which in turn
1256
            // will be overlaid with its workspace version again to fetch both PID fields.
1257
            $incomingRecordIsAMoveVersion = (int)($row['t3ver_oid'] ?? 0) > 0 && (int)($row['t3ver_state'] ?? 0) === VersionState::MOVE_POINTER;
1258
            if ($incomingRecordIsAMoveVersion) {
1259
                // Fetch the live version again if the given $row is a move pointer, so we know the original PID
1260
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1261
                $queryBuilder->getRestrictions()
1262
                    ->removeAll()
1263
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1264
                $row = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fieldNames, true))
1265
                    ->from($table)
1266
                    ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter((int)$row['t3ver_oid'], \PDO::PARAM_INT)))
1267
                    ->execute()
1268
                    ->fetch();
1269
            }
1270
            if ($wsAlt = $this->getWorkspaceVersionOfRecord($this->versioningWorkspaceId, $table, $row['uid'], $fieldNames, $bypassEnableFieldsCheck)) {
1271
                if (is_array($wsAlt)) {
1272
                    $rowVersionState = VersionState::cast($wsAlt['t3ver_state'] ?? null);
1273
                    if ($rowVersionState->equals(VersionState::MOVE_POINTER)) {
1274
                        // For move pointers, store the actual live PID in the _ORIG_pid
1275
                        // The only place where PID is actually different in a workspace
1276
                        $wsAlt['_ORIG_pid'] = $row['pid'];
1277
                    }
1278
                    // For versions of single elements or page+content, preserve online UID
1279
                    // (this will produce true "overlay" of element _content_, not any references)
1280
                    // For new versions there is no online counterpart
1281
                    if (!$rowVersionState->equals(VersionState::NEW_PLACEHOLDER)) {
1282
                        $wsAlt['_ORIG_uid'] = $wsAlt['uid'];
1283
                    }
1284
                    $wsAlt['uid'] = $row['uid'];
1285
                    // Changing input record to the workspace version alternative:
1286
                    $row = $wsAlt;
1287
                    // Unset record if it turned out to be deleted in workspace
1288
                    if ($rowVersionState->equals(VersionState::DELETE_PLACEHOLDER)) {
1289
                        $row = false;
1290
                    }
1291
                    // Check if move-pointer in workspace (unless if a move-placeholder is the
1292
                    // reason why it appears!):
1293
                    // You have to specifically set $unsetMovePointers in order to clear these
1294
                    // because it is normally a display issue if it should be shown or not.
1295
                    if ($rowVersionState->equals(VersionState::MOVE_POINTER) && !$incomingRecordIsAMoveVersion && $unsetMovePointers) {
1296
                        // Unset record if it turned out to be deleted in workspace
1297
                        $row = false;
1298
                    }
1299
                } else {
1300
                    // No version found, then check if online version is dummy-representation
1301
                    // Notice, that unless $bypassEnableFieldsCheck is TRUE, the $row is unset if
1302
                    // enablefields for BOTH the version AND the online record deselects it. See
1303
                    // note for $bypassEnableFieldsCheck
1304
                    /** @var \TYPO3\CMS\Core\Versioning\VersionState $versionState */
1305
                    $versionState = VersionState::cast($row['t3ver_state']);
1306
                    if ($wsAlt <= -1 || $versionState->indicatesPlaceholder()) {
1307
                        // Unset record if it turned out to be "hidden"
1308
                        $row = false;
1309
                    }
1310
                }
1311
            }
1312
        }
1313
    }
1314
1315
    /**
1316
     * Returns the PID of the new (moved) location within a version, when a $liveUid is given.
1317
     *
1318
     * Please note: This is only performed within a workspace.
1319
     * This was previously stored in the move placeholder's PID, but move pointer's PID and move placeholder's PID
1320
     * are the same since TYPO3 v10, so the MOVE_POINTER is queried.
1321
     *
1322
     * @param string $table Table name
1323
     * @param int $liveUid Record UID of online version
1324
     * @return int|null If found, the Page ID of the moved record, otherwise null.
1325
     */
1326
    private function getMovedPidOfVersionedRecord(string $table, int $liveUid): ?int
0 ignored issues
show
Unused Code introduced by
The method getMovedPidOfVersionedRecord() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
1327
    {
1328
        if ($this->versioningWorkspaceId <= 0) {
1329
            return null;
1330
        }
1331
        if (!$this->hasTableWorkspaceSupport($table)) {
1332
            return null;
1333
        }
1334
        // Select workspace version of record
1335
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1336
        $queryBuilder->getRestrictions()
1337
            ->removeAll()
1338
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1339
1340
        $row = $queryBuilder->select('pid')
1341
            ->from($table)
1342
            ->where(
1343
                $queryBuilder->expr()->eq(
1344
                    't3ver_state',
1345
                    $queryBuilder->createNamedParameter(
1346
                        (string)VersionState::cast(VersionState::MOVE_POINTER),
1347
                        \PDO::PARAM_INT
1348
                    )
1349
                ),
1350
                $queryBuilder->expr()->eq(
1351
                    't3ver_oid',
1352
                    $queryBuilder->createNamedParameter($liveUid, \PDO::PARAM_INT)
1353
                ),
1354
                $queryBuilder->expr()->eq(
1355
                    't3ver_wsid',
1356
                    $queryBuilder->createNamedParameter($this->versioningWorkspaceId, \PDO::PARAM_INT)
1357
                )
1358
            )
1359
            ->setMaxResults(1)
1360
            ->execute()
1361
            ->fetch();
1362
1363
        if (is_array($row)) {
1364
            return (int)$row['pid'];
1365
        }
1366
        return null;
1367
    }
1368
1369
    /**
1370
     * Select the version of a record for a workspace
1371
     *
1372
     * @param int $workspace Workspace ID
1373
     * @param string $table Table name to select from
1374
     * @param int $uid Record uid for which to find workspace version.
1375
     * @param string $fields Fields to select, `*` is the default - If a custom list is set, make sure the list
1376
     *                       contains the `uid` field. It's mandatory for further processing of the result row.
1377
     * @param bool $bypassEnableFieldsCheck If TRUE, enablefields are not checked for.
1378
     * @return mixed If found, return record, otherwise other value: Returns 1 if version was sought for but not found, returns -1/-2 if record (offline/online) existed but had enableFields that would disable it. Returns FALSE if not in workspace or no versioning for record. Notice, that the enablefields of the online record is also tested.
1379
     * @see BackendUtility::getWorkspaceVersionOfRecord()
1380
     */
1381
    private function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields = '*', $bypassEnableFieldsCheck = false)
1382
    {
1383
        if ($workspace !== 0 && $this->hasTableWorkspaceSupport($table)) {
1384
            $workspace = (int)$workspace;
1385
            $uid = (int)$uid;
1386
            // Select workspace version of record, only testing for deleted.
1387
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1388
            $queryBuilder->getRestrictions()
1389
                ->removeAll()
1390
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1391
1392
            $newrow = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
1393
                ->from($table)
1394
                ->where(
1395
                    $queryBuilder->expr()->eq(
1396
                        't3ver_wsid',
1397
                        $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1398
                    ),
1399
                    $queryBuilder->expr()->orX(
1400
                    // t3ver_state=1 does not contain a t3ver_oid, and returns itself
1401
                        $queryBuilder->expr()->andX(
1402
                            $queryBuilder->expr()->eq(
1403
                                'uid',
1404
                                $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1405
                            ),
1406
                            $queryBuilder->expr()->eq(
1407
                                't3ver_state',
1408
                                $queryBuilder->createNamedParameter(VersionState::NEW_PLACEHOLDER, \PDO::PARAM_INT)
1409
                            )
1410
                        ),
1411
                        $queryBuilder->expr()->eq(
1412
                            't3ver_oid',
1413
                            $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1414
                        )
1415
                    )
1416
                )
1417
                ->setMaxResults(1)
1418
                ->execute()
1419
                ->fetch();
1420
1421
            // If version found, check if it could have been selected with enableFields on
1422
            // as well:
1423
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1424
            $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class, $this->context));
1425
            // Remove the frontend workspace restriction because we are testing a version record
1426
            $queryBuilder->getRestrictions()->removeByType(FrontendWorkspaceRestriction::class);
0 ignored issues
show
Bug introduced by
The type AOE\Crawler\Domain\Repos...endWorkspaceRestriction was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1427
            $queryBuilder->select('uid')
1428
                ->from($table)
1429
                ->setMaxResults(1);
1430
1431
            if (is_array($newrow)) {
1432
                $queryBuilder->where(
1433
                    $queryBuilder->expr()->eq(
1434
                        't3ver_wsid',
1435
                        $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1436
                    ),
1437
                    $queryBuilder->expr()->orX(
1438
                    // t3ver_state=1 does not contain a t3ver_oid, and returns itself
1439
                        $queryBuilder->expr()->andX(
1440
                            $queryBuilder->expr()->eq(
1441
                                'uid',
1442
                                $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1443
                            ),
1444
                            $queryBuilder->expr()->eq(
1445
                                't3ver_state',
1446
                                $queryBuilder->createNamedParameter(VersionState::NEW_PLACEHOLDER, \PDO::PARAM_INT)
1447
                            )
1448
                        ),
1449
                        $queryBuilder->expr()->eq(
1450
                            't3ver_oid',
1451
                            $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1452
                        )
1453
                    )
1454
                );
1455
                if ($bypassEnableFieldsCheck || $queryBuilder->execute()->fetchColumn()) {
1456
                    // Return offline version, tested for its enableFields.
1457
                    return $newrow;
1458
                }
1459
                // Return -1 because offline version was de-selected due to its enableFields.
1460
                return -1;
1461
            }
1462
            // OK, so no workspace version was found. Then check if online version can be
1463
            // selected with full enable fields and if so, return 1:
1464
            $queryBuilder->where(
1465
                $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT))
1466
            );
1467
            if ($bypassEnableFieldsCheck || $queryBuilder->execute()->fetchColumn()) {
1468
                // Means search was done, but no version found.
1469
                return 1;
1470
            }
1471
            // Return -2 because the online record was de-selected due to its enableFields.
1472
            return -2;
1473
        }
1474
        // No look up in database because versioning not enabled / or workspace not
1475
        // offline
1476
        return false;
1477
    }
1478
1479
    /**
1480
     * Purges computed properties from database rows,
1481
     * such as _ORIG_uid or _ORIG_pid for instance.
1482
     *
1483
     * @param array $row
1484
     * @return array
1485
     */
1486
    private function purgeComputedProperties(array $row)
1487
    {
1488
        foreach ($this->computedPropertyNames as $computedPropertyName) {
1489
            if (array_key_exists($computedPropertyName, $row)) {
1490
                unset($row[$computedPropertyName]);
1491
            }
1492
        }
1493
        return $row;
1494
    }
1495
1496
    /**
1497
     * @return VariableFrontend
1498
     */
1499
    private function getRuntimeCache(): VariableFrontend
1500
    {
1501
        return GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
1502
    }
1503
1504
    private function hasTableWorkspaceSupport(string $tableName): bool
1505
    {
1506
        return !empty($GLOBALS['TCA'][$tableName]['ctrl']['versioningWS']);
1507
    }
1508
}
1509