Passed
Branch master (6c65a4)
by Christian
16:31
created

PageRepository::getMultipleGroupsWhereClause()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 2
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
1
<?php
2
namespace TYPO3\CMS\Frontend\Page;
3
4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
 * It is free software; you can redistribute it and/or modify it under
8
 * the terms of the GNU General Public License, either version 2
9
 * of the License, or any later version.
10
 *
11
 * For the full copyright and license information, please read the
12
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
 * The TYPO3 project - inspiring people to share!
15
 */
16
17
use Psr\Log\LoggerAwareInterface;
18
use Psr\Log\LoggerAwareTrait;
19
use TYPO3\CMS\Core\Compatibility\PublicPropertyDeprecationTrait;
20
use TYPO3\CMS\Core\Database\Connection;
21
use TYPO3\CMS\Core\Database\ConnectionPool;
22
use TYPO3\CMS\Core\Database\Query\QueryHelper;
23
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
24
use TYPO3\CMS\Core\Database\Query\Restriction\FrontendRestrictionContainer;
25
use TYPO3\CMS\Core\Database\Query\Restriction\FrontendWorkspaceRestriction;
26
use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;
27
use TYPO3\CMS\Core\Resource\FileRepository;
28
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
29
use TYPO3\CMS\Core\Utility\GeneralUtility;
30
use TYPO3\CMS\Core\Utility\HttpUtility;
31
use TYPO3\CMS\Core\Utility\RootlineUtility;
32
use TYPO3\CMS\Core\Versioning\VersionState;
33
34
/**
35
 * Page functions, a lot of sql/pages-related functions
36
 *
37
 * Mainly used in the frontend but also in some cases in the backend. It's
38
 * important to set the right $where_hid_del in the object so that the
39
 * functions operate properly
40
 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::fetch_the_id()
41
 */
42
class PageRepository implements LoggerAwareInterface
43
{
44
    use LoggerAwareTrait;
45
    use PublicPropertyDeprecationTrait;
46
47
    /**
48
     * List of all deprecated public properties
49
     * @var array
50
     */
51
    protected $deprecatedPublicProperties = [
52
        'workspaceCache' => 'Using $workspaceCache of class PageRepository from the outside is discouraged, as this only reflects a local runtime cache.',
53
        'error_getRootLine' => 'Using $error_getRootLine of class PageRepository from the outside is deprecated as this property only exists for legacy reasons.',
54
        'error_getRootLine_failPid' => 'Using $error_getRootLine_failPid of class PageRepository from the outside is deprecated as this property only exists for legacy reasons.',
55
    ];
56
57
    /**
58
     * This is not the final clauses. There will normally be conditions for the
59
     * hidden, starttime and endtime fields as well. You MUST initialize the object
60
     * by the init() function
61
     *
62
     * @var string
63
     */
64
    public $where_hid_del = ' AND pages.deleted=0';
65
66
    /**
67
     * Clause for fe_group access
68
     *
69
     * @var string
70
     */
71
    public $where_groupAccess = '';
72
73
    /**
74
     * @var int
75
     */
76
    public $sys_language_uid = 0;
77
78
    /**
79
     * If TRUE, versioning preview of other record versions is allowed. THIS MUST
80
     * ONLY BE SET IF the page is not cached and truly previewed by a backend
81
     * user!!!
82
     *
83
     * @var bool
84
     */
85
    public $versioningPreview = false;
86
87
    /**
88
     * Workspace ID for preview
89
     *
90
     * @var int
91
     */
92
    public $versioningWorkspaceId = 0;
93
94
    /**
95
     * @var array
96
     */
97
    protected $workspaceCache = [];
98
99
    /**
100
     * Error string set by getRootLine()
101
     *
102
     * @var string
103
     */
104
    protected $error_getRootLine = '';
105
106
    /**
107
     * Error uid set by getRootLine()
108
     *
109
     * @var int
110
     */
111
    protected $error_getRootLine_failPid = 0;
112
113
    /**
114
     * @var array
115
     */
116
    protected $cache_getPage = [];
117
118
    /**
119
     * @var array
120
     */
121
    protected $cache_getPage_noCheck = [];
122
123
    /**
124
     * @var array
125
     */
126
    protected $cache_getPageIdFromAlias = [];
127
128
    /**
129
     * @var array
130
     */
131
    protected $cache_getMountPointInfo = [];
132
133
    /**
134
     * @var array
135
     */
136
    protected $tableNamesAllowedOnRootLevel = [
137
        'sys_file_metadata',
138
        'sys_category',
139
    ];
140
141
    /**
142
     * Computed properties that are added to database rows.
143
     *
144
     * @var array
145
     */
146
    protected $computedPropertyNames = [
147
        '_LOCALIZED_UID',
148
        '_MP_PARAM',
149
        '_ORIG_uid',
150
        '_ORIG_pid',
151
        '_PAGES_OVERLAY',
152
        '_PAGES_OVERLAY_UID',
153
        '_PAGES_OVERLAY_LANGUAGE',
154
    ];
155
156
    /**
157
     * Named constants for "magic numbers" of the field doktype
158
     */
159
    const DOKTYPE_DEFAULT = 1;
160
    const DOKTYPE_LINK = 3;
161
    const DOKTYPE_SHORTCUT = 4;
162
    const DOKTYPE_BE_USER_SECTION = 6;
163
    const DOKTYPE_MOUNTPOINT = 7;
164
    const DOKTYPE_SPACER = 199;
165
    const DOKTYPE_SYSFOLDER = 254;
166
    const DOKTYPE_RECYCLER = 255;
167
168
    /**
169
     * Named constants for "magic numbers" of the field shortcut_mode
170
     */
171
    const SHORTCUT_MODE_NONE = 0;
172
    const SHORTCUT_MODE_FIRST_SUBPAGE = 1;
173
    const SHORTCUT_MODE_RANDOM_SUBPAGE = 2;
174
    const SHORTCUT_MODE_PARENT_PAGE = 3;
175
176
    /**
177
     * init() MUST be run directly after creating a new template-object
178
     * This sets the internal variable $this->where_hid_del to the correct where
179
     * clause for page records taking deleted/hidden/starttime/endtime/t3ver_state
180
     * into account
181
     *
182
     * @param bool $show_hidden If $show_hidden is TRUE, the hidden-field is ignored!! Normally this should be FALSE. Is used for previewing.
183
     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::fetch_the_id(), \TYPO3\CMS\Tstemplate\Controller\TemplateAnalyzerModuleFunctionController::initialize_editor()
184
     */
185
    public function init($show_hidden)
186
    {
187
        $this->where_groupAccess = '';
188
189
        if ($this->versioningPreview) {
190
            // For version previewing, make sure that enable-fields are not
191
            // de-selecting hidden pages - we need versionOL() to unset them only
192
            // if the overlay record instructs us to.
193
            // Clear where_hid_del and restrict to live and current workspaces
194
            $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
195
                ->getQueryBuilderForTable('pages')
196
                ->expr();
197
            $this->where_hid_del = ' AND ' . $expressionBuilder->andX(
198
                $expressionBuilder->eq('pages.deleted', 0),
199
                $expressionBuilder->orX(
200
                    $expressionBuilder->eq('pages.t3ver_wsid', 0),
201
                    $expressionBuilder->eq('pages.t3ver_wsid', (int)$this->versioningWorkspaceId)
202
                )
203
            );
204
        } else {
205
            // add starttime / endtime, and check for hidden/deleted
206
            // Filter out new/deleted place-holder pages in case we are NOT in a
207
            // versioning preview (that means we are online!)
208
            $this->where_hid_del = $this->enableFields('pages', $show_hidden, ['fe_group' => true], true);
0 ignored issues
show
Bug introduced by
$show_hidden of type boolean is incompatible with the type integer expected by parameter $show_hidden of TYPO3\CMS\Frontend\Page\...ository::enableFields(). ( Ignorable by Annotation )

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

208
            $this->where_hid_del = $this->enableFields('pages', /** @scrutinizer ignore-type */ $show_hidden, ['fe_group' => true], true);
Loading history...
209
        }
210
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['init'])) {
211
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['init'] as $classRef) {
212
                $hookObject = GeneralUtility::makeInstance($classRef);
213
                if (!$hookObject instanceof PageRepositoryInitHookInterface) {
214
                    throw new \UnexpectedValueException($classRef . ' must implement interface ' . PageRepositoryInitHookInterface::class, 1379579812);
215
                }
216
                $hookObject->init_postProcess($this);
217
            }
218
        }
219
    }
220
221
    /**************************
222
     *
223
     * Selecting page records
224
     *
225
     **************************/
226
227
    /**
228
     * Loads the full page record for the given page ID.
229
     *
230
     * The page record is either served from a first-level cache or loaded from the
231
     * database. If no page can be found, an empty array is returned.
232
     *
233
     * Language overlay and versioning overlay are applied. Mount Point
234
     * handling is not done, an overlaid Mount Point is not replaced.
235
     *
236
     * The result is conditioned by the public properties where_groupAccess
237
     * and where_hid_del that are preset by the init() method.
238
     *
239
     * @see PageRepository::where_groupAccess
240
     * @see PageRepository::where_hid_del
241
     * @see PageRepository::init()
242
     *
243
     * By default the usergroup access check is enabled. Use the second method argument
244
     * to disable the usergroup access check.
245
     *
246
     * The given UID can be preprocessed by registering a hook class that is
247
     * implementing the PageRepositoryGetPageHookInterface into the configuration array
248
     * $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPage'].
249
     *
250
     * @param int $uid The page id to look up
251
     * @param bool $disableGroupAccessCheck set to true to disable group access check
252
     * @return array The resulting page record with overlays or empty array
253
     * @throws \UnexpectedValueException
254
     * @see PageRepository::getPage_noCheck()
255
     */
256
    public function getPage($uid, $disableGroupAccessCheck = false)
257
    {
258
        // Hook to manipulate the page uid for special overlay handling
259
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPage'] ?? [] as $className) {
260
            $hookObject = GeneralUtility::makeInstance($className);
261
            if (!$hookObject instanceof PageRepositoryGetPageHookInterface) {
262
                throw new \UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetPageHookInterface::class, 1251476766);
263
            }
264
            $hookObject->getPage_preProcess($uid, $disableGroupAccessCheck, $this);
265
        }
266
        $cacheKey = md5(
267
            implode(
268
                '-',
269
                [
270
                    ($disableGroupAccessCheck ? '' : $this->where_groupAccess),
271
                    $this->where_hid_del,
272
                    $this->sys_language_uid
273
                ]
274
            )
275
        );
276
        if (is_array($this->cache_getPage[$uid][$cacheKey])) {
277
            return $this->cache_getPage[$uid][$cacheKey];
278
        }
279
        $result = [];
280
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
281
        $queryBuilder->getRestrictions()->removeAll();
282
        $queryBuilder->select('*')
283
            ->from('pages')
284
            ->where(
285
                $queryBuilder->expr()->eq('uid', (int)$uid),
286
                QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del)
287
            );
288
289
        if (!$disableGroupAccessCheck) {
290
            $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess));
291
        }
292
293
        $row = $queryBuilder->execute()->fetch();
294
        if ($row) {
295
            $this->versionOL('pages', $row);
296
            if (is_array($row)) {
297
                $result = $this->getPageOverlay($row);
298
            }
299
        }
300
        $this->cache_getPage[$uid][$cacheKey] = $result;
301
        return $result;
302
    }
303
304
    /**
305
     * Return the $row for the page with uid = $uid WITHOUT checking for
306
     * ->where_hid_del (start- and endtime or hidden). Only "deleted" is checked!
307
     *
308
     * @param int $uid The page id to look up
309
     * @return array The page row with overlaid localized fields. Empty array if no page.
310
     * @see getPage()
311
     */
312
    public function getPage_noCheck($uid)
313
    {
314
        if ($this->cache_getPage_noCheck[$uid]) {
315
            return $this->cache_getPage_noCheck[$uid];
316
        }
317
318
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
319
        $queryBuilder->getRestrictions()
320
            ->removeAll()
321
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
322
        $row = $queryBuilder->select('*')
323
            ->from('pages')
324
            ->where($queryBuilder->expr()->eq('uid', (int)$uid))
325
            ->execute()
326
            ->fetch();
327
328
        $result = [];
329
        if ($row) {
330
            $this->versionOL('pages', $row);
331
            if (is_array($row)) {
332
                $result = $this->getPageOverlay($row);
333
            }
334
        }
335
        $this->cache_getPage_noCheck[$uid] = $result;
336
        return $result;
337
    }
338
339
    /**
340
     * Returns the $row of the first web-page in the tree (for the default menu...)
341
     *
342
     * @param int $uid The page id for which to fetch first subpages (PID)
343
     * @return mixed If found: The page record (with overlaid localized fields, if any). If NOT found: blank value (not array!)
344
     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::fetch_the_id()
345
     */
346
    public function getFirstWebPage($uid)
347
    {
348
        $output = '';
349
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
350
        $queryBuilder->getRestrictions()->removeAll();
351
        $row = $queryBuilder->select('*')
352
            ->from('pages')
353
            ->where(
354
                $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)),
355
                QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del),
356
                QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess)
357
            )
358
            ->orderBy('sorting')
359
            ->setMaxResults(1)
360
            ->execute()
361
            ->fetch();
362
363
        if ($row) {
364
            $this->versionOL('pages', $row);
365
            if (is_array($row)) {
366
                $output = $this->getPageOverlay($row);
367
            }
368
        }
369
        return $output;
370
    }
371
372
    /**
373
     * Returns a pagerow for the page with alias $alias
374
     *
375
     * @param string $alias The alias to look up the page uid for.
376
     * @return int Returns page uid (int) if found, otherwise 0 (zero)
377
     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::checkAndSetAlias(), ContentObjectRenderer::typoLink()
378
     */
379
    public function getPageIdFromAlias($alias)
380
    {
381
        $alias = strtolower($alias);
382
        if ($this->cache_getPageIdFromAlias[$alias]) {
383
            return $this->cache_getPageIdFromAlias[$alias];
384
        }
385
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
386
        $queryBuilder->getRestrictions()
387
            ->removeAll()
388
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
389
390
        $row = $queryBuilder->select('uid')
391
            ->from('pages')
392
            ->where(
393
                $queryBuilder->expr()->eq('alias', $queryBuilder->createNamedParameter($alias, \PDO::PARAM_STR)),
394
                // "AND pid>=0" because of versioning (means that aliases sent MUST be online!)
395
                $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
396
            )
397
            ->setMaxResults(1)
398
            ->execute()
399
            ->fetch();
400
401
        if ($row) {
402
            $this->cache_getPageIdFromAlias[$alias] = $row['uid'];
403
            return $row['uid'];
404
        }
405
        $this->cache_getPageIdFromAlias[$alias] = 0;
406
        return 0;
407
    }
408
409
    /**
410
     * Returns the relevant page overlay record fields
411
     *
412
     * @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.
413
     * @param int $lUid Language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
414
     * @throws \UnexpectedValueException
415
     * @return array Page row which is overlaid with language_overlay record (or the overlay record alone)
416
     */
417
    public function getPageOverlay($pageInput, $lUid = -1)
418
    {
419
        $rows = $this->getPagesOverlay([$pageInput], $lUid);
420
        // Always an array in return
421
        return $rows[0] ?? [];
422
    }
423
424
    /**
425
     * Returns the relevant page overlay record fields
426
     *
427
     * @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.
428
     * @param int $lUid Language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
429
     * @throws \UnexpectedValueException
430
     * @return array Page rows which are overlaid with language_overlay record.
431
     *               If the input was an array of integers, missing records are not
432
     *               included. If the input were page rows, untranslated pages
433
     *               are returned.
434
     */
435
    public function getPagesOverlay(array $pagesInput, $lUid = -1)
436
    {
437
        if (empty($pagesInput)) {
438
            return [];
439
        }
440
        // Initialize:
441
        if ($lUid < 0) {
442
            $lUid = $this->sys_language_uid;
443
        }
444
        $row = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $row is dead and can be removed.
Loading history...
445
        foreach ($pagesInput as &$origPage) {
446
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPageOverlay'] ?? [] as $className) {
447
                $hookObject = GeneralUtility::makeInstance($className);
448
                if (!$hookObject instanceof PageRepositoryGetPageOverlayHookInterface) {
449
                    throw new \UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetPageOverlayHookInterface::class, 1269878881);
450
                }
451
                $hookObject->getPageOverlay_preProcess($origPage, $lUid, $this);
452
            }
453
        }
454
        unset($origPage);
455
        // If language UID is different from zero, do overlay:
456
        if ($lUid) {
457
            $page_ids = [];
458
459
            $origPage = reset($pagesInput);
460
            foreach ($pagesInput as $origPage) {
461
                if (is_array($origPage)) {
462
                    // Was the whole record
463
                    $page_ids[] = $origPage['uid'];
464
                } else {
465
                    // Was the id
466
                    $page_ids[] = $origPage;
467
                }
468
            }
469
            // NOTE regarding the query restrictions
470
            // Currently the showHiddenRecords of TSFE set will allow
471
            // page translation records to be selected as they are
472
            // child-records of a page.
473
            // However you may argue that the showHiddenField flag should
474
            // determine this. But that's not how it's done right now.
475
            // Selecting overlay record:
476
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
477
                ->getQueryBuilderForTable('pages');
478
            $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
479
            $result = $queryBuilder->select('*')
480
                ->from('pages')
481
                ->where(
482
                    $queryBuilder->expr()->in(
483
                        $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'],
484
                        $queryBuilder->createNamedParameter($page_ids, Connection::PARAM_INT_ARRAY)
485
                    ),
486
                    $queryBuilder->expr()->eq(
487
                        $GLOBALS['TCA']['pages']['ctrl']['languageField'],
488
                        $queryBuilder->createNamedParameter($lUid, \PDO::PARAM_INT)
489
                    )
490
                )
491
                ->execute();
492
493
            $overlays = [];
494
            while ($row = $result->fetch()) {
495
                $this->versionOL('pages', $row);
496
                if (is_array($row)) {
497
                    $row['_PAGES_OVERLAY'] = true;
498
                    $row['_PAGES_OVERLAY_UID'] = $row['uid'];
499
                    $row['_PAGES_OVERLAY_LANGUAGE'] = $lUid;
500
                    $origUid = $row[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']];
501
                    // Unset vital fields that are NOT allowed to be overlaid:
502
                    unset($row['uid']);
503
                    unset($row['pid']);
504
                    $overlays[$origUid] = $row;
505
                }
506
            }
507
        }
508
        // Create output:
509
        $pagesOutput = [];
510
        foreach ($pagesInput as $key => $origPage) {
511
            if (is_array($origPage)) {
512
                $pagesOutput[$key] = $origPage;
513
                if (isset($overlays[$origPage['uid']])) {
514
                    // Overwrite the original field with the overlay
515
                    foreach ($overlays[$origPage['uid']] as $fieldName => $fieldValue) {
516
                        if ($fieldName !== 'uid' && $fieldName !== 'pid') {
517
                            $pagesOutput[$key][$fieldName] = $fieldValue;
518
                        }
519
                    }
520
                }
521
            } else {
522
                if (isset($overlays[$origPage])) {
523
                    $pagesOutput[$key] = $overlays[$origPage];
524
                }
525
            }
526
        }
527
        return $pagesOutput;
528
    }
529
530
    /**
531
     * Creates language-overlay for records in general (where translation is found
532
     * in records from the same table)
533
     *
534
     * @param string $table Table name
535
     * @param array $row Record to overlay. Must contain uid, pid and $table]['ctrl']['languageField']
536
     * @param int $sys_language_content Pointer to the sys_language uid for content on the site.
537
     * @param string $OLmode Overlay mode. If "hideNonTranslated" then records without translation will not be returned  un-translated but unset (and return value is FALSE)
538
     * @throws \UnexpectedValueException
539
     * @return mixed Returns the input record, possibly overlaid with a translation.  But if $OLmode is "hideNonTranslated" then it will return FALSE if no translation is found.
540
     */
541
    public function getRecordOverlay($table, $row, $sys_language_content, $OLmode = '')
542
    {
543
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'] ?? [] as $className) {
544
            $hookObject = GeneralUtility::makeInstance($className);
545
            if (!$hookObject instanceof PageRepositoryGetRecordOverlayHookInterface) {
546
                throw new \UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetRecordOverlayHookInterface::class, 1269881658);
547
            }
548
            $hookObject->getRecordOverlay_preProcess($table, $row, $sys_language_content, $OLmode, $this);
549
        }
550
        if ($row['uid'] > 0 && ($row['pid'] > 0 || in_array($table, $this->tableNamesAllowedOnRootLevel, true))) {
551
            if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['languageField'] && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
552
                // Return record for ALL languages untouched
553
                // TODO: Fix call stack to prevent this situation in the first place
554
                if ((int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] !== -1) {
555
                    // Will not be able to work with other tables (Just didn't implement it yet;
556
                    // Requires a scan over all tables [ctrl] part for first FIND the table that
557
                    // carries localization information for this table (which could even be more
558
                    // than a single table) and then use that. Could be implemented, but obviously
559
                    // takes a little more....) Will try to overlay a record only if the
560
                    // sys_language_content value is larger than zero.
561
                    if ($sys_language_content > 0) {
562
                        // Must be default language, otherwise no overlaying
563
                        if ((int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] === 0) {
564
                            // Select overlay record:
565
                            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
566
                                ->getQueryBuilderForTable($table);
567
                            $queryBuilder->setRestrictions(
568
                                GeneralUtility::makeInstance(FrontendRestrictionContainer::class)
569
                            );
570
                            $olrow = $queryBuilder->select('*')
571
                                ->from($table)
572
                                ->where(
573
                                    $queryBuilder->expr()->eq(
574
                                        'pid',
575
                                        $queryBuilder->createNamedParameter($row['pid'], \PDO::PARAM_INT)
576
                                    ),
577
                                    $queryBuilder->expr()->eq(
578
                                        $GLOBALS['TCA'][$table]['ctrl']['languageField'],
579
                                        $queryBuilder->createNamedParameter($sys_language_content, \PDO::PARAM_INT)
580
                                    ),
581
                                    $queryBuilder->expr()->eq(
582
                                        $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
583
                                        $queryBuilder->createNamedParameter($row['uid'], \PDO::PARAM_INT)
584
                                    )
585
                                )
586
                                ->setMaxResults(1)
587
                                ->execute()
588
                                ->fetch();
589
590
                            $this->versionOL($table, $olrow);
591
                            // Merge record content by traversing all fields:
592
                            if (is_array($olrow)) {
593
                                if (isset($olrow['_ORIG_uid'])) {
594
                                    $row['_ORIG_uid'] = $olrow['_ORIG_uid'];
595
                                }
596
                                if (isset($olrow['_ORIG_pid'])) {
597
                                    $row['_ORIG_pid'] = $olrow['_ORIG_pid'];
598
                                }
599
                                foreach ($row as $fN => $fV) {
600
                                    if ($fN !== 'uid' && $fN !== 'pid' && isset($olrow[$fN])) {
601
                                        $row[$fN] = $olrow[$fN];
602
                                    } elseif ($fN === 'uid') {
603
                                        $row['_LOCALIZED_UID'] = $olrow['uid'];
604
                                    }
605
                                }
606
                            } elseif ($OLmode === 'hideNonTranslated' && (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] === 0) {
607
                                // Unset, if non-translated records should be hidden. ONLY done if the source
608
                                // record really is default language and not [All] in which case it is allowed.
609
                                unset($row);
610
                            }
611
                        } elseif ($sys_language_content != $row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]) {
612
                            unset($row);
613
                        }
614
                    } else {
615
                        // When default language is displayed, we never want to return a record carrying
616
                        // another language!
617
                        if ($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0) {
618
                            unset($row);
619
                        }
620
                    }
621
                }
622
            }
623
        }
624
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getRecordOverlay'] ?? [] as $className) {
625
            $hookObject = GeneralUtility::makeInstance($className);
626
            if (!$hookObject instanceof PageRepositoryGetRecordOverlayHookInterface) {
627
                throw new \UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetRecordOverlayHookInterface::class, 1269881659);
628
            }
629
            $hookObject->getRecordOverlay_postProcess($table, $row, $sys_language_content, $OLmode, $this);
630
        }
631
        return $row;
632
    }
633
634
    /************************************************
635
     *
636
     * Page related: Menu, Domain record, Root line
637
     *
638
     ************************************************/
639
640
    /**
641
     * Returns an array with page rows for subpages of a certain page ID. This is used for menus in the frontend.
642
     * If there are mount points in overlay mode the _MP_PARAM field is set to the correct MPvar.
643
     *
644
     * If the $pageId being input does in itself require MPvars to define a correct
645
     * rootline these must be handled externally to this function.
646
     *
647
     * @param int|int[] $pageId The page id (or array of page ids) for which to fetch subpages (PID)
648
     * @param string $fields List of fields to select. Default is "*" = all
649
     * @param string $sortField The field to sort by. Default is "sorting
650
     * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
651
     * @param bool $checkShortcuts Check if shortcuts exist, checks by default
652
     * @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlaid localized fields, if any)
653
     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getPageShortcut(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::makeMenu()
654
     */
655
    public function getMenu($pageId, $fields = '*', $sortField = 'sorting', $additionalWhereClause = '', $checkShortcuts = true)
656
    {
657
        return $this->getSubpagesForPages((array)$pageId, $fields, $sortField, $additionalWhereClause, $checkShortcuts);
658
    }
659
660
    /**
661
     * Returns an array with page-rows for pages with uid in $pageIds.
662
     *
663
     * This is used for menus. If there are mount points in overlay mode
664
     * the _MP_PARAM field is set to the correct MPvar.
665
     *
666
     * @param int[] $pageIds Array of page ids to fetch
667
     * @param string $fields List of fields to select. Default is "*" = all
668
     * @param string $sortField The field to sort by. Default is "sorting"
669
     * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
670
     * @param bool $checkShortcuts Check if shortcuts exist, checks by default
671
     * @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlaid localized fields, if any)
672
     */
673
    public function getMenuForPages(array $pageIds, $fields = '*', $sortField = 'sorting', $additionalWhereClause = '', $checkShortcuts = true)
674
    {
675
        return $this->getSubpagesForPages($pageIds, $fields, $sortField, $additionalWhereClause, $checkShortcuts, false);
676
    }
677
678
    /**
679
     * Loads page records either by PIDs or by UIDs.
680
     *
681
     * By default the subpages of the given page IDs are loaded (as the method name suggests). If $parentPages is set
682
     * to FALSE, the page records for the given page IDs are loaded directly.
683
     *
684
     * Concerning the rationale, please see these two other methods:
685
     *
686
     * @see PageRepository::getMenu()
687
     * @see PageRepository::getMenuForPages()
688
     *
689
     * Version and language overlay are applied to the loaded records.
690
     *
691
     * If a record is a mount point in overlay mode, the the overlaying page record is returned in place of the
692
     * record. The record is enriched by the field _MP_PARAM containing the mount point mapping for the mount
693
     * point.
694
     *
695
     * The query can be customized by setting fields, sorting and additional WHERE clauses. If additional WHERE
696
     * clauses are given, the clause must start with an operator, i.e: "AND title like '%blabla%'".
697
     *
698
     * The keys of the returned page records are the page UIDs.
699
     *
700
     * CAUTION: In case of an overlaid mount point, it is the original UID.
701
     *
702
     * @param int[] $pageIds PIDs or UIDs to load records for
703
     * @param string $fields fields to select
704
     * @param string $sortField the field to sort by
705
     * @param string $additionalWhereClause optional additional WHERE clause
706
     * @param bool $checkShortcuts whether to check if shortcuts exist
707
     * @param bool $parentPages Switch to load pages (false) or child pages (true).
708
     * @return array page records
709
     *
710
     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getPageShortcut()
711
     * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::makeMenu()
712
     */
713
    protected function getSubpagesForPages(
714
        array $pageIds,
715
        string $fields = '*',
716
        string $sortField = 'sorting',
717
        string $additionalWhereClause = '',
718
        bool $checkShortcuts = true,
719
        bool $parentPages = true
720
    ): array {
721
        $relationField = $parentPages ? 'pid' : 'uid';
722
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
723
        $queryBuilder->getRestrictions()->removeAll();
724
725
        $res = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
726
            ->from('pages')
727
            ->where(
728
                $queryBuilder->expr()->in(
729
                    $relationField,
730
                    $queryBuilder->createNamedParameter($pageIds, Connection::PARAM_INT_ARRAY)
731
                ),
732
                $queryBuilder->expr()->eq(
733
                    $GLOBALS['TCA']['pages']['ctrl']['languageField'],
734
                    $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
735
                ),
736
                QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del),
737
                QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess),
738
                QueryHelper::stripLogicalOperatorPrefix($additionalWhereClause)
739
            );
740
741
        if (!empty($sortField)) {
742
            $orderBy = QueryHelper::parseOrderBy($sortField);
743
            foreach ($orderBy as $order) {
744
                $res->orderBy(...$order);
745
            }
746
        }
747
        $result = $res->execute();
748
749
        $pages = [];
750
        while ($page = $result->fetch()) {
751
            $originalUid = $page['uid'];
752
753
            // Versioning Preview Overlay
754
            $this->versionOL('pages', $page, true);
755
            // Skip if page got disabled due to version overlay
756
            // (might be delete or move placeholder)
757
            if (empty($page)) {
758
                continue;
759
            }
760
761
            // Add a mount point parameter if needed
762
            $page = $this->addMountPointParameterToPage((array)$page);
763
764
            // If shortcut, look up if the target exists and is currently visible
765
            if ($checkShortcuts) {
766
                $page = $this->checkValidShortcutOfPage((array)$page, $additionalWhereClause);
767
            }
768
769
            // If the page still is there, we add it to the output
770
            if (!empty($page)) {
771
                $pages[$originalUid] = $page;
772
            }
773
        }
774
775
        // Finally load language overlays
776
        return $this->getPagesOverlay($pages);
777
    }
778
779
    /**
780
     * Replaces the given page record with mounted page if required
781
     *
782
     * If the given page record is a mount point in overlay mode, the page
783
     * record is replaced by the record of the overlaying page. The overlay
784
     * record is enriched by setting the mount point mapping into the field
785
     * _MP_PARAM as string for example '23-14'.
786
     *
787
     * In all other cases the given page record is returned as is.
788
     *
789
     * @todo Find a better name. The current doesn't hit the point.
790
     *
791
     * @param array $page The page record to handle.
792
     * @return array The given page record or it's replacement.
793
     */
794
    protected function addMountPointParameterToPage(array $page): array
795
    {
796
        if (empty($page)) {
797
            return [];
798
        }
799
800
        // $page MUST have "uid", "pid", "doktype", "mount_pid", "mount_pid_ol" fields in it
801
        $mountPointInfo = $this->getMountPointInfo($page['uid'], $page);
802
803
        // There is a valid mount point in overlay mode.
804
        if (is_array($mountPointInfo) && $mountPointInfo['overlay']) {
805
806
            // Using "getPage" is OK since we need the check for enableFields AND for type 2
807
            // of mount pids we DO require a doktype < 200!
808
            $mountPointPage = $this->getPage($mountPointInfo['mount_pid']);
809
810
            if (!empty($mountPointPage)) {
811
                $page = $mountPointPage;
812
                $page['_MP_PARAM'] = $mountPointInfo['MPvar'];
813
            } else {
814
                $page = [];
815
            }
816
        }
817
        return $page;
818
    }
819
820
    /**
821
     * If shortcut, look up if the target exists and is currently visible
822
     *
823
     * @param array $page The page to check
824
     * @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%blabla%'" for instance.
825
     * @return array
826
     */
827
    protected function checkValidShortcutOfPage(array $page, $additionalWhereClause)
828
    {
829
        if (empty($page)) {
830
            return [];
831
        }
832
833
        $dokType = (int)$page['doktype'];
834
        $shortcutMode = (int)$page['shortcut_mode'];
835
836
        if ($dokType === self::DOKTYPE_SHORTCUT && ($page['shortcut'] || $shortcutMode)) {
837
            if ($shortcutMode === self::SHORTCUT_MODE_NONE) {
838
                // No shortcut_mode set, so target is directly set in $page['shortcut']
839
                $searchField = 'uid';
840
                $searchUid = (int)$page['shortcut'];
841
            } elseif ($shortcutMode === self::SHORTCUT_MODE_FIRST_SUBPAGE || $shortcutMode === self::SHORTCUT_MODE_RANDOM_SUBPAGE) {
842
                // Check subpages - first subpage or random subpage
843
                $searchField = 'pid';
844
                // If a shortcut mode is set and no valid page is given to select subpags
845
                // from use the actual page.
846
                $searchUid = (int)$page['shortcut'] ?: $page['uid'];
847
            } elseif ($shortcutMode === self::SHORTCUT_MODE_PARENT_PAGE) {
848
                // Shortcut to parent page
849
                $searchField = 'uid';
850
                $searchUid = $page['pid'];
851
            } else {
852
                $searchField = '';
853
                $searchUid = 0;
854
            }
855
856
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
857
            $queryBuilder->getRestrictions()->removeAll();
858
            $count = $queryBuilder->count('uid')
859
                ->from('pages')
860
                ->where(
861
                    $queryBuilder->expr()->eq(
862
                        $searchField,
863
                        $queryBuilder->createNamedParameter($searchUid, \PDO::PARAM_INT)
864
                    ),
865
                    QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del),
866
                    QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess),
867
                    QueryHelper::stripLogicalOperatorPrefix($additionalWhereClause)
868
                )
869
                ->execute()
870
                ->fetchColumn();
871
872
            if (!$count) {
873
                $page = [];
874
            }
875
        } elseif ($dokType === self::DOKTYPE_SHORTCUT) {
876
            // Neither shortcut target nor mode is set. Remove the page from the menu.
877
            $page = [];
878
        }
879
        return $page;
880
    }
881
    /**
882
     * Will find the page carrying the domain record matching the input domain.
883
     * Might exit after sending a redirect-header IF a found domain record
884
     * instructs to do so.
885
     *
886
     * @param string $domain Domain name to search for. Eg. "www.typo3.com". Typical the HTTP_HOST value.
887
     * @param string $path Path for the current script in domain. Eg. "/somedir/subdir". Typ. supplied by \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('SCRIPT_NAME')
888
     * @param string $request_uri Request URI: Used to get parameters from if they should be appended. Typ. supplied by \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('REQUEST_URI')
889
     * @return mixed If found, returns integer with page UID where found. Otherwise blank. Might exit if location-header is sent, see description.
890
     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::findDomainRecord()
891
     */
892
    public function getDomainStartPage($domain, $path = '', $request_uri = '')
893
    {
894
        $domain = explode(':', $domain);
895
        $domain = strtolower(preg_replace('/\\.$/', '', $domain[0]));
896
        // Removing extra trailing slashes
897
        $path = trim(preg_replace('/\\/[^\\/]*$/', '', $path));
898
        // Appending to domain string
899
        $domain .= $path;
900
        $domain = preg_replace('/\\/*$/', '', $domain);
901
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
902
        $queryBuilder->getRestrictions()->removeAll();
903
        $row = $queryBuilder
904
            ->select(
905
                'pages.uid',
906
                'sys_domain.redirectTo',
907
                'sys_domain.redirectHttpStatusCode',
908
                'sys_domain.prepend_params'
909
            )
910
            ->from('pages')
911
            ->from('sys_domain')
912
            ->where(
913
                $queryBuilder->expr()->eq('pages.uid', $queryBuilder->quoteIdentifier('sys_domain.pid')),
914
                $queryBuilder->expr()->eq(
915
                    'sys_domain.hidden',
916
                    $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
917
                ),
918
                $queryBuilder->expr()->orX(
919
                    $queryBuilder->expr()->eq(
920
                        'sys_domain.domainName',
921
                        $queryBuilder->createNamedParameter($domain, \PDO::PARAM_STR)
922
                    ),
923
                    $queryBuilder->expr()->eq(
924
                        'sys_domain.domainName',
925
                        $queryBuilder->createNamedParameter($domain . '/', \PDO::PARAM_STR)
926
                    )
927
                ),
928
                QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del),
929
                QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess)
930
            )
931
            ->setMaxResults(1)
932
            ->execute()
933
            ->fetch();
934
935
        if (!$row) {
936
            return '';
937
        }
938
939
        if ($row['redirectTo']) {
940
            $redirectUrl = $row['redirectTo'];
941
            if ($row['prepend_params']) {
942
                $redirectUrl = rtrim($redirectUrl, '/');
943
                $prependStr = ltrim(substr($request_uri, strlen($path)), '/');
944
                $redirectUrl .= '/' . $prependStr;
945
            }
946
            $statusCode = (int)$row['redirectHttpStatusCode'];
947
            if ($statusCode && defined(HttpUtility::class . '::HTTP_STATUS_' . $statusCode)) {
948
                HttpUtility::redirect($redirectUrl, constant(HttpUtility::class . '::HTTP_STATUS_' . $statusCode));
949
            } else {
950
                HttpUtility::redirect($redirectUrl, HttpUtility::HTTP_STATUS_301);
951
            }
952
            die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
953
        }
954
        return $row['uid'];
955
    }
956
957
    /**
958
     * Returns array with fields of the pages from here ($uid) and back to the root
959
     *
960
     * NOTICE: This function only takes deleted pages into account! So hidden,
961
     * starttime and endtime restricted pages are included no matter what.
962
     *
963
     * Further: If any "recycler" page is found (doktype=255) then it will also block
964
     * for the rootline)
965
     *
966
     * If you want more fields in the rootline records than default such can be added
967
     * by listing them in $GLOBALS['TYPO3_CONF_VARS']['FE']['addRootLineFields']
968
     *
969
     * @param int $uid The page uid for which to seek back to the page tree root.
970
     * @param string $MP Commalist of MountPoint parameters, eg. "1-2,3-4" etc. Normally this value comes from the GET var, MP
971
     * @param bool $ignoreMPerrors If set, some errors related to Mount Points in root line are ignored.
972
     * @throws \Exception
973
     * @throws \RuntimeException
974
     * @return array Array with page records from the root line as values. The array is ordered with the outer records first and root record in the bottom. The keys are numeric but in reverse order. So if you traverse/sort the array by the numeric keys order you will get the order from root and out. If an error is found (like eternal looping or invalid mountpoint) it will return an empty array.
975
     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getPageAndRootline()
976
     */
977
    public function getRootLine($uid, $MP = '', $ignoreMPerrors = false)
978
    {
979
        $rootline = GeneralUtility::makeInstance(RootlineUtility::class, $uid, $MP, $this);
0 ignored issues
show
Bug introduced by
$MP of type string is incompatible with the type array<integer,mixed> expected by parameter $constructorArguments of TYPO3\CMS\Core\Utility\G...Utility::makeInstance(). ( Ignorable by Annotation )

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

979
        $rootline = GeneralUtility::makeInstance(RootlineUtility::class, $uid, /** @scrutinizer ignore-type */ $MP, $this);
Loading history...
Bug introduced by
$this of type TYPO3\CMS\Frontend\Page\PageRepository is incompatible with the type array<integer,mixed> expected by parameter $constructorArguments of TYPO3\CMS\Core\Utility\G...Utility::makeInstance(). ( Ignorable by Annotation )

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

979
        $rootline = GeneralUtility::makeInstance(RootlineUtility::class, $uid, $MP, /** @scrutinizer ignore-type */ $this);
Loading history...
Bug introduced by
$uid of type integer is incompatible with the type array<integer,mixed> expected by parameter $constructorArguments of TYPO3\CMS\Core\Utility\G...Utility::makeInstance(). ( Ignorable by Annotation )

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

979
        $rootline = GeneralUtility::makeInstance(RootlineUtility::class, /** @scrutinizer ignore-type */ $uid, $MP, $this);
Loading history...
980
        try {
981
            return $rootline->get();
982
        } catch (\RuntimeException $ex) {
983
            if ($ignoreMPerrors) {
984
                $this->error_getRootLine = $ex->getMessage();
985
                if (substr($this->error_getRootLine, -7) === 'uid -1.') {
986
                    $this->error_getRootLine_failPid = -1;
987
                }
988
                return [];
989
            }
990
            if ($ex->getCode() === 1343589451) {
991
                /** @see \TYPO3\CMS\Core\Utility\RootlineUtility::getRecordArray */
992
                return [];
993
            }
994
            throw $ex;
995
        }
996
    }
997
998
    /**
999
     * Returns the redirect URL for the input page row IF the doktype is set to 3.
1000
     *
1001
     * @param array $pagerow The page row to return URL type for
1002
     * @return string|bool The URL from based on the data from "pages:url". False if not found.
1003
     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::initializeRedirectUrlHandlers()
1004
     */
1005
    public function getExtURL($pagerow)
1006
    {
1007
        if ((int)$pagerow['doktype'] === self::DOKTYPE_LINK) {
1008
            $redirectTo = $pagerow['url'];
1009
            $uI = parse_url($redirectTo);
1010
            // If relative path, prefix Site URL
1011
            // If it's a valid email without protocol, add "mailto:"
1012
            if (!$uI['scheme']) {
1013
                if (GeneralUtility::validEmail($redirectTo)) {
1014
                    $redirectTo = 'mailto:' . $redirectTo;
1015
                } elseif ($redirectTo[0] !== '/') {
1016
                    $redirectTo = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . $redirectTo;
1017
                }
1018
            }
1019
            return $redirectTo;
1020
        }
1021
        return false;
1022
    }
1023
1024
    /**
1025
     * Returns a MountPoint array for the specified page
1026
     *
1027
     * Does a recursive search if the mounted page should be a mount page
1028
     * itself.
1029
     *
1030
     * Note:
1031
     *
1032
     * Recursive mount points are not supported by all parts of the core.
1033
     * The usage is discouraged. They may be removed from this method.
1034
     *
1035
     * @see: https://decisions.typo3.org/t/supporting-or-prohibiting-recursive-mount-points/165/3
1036
     *
1037
     * An array will be returned if mount pages are enabled, the correct
1038
     * doktype (7) is set for page and there IS a mount_pid with a valid
1039
     * record.
1040
     *
1041
     * The optional page record must contain at least uid, pid, doktype,
1042
     * mount_pid,mount_pid_ol. If it is not supplied it will be looked up by
1043
     * the system at additional costs for the lookup.
1044
     *
1045
     * Returns FALSE if no mount point was found, "-1" if there should have been
1046
     * one, but no connection to it, otherwise an array with information
1047
     * about mount pid and modes.
1048
     *
1049
     * @param int $pageId Page id to do the lookup for.
1050
     * @param array|bool $pageRec Optional page record for the given page.
1051
     * @param array $prevMountPids Internal register to prevent lookup cycles.
1052
     * @param int $firstPageUid The first page id.
1053
     * @return mixed Mount point array or failure flags (-1, false).
1054
     * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
1055
     */
1056
    public function getMountPointInfo($pageId, $pageRec = false, $prevMountPids = [], $firstPageUid = 0)
1057
    {
1058
        $result = false;
1059
        if ($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
1060
            if (isset($this->cache_getMountPointInfo[$pageId])) {
1061
                return $this->cache_getMountPointInfo[$pageId];
1062
            }
1063
            // Get pageRec if not supplied:
1064
            if (!is_array($pageRec)) {
1065
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1066
                $queryBuilder->getRestrictions()
1067
                    ->removeAll()
1068
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1069
1070
                $pageRec = $queryBuilder->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol', 't3ver_state')
1071
                    ->from('pages')
1072
                    ->where(
1073
                        $queryBuilder->expr()->eq(
1074
                            'uid',
1075
                            $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT)
1076
                        ),
1077
                        $queryBuilder->expr()->neq(
1078
                            'doktype',
1079
                            $queryBuilder->createNamedParameter(255, \PDO::PARAM_INT)
1080
                        )
1081
                    )
1082
                    ->execute()
1083
                    ->fetch();
1084
1085
                // Only look for version overlay if page record is not supplied; This assumes
1086
                // that the input record is overlaid with preview version, if any!
1087
                $this->versionOL('pages', $pageRec);
1088
            }
1089
            // Set first Page uid:
1090
            if (!$firstPageUid) {
1091
                $firstPageUid = $pageRec['uid'];
1092
            }
1093
            // Look for mount pid value plus other required circumstances:
1094
            $mount_pid = (int)$pageRec['mount_pid'];
1095
            if (is_array($pageRec) && (int)$pageRec['doktype'] === self::DOKTYPE_MOUNTPOINT && $mount_pid > 0 && !in_array($mount_pid, $prevMountPids, true)) {
1096
                // Get the mount point record (to verify its general existence):
1097
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1098
                $queryBuilder->getRestrictions()
1099
                    ->removeAll()
1100
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1101
1102
                $mountRec = $queryBuilder->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol', 't3ver_state')
1103
                    ->from('pages')
1104
                    ->where(
1105
                        $queryBuilder->expr()->eq(
1106
                            'uid',
1107
                            $queryBuilder->createNamedParameter($mount_pid, \PDO::PARAM_INT)
1108
                        ),
1109
                        $queryBuilder->expr()->neq(
1110
                            'doktype',
1111
                            $queryBuilder->createNamedParameter(255, \PDO::PARAM_INT)
1112
                        )
1113
                    )
1114
                    ->execute()
1115
                    ->fetch();
1116
1117
                $this->versionOL('pages', $mountRec);
1118
                if (is_array($mountRec)) {
1119
                    // Look for recursive mount point:
1120
                    $prevMountPids[] = $mount_pid;
1121
                    $recursiveMountPid = $this->getMountPointInfo($mount_pid, $mountRec, $prevMountPids, $firstPageUid);
1122
                    // Return mount point information:
1123
                    $result = $recursiveMountPid ?: [
1124
                        'mount_pid' => $mount_pid,
1125
                        'overlay' => $pageRec['mount_pid_ol'],
1126
                        'MPvar' => $mount_pid . '-' . $firstPageUid,
1127
                        'mount_point_rec' => $pageRec,
1128
                        'mount_pid_rec' => $mountRec
1129
                    ];
1130
                } else {
1131
                    // Means, there SHOULD have been a mount point, but there was none!
1132
                    $result = -1;
1133
                }
1134
            }
1135
        }
1136
        $this->cache_getMountPointInfo[$pageId] = $result;
1137
        return $result;
1138
    }
1139
1140
    /********************************
1141
     *
1142
     * Selecting records in general
1143
     *
1144
     ********************************/
1145
1146
    /**
1147
     * Checks if a record exists and is accessible.
1148
     * The row is returned if everything's OK.
1149
     *
1150
     * @param string $table The table name to search
1151
     * @param int $uid The uid to look up in $table
1152
     * @param bool|int $checkPage If checkPage is set, it's also required that the page on which the record resides is accessible
1153
     * @return array|int Returns array (the record) if OK, otherwise blank/0 (zero)
1154
     */
1155
    public function checkRecord($table, $uid, $checkPage = 0)
1156
    {
1157
        $uid = (int)$uid;
1158
        if (is_array($GLOBALS['TCA'][$table]) && $uid > 0) {
1159
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1160
            $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1161
            $row = $queryBuilder->select('*')
1162
                ->from($table)
1163
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)))
1164
                ->execute()
1165
                ->fetch();
1166
1167
            if ($row) {
1168
                $this->versionOL($table, $row);
1169
                if (is_array($row)) {
1170
                    if ($checkPage) {
1171
                        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1172
                            ->getQueryBuilderForTable('pages');
1173
                        $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1174
                        $numRows = (int)$queryBuilder->count('*')
1175
                            ->from('pages')
1176
                            ->where(
1177
                                $queryBuilder->expr()->eq(
1178
                                    'uid',
1179
                                    $queryBuilder->createNamedParameter($row['pid'], \PDO::PARAM_INT)
1180
                                )
1181
                            )
1182
                            ->execute()
1183
                            ->fetchColumn();
1184
                        if ($numRows > 0) {
1185
                            return $row;
1186
                        }
1187
                        return 0;
1188
                    }
1189
                    return $row;
1190
                }
1191
            }
1192
        }
1193
        return 0;
1194
    }
1195
1196
    /**
1197
     * Returns record no matter what - except if record is deleted
1198
     *
1199
     * @param string $table The table name to search
1200
     * @param int $uid The uid to look up in $table
1201
     * @param string $fields The fields to select, default is "*
1202
     * @param bool $noWSOL If set, no version overlay is applied
1203
     * @return mixed Returns array (the record) if found, otherwise blank/0 (zero)
1204
     * @see getPage_noCheck()
1205
     */
1206
    public function getRawRecord($table, $uid, $fields = '*', $noWSOL = null)
1207
    {
1208
        $uid = (int)$uid;
1209
        if (isset($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]) && $uid > 0) {
1210
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1211
            $queryBuilder->getRestrictions()
1212
                ->removeAll()
1213
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1214
            $row = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
1215
                ->from($table)
1216
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)))
1217
                ->execute()
1218
                ->fetch();
1219
1220
            if ($row) {
1221
                if ($noWSOL !== null) {
1222
                    trigger_error('The fourth parameter of PageRepository->getRawRecord() has been deprecated, use a SQL statement directly. The parameter will be removed in TYPO3 v10.', E_USER_DEPRECATED);
1223
                }
1224
                // @deprecated - remove this if-clause in TYPO3 v10
1225
                if (!$noWSOL) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $noWSOL of type null|boolean is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
1226
                    $this->versionOL($table, $row);
1227
                }
1228
                if (is_array($row)) {
1229
                    return $row;
1230
                }
1231
            }
1232
        }
1233
        return 0;
1234
    }
1235
1236
    /**
1237
     * Selects records based on matching a field (ei. other than UID) with a value
1238
     *
1239
     * @param string $theTable The table name to search, eg. "pages" or "tt_content
1240
     * @param string $theField The fieldname to match, eg. "uid" or "alias
1241
     * @param string $theValue The value that fieldname must match, eg. "123" or "frontpage
1242
     * @param string $whereClause Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
1243
     * @param string $groupBy Optional GROUP BY field(s). If none, supply blank string.
1244
     * @param string $orderBy Optional ORDER BY field(s). If none, supply blank string.
1245
     * @param string $limit Optional LIMIT value ([begin,]max). If none, supply blank string.
1246
     * @return mixed Returns array (the record) if found, otherwise nothing (void)
1247
     */
1248
    public function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '')
1249
    {
1250
        if (is_array($GLOBALS['TCA'][$theTable])) {
1251
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($theTable);
1252
            $queryBuilder->getRestrictions()
1253
                ->removeAll()
1254
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1255
1256
            $queryBuilder->select('*')
1257
                ->from($theTable)
1258
                ->where($queryBuilder->expr()->eq($theField, $queryBuilder->createNamedParameter($theValue)));
1259
1260
            if ($whereClause !== '') {
1261
                $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($whereClause));
1262
            }
1263
1264
            if ($groupBy !== '') {
1265
                $queryBuilder->groupBy(QueryHelper::parseGroupBy($groupBy));
1266
            }
1267
1268
            if ($orderBy !== '') {
1269
                foreach (QueryHelper::parseOrderBy($orderBy) as $orderPair) {
1270
                    list($fieldName, $order) = $orderPair;
1271
                    $queryBuilder->addOrderBy($fieldName, $order);
1272
                }
1273
            }
1274
1275
            if ($limit !== '') {
1276
                if (strpos($limit, ',')) {
1277
                    $limitOffsetAndMax = GeneralUtility::intExplode(',', $limit);
1278
                    $queryBuilder->setFirstResult((int)$limitOffsetAndMax[0]);
1279
                    $queryBuilder->setMaxResults((int)$limitOffsetAndMax[1]);
1280
                } else {
1281
                    $queryBuilder->setMaxResults((int)$limit);
1282
                }
1283
            }
1284
1285
            $rows = $queryBuilder->execute()->fetchAll();
1286
1287
            if (!empty($rows)) {
1288
                return $rows;
1289
            }
1290
        }
1291
        return null;
1292
    }
1293
1294
    /********************************
1295
     *
1296
     * Standard clauses
1297
     *
1298
     ********************************/
1299
1300
    /**
1301
     * Returns the "AND NOT deleted" clause for the tablename given IF
1302
     * $GLOBALS['TCA'] configuration points to such a field.
1303
     *
1304
     * @param string $table Tablename
1305
     * @return string
1306
     * @see enableFields()
1307
     * @deprecated since TYPO3 v9, will be removed in TYPO3 v10, use QueryBuilders' Restrictions directly instead.
1308
     */
1309
    public function deleteClause($table)
1310
    {
1311
        trigger_error('The delete clause can be applied via the DeletedRestrictions via QueryBuilder, this method will be removed in TYPO3 v10.0', E_USER_DEPRECATED);
1312
        return $GLOBALS['TCA'][$table]['ctrl']['delete'] ? ' AND ' . $table . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0' : '';
1313
    }
1314
1315
    /**
1316
     * Returns a part of a WHERE clause which will filter out records with start/end
1317
     * times or hidden/fe_groups fields set to values that should de-select them
1318
     * according to the current time, preview settings or user login. Definitely a
1319
     * frontend function.
1320
     *
1321
     * Is using the $GLOBALS['TCA'] arrays "ctrl" part where the key "enablefields"
1322
     * determines for each table which of these features applies to that table.
1323
     *
1324
     * @param string $table Table name found in the $GLOBALS['TCA'] array
1325
     * @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.
1326
     * @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.
1327
     * @param bool $noVersionPreview If set, enableFields will be applied regardless of any versioning preview settings which might otherwise disable enableFields
1328
     * @throws \InvalidArgumentException
1329
     * @return string The clause starting like " AND ...=... AND ...=...
1330
     * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::enableFields()
1331
     */
1332
    public function enableFields($table, $show_hidden = -1, $ignore_array = [], $noVersionPreview = false)
1333
    {
1334
        if ($show_hidden === -1 && is_object($this->getTypoScriptFrontendController())) {
1335
            // If show_hidden was not set from outside and if TSFE is an object, set it
1336
            // based on showHiddenPage and showHiddenRecords from TSFE
1337
            $show_hidden = $table === 'pages'
1338
                ? $this->getTypoScriptFrontendController()->showHiddenPage
1339
                : $this->getTypoScriptFrontendController()->showHiddenRecords;
1340
        }
1341
        if ($show_hidden === -1) {
1342
            $show_hidden = 0;
1343
        }
1344
        // If show_hidden was not changed during the previous evaluation, do it here.
1345
        $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
1346
        $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1347
            ->getQueryBuilderForTable($table)
1348
            ->expr();
1349
        $constraints = [];
1350
        if (is_array($ctrl)) {
1351
            // Delete field check:
1352
            if ($ctrl['delete']) {
1353
                $constraints[] = $expressionBuilder->eq($table . '.' . $ctrl['delete'], 0);
1354
            }
1355
            if ($ctrl['versioningWS']) {
1356
                if (!$this->versioningPreview) {
1357
                    // Filter out placeholder records (new/moved/deleted items)
1358
                    // in case we are NOT in a versioning preview (that means we are online!)
1359
                    $constraints[] = $expressionBuilder->lte(
1360
                        $table . '.t3ver_state',
1361
                        new VersionState(VersionState::DEFAULT_STATE)
1362
                    );
1363
                } elseif ($table !== 'pages') {
1364
                    // show only records of live and of the current workspace
1365
                    // in case we are in a versioning preview
1366
                    $constraints[] = $expressionBuilder->orX(
1367
                        $expressionBuilder->eq($table . '.t3ver_wsid', 0),
1368
                        $expressionBuilder->eq($table . '.t3ver_wsid', (int)$this->versioningWorkspaceId)
1369
                    );
1370
                }
1371
1372
                // Filter out versioned records
1373
                if (!$noVersionPreview && empty($ignore_array['pid'])) {
1374
                    $constraints[] = $expressionBuilder->neq($table . '.pid', -1);
1375
                }
1376
            }
1377
1378
            // Enable fields:
1379
            if (is_array($ctrl['enablecolumns'])) {
1380
                // In case of versioning-preview, enableFields are ignored (checked in
1381
                // versionOL())
1382
                if (!$this->versioningPreview || !$ctrl['versioningWS'] || $noVersionPreview) {
1383
                    if ($ctrl['enablecolumns']['disabled'] && !$show_hidden && !$ignore_array['disabled']) {
1384
                        $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
1385
                        $constraints[] = $expressionBuilder->eq($field, 0);
1386
                    }
1387
                    if ($ctrl['enablecolumns']['starttime'] && !$ignore_array['starttime']) {
1388
                        $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
1389
                        $constraints[] = $expressionBuilder->lte($field, (int)$GLOBALS['SIM_ACCESS_TIME']);
1390
                    }
1391
                    if ($ctrl['enablecolumns']['endtime'] && !$ignore_array['endtime']) {
1392
                        $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
1393
                        $constraints[] = $expressionBuilder->orX(
1394
                            $expressionBuilder->eq($field, 0),
1395
                            $expressionBuilder->gt($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
1396
                        );
1397
                    }
1398
                    if ($ctrl['enablecolumns']['fe_group'] && !$ignore_array['fe_group']) {
1399
                        $field = $table . '.' . $ctrl['enablecolumns']['fe_group'];
1400
                        $constraints[] = QueryHelper::stripLogicalOperatorPrefix(
1401
                            $this->getMultipleGroupsWhereClause($field, $table)
1402
                        );
1403
                    }
1404
                    // Call hook functions for additional enableColumns
1405
                    // It is used by the extension ingmar_accessctrl which enables assigning more
1406
                    // than one usergroup to content and page records
1407
                    $_params = [
1408
                        'table' => $table,
1409
                        'show_hidden' => $show_hidden,
1410
                        'ignore_array' => $ignore_array,
1411
                        'ctrl' => $ctrl
1412
                    ];
1413
                    foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['addEnableColumns'] ?? [] as $_funcRef) {
1414
                        $constraints[] = QueryHelper::stripLogicalOperatorPrefix(
1415
                            GeneralUtility::callUserFunction($_funcRef, $_params, $this)
1416
                        );
1417
                    }
1418
                }
1419
            }
1420
        } else {
1421
            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);
1422
        }
1423
1424
        return empty($constraints) ? '' : ' AND ' . $expressionBuilder->andX(...$constraints);
1425
    }
1426
1427
    /**
1428
     * Creating where-clause for checking group access to elements in enableFields
1429
     * function
1430
     *
1431
     * @param string $field Field with group list
1432
     * @param string $table Table name
1433
     * @return string AND sql-clause
1434
     * @see enableFields()
1435
     */
1436
    public function getMultipleGroupsWhereClause($field, $table)
1437
    {
1438
        $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1439
            ->getQueryBuilderForTable($table)
1440
            ->expr();
1441
        $memberGroups = GeneralUtility::intExplode(',', $this->getTypoScriptFrontendController()->gr_list);
1442
        $orChecks = [];
1443
        // If the field is empty, then OK
1444
        $orChecks[] = $expressionBuilder->eq($field, $expressionBuilder->literal(''));
1445
        // If the field is NULL, then OK
1446
        $orChecks[] = $expressionBuilder->isNull($field);
1447
        // If the field contains zero, then OK
1448
        $orChecks[] = $expressionBuilder->eq($field, $expressionBuilder->literal('0'));
1449
        foreach ($memberGroups as $value) {
1450
            $orChecks[] = $expressionBuilder->inSet($field, $expressionBuilder->literal($value));
1451
        }
1452
1453
        return' AND (' . $expressionBuilder->orX(...$orChecks) . ')';
1454
    }
1455
1456
    /**********************
1457
     *
1458
     * Versioning Preview
1459
     *
1460
     **********************/
1461
1462
    /**
1463
     * Finding online PID for offline version record
1464
     *
1465
     * ONLY active when backend user is previewing records. MUST NEVER affect a site
1466
     * served which is not previewed by backend users!!!
1467
     *
1468
     * Will look if the "pid" value of the input record is -1 (it is an offline
1469
     * version) and if the table supports versioning; if so, it will translate the -1
1470
     * PID into the PID of the original record.
1471
     *
1472
     * Used whenever you are tracking something back, like making the root line.
1473
     *
1474
     * Principle; Record offline! => Find online?
1475
     *
1476
     * @param string $table Table name
1477
     * @param array $rr Record array passed by reference. As minimum, "pid" and "uid" fields must exist! "t3ver_oid" and "t3ver_wsid" is nice and will save you a DB query.
1478
     * @see BackendUtility::fixVersioningPid(), versionOL(), getRootLine()
1479
     */
1480
    public function fixVersioningPid($table, &$rr)
1481
    {
1482
        if ($this->versioningPreview && is_array($rr) && (int)$rr['pid'] === -1 && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1483
            $oid = 0;
1484
            $wsid = 0;
1485
            // Check values for t3ver_oid and t3ver_wsid:
1486
            if (isset($rr['t3ver_oid']) && isset($rr['t3ver_wsid'])) {
1487
                // If "t3ver_oid" is already a field, just set this:
1488
                $oid = $rr['t3ver_oid'];
1489
                $wsid = $rr['t3ver_wsid'];
1490
            } else {
1491
                // Otherwise we have to expect "uid" to be in the record and look up based
1492
                // on this:
1493
                $uid = (int)$rr['uid'];
1494
                if ($uid > 0) {
1495
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1496
                    $queryBuilder->getRestrictions()
1497
                        ->removeAll()
1498
                        ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1499
                    $newPidRec = $queryBuilder->select('t3ver_oid', 't3ver_wsid')
1500
                        ->from($table)
1501
                        ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)))
1502
                        ->execute()
1503
                        ->fetch();
1504
1505
                    if (is_array($newPidRec)) {
1506
                        $oid = $newPidRec['t3ver_oid'];
1507
                        $wsid = $newPidRec['t3ver_wsid'];
1508
                    }
1509
                }
1510
            }
1511
            // If workspace ids matches and ID of current online version is found, look up
1512
            // the PID value of that:
1513
            if ($oid && ((int)$this->versioningWorkspaceId === 0 && $this->checkWorkspaceAccess($wsid) || (int)$wsid === (int)$this->versioningWorkspaceId)) {
1514
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1515
                $queryBuilder->getRestrictions()
1516
                    ->removeAll()
1517
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1518
                $oidRec = $queryBuilder->select('pid')
1519
                    ->from($table)
1520
                    ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($oid, \PDO::PARAM_INT)))
1521
                    ->execute()
1522
                    ->fetch();
1523
1524
                if (is_array($oidRec)) {
1525
                    // SWAP uid as well? Well no, because when fixing a versioning PID happens it is
1526
                    // assumed that this is a "branch" type page and therefore the uid should be
1527
                    // kept (like in versionOL()). However if the page is NOT a branch version it
1528
                    // should not happen - but then again, direct access to that uid should not
1529
                    // happen!
1530
                    $rr['_ORIG_pid'] = $rr['pid'];
1531
                    $rr['pid'] = $oidRec['pid'];
1532
                }
1533
            }
1534
        }
1535
        // Changing PID in case of moving pointer:
1536
        if ($movePlhRec = $this->getMovePlaceholder($table, $rr['uid'], 'pid')) {
1537
            $rr['pid'] = $movePlhRec['pid'];
1538
        }
1539
    }
1540
1541
    /**
1542
     * Versioning Preview Overlay
1543
     *
1544
     * ONLY active when backend user is previewing records. MUST NEVER affect a site
1545
     * served which is not previewed by backend users!!!
1546
     *
1547
     * Generally ALWAYS used when records are selected based on uid or pid. If
1548
     * records are selected on other fields than uid or pid (eg. "email = ....") then
1549
     * usage might produce undesired results and that should be evaluated on
1550
     * individual basis.
1551
     *
1552
     * Principle; Record online! => Find offline?
1553
     *
1554
     * @param string $table Table name
1555
     * @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!
1556
     * @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)
1557
     * @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!
1558
     * @see fixVersioningPid(), BackendUtility::workspaceOL()
1559
     */
1560
    public function versionOL($table, &$row, $unsetMovePointers = false, $bypassEnableFieldsCheck = false)
1561
    {
1562
        if ($this->versioningPreview && is_array($row)) {
1563
            // will overlay any movePlhOL found with the real record, which in turn
1564
            // will be overlaid with its workspace version if any.
1565
            $movePldSwap = $this->movePlhOL($table, $row);
1566
            // implode(',',array_keys($row)) = Using fields from original record to make
1567
            // sure no additional fields are selected. This is best for eg. getPageOverlay()
1568
            // Computed properties are excluded since those would lead to SQL errors.
1569
            $fieldNames = implode(',', array_keys($this->purgeComputedProperties($row)));
1570
            if ($wsAlt = $this->getWorkspaceVersionOfRecord($this->versioningWorkspaceId, $table, $row['uid'], $fieldNames, $bypassEnableFieldsCheck)) {
1571
                if (is_array($wsAlt)) {
1572
                    // Always fix PID (like in fixVersioningPid() above). [This is usually not
1573
                    // the important factor for versioning OL]
1574
                    // Keep the old (-1) - indicates it was a version...
1575
                    $wsAlt['_ORIG_pid'] = $wsAlt['pid'];
1576
                    // Set in the online versions PID.
1577
                    $wsAlt['pid'] = $row['pid'];
1578
                    // For versions of single elements or page+content, preserve online UID and PID
1579
                    // (this will produce true "overlay" of element _content_, not any references)
1580
                    // For page+content the "_ORIG_uid" should actually be used as PID for selection.
1581
                    $wsAlt['_ORIG_uid'] = $wsAlt['uid'];
1582
                    $wsAlt['uid'] = $row['uid'];
1583
                    // Translate page alias as well so links are pointing to the _online_ page:
1584
                    if ($table === 'pages') {
1585
                        $wsAlt['alias'] = $row['alias'];
1586
                    }
1587
                    // Changing input record to the workspace version alternative:
1588
                    $row = $wsAlt;
1589
                    // Check if it is deleted/new
1590
                    $rowVersionState = VersionState::cast($row['t3ver_state']);
1591
                    if (
1592
                        $rowVersionState->equals(VersionState::NEW_PLACEHOLDER)
1593
                        || $rowVersionState->equals(VersionState::DELETE_PLACEHOLDER)
1594
                    ) {
1595
                        // Unset record if it turned out to be deleted in workspace
1596
                        $row = false;
1597
                    }
1598
                    // Check if move-pointer in workspace (unless if a move-placeholder is the
1599
                    // reason why it appears!):
1600
                    // You have to specifically set $unsetMovePointers in order to clear these
1601
                    // because it is normally a display issue if it should be shown or not.
1602
                    if (
1603
                        (
1604
                            $rowVersionState->equals(VersionState::MOVE_POINTER)
1605
                            && !$movePldSwap
1606
                        ) && $unsetMovePointers
1607
                    ) {
1608
                        // Unset record if it turned out to be deleted in workspace
1609
                        $row = false;
1610
                    }
1611
                } else {
1612
                    // No version found, then check if t3ver_state = VersionState::NEW_PLACEHOLDER
1613
                    // (online version is dummy-representation)
1614
                    // Notice, that unless $bypassEnableFieldsCheck is TRUE, the $row is unset if
1615
                    // enablefields for BOTH the version AND the online record deselects it. See
1616
                    // note for $bypassEnableFieldsCheck
1617
                    /** @var \TYPO3\CMS\Core\Versioning\VersionState $versionState */
1618
                    $versionState = VersionState::cast($row['t3ver_state']);
1619
                    if ($wsAlt <= -1 || $versionState->indicatesPlaceholder()) {
1620
                        // Unset record if it turned out to be "hidden"
1621
                        $row = false;
1622
                    }
1623
                }
1624
            }
1625
        }
1626
    }
1627
1628
    /**
1629
     * Checks if record is a move-placeholder
1630
     * (t3ver_state==VersionState::MOVE_PLACEHOLDER) and if so it will set $row to be
1631
     * the pointed-to live record (and return TRUE) Used from versionOL
1632
     *
1633
     * @param string $table Table name
1634
     * @param array $row Row (passed by reference) - only online records...
1635
     * @return bool TRUE if overlay is made.
1636
     * @see BackendUtility::movePlhOl()
1637
     */
1638
    public function movePlhOL($table, &$row)
1639
    {
1640
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])
1641
            && (int)VersionState::cast($row['t3ver_state'])->equals(VersionState::MOVE_PLACEHOLDER)
1642
        ) {
1643
            $moveID = 0;
1644
            // If t3ver_move_id is not found, then find it (but we like best if it is here)
1645
            if (!isset($row['t3ver_move_id'])) {
1646
                if ((int)$row['uid'] > 0) {
1647
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1648
                    $queryBuilder->getRestrictions()
1649
                        ->removeAll()
1650
                        ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1651
                    $moveIDRec = $queryBuilder->select('t3ver_move_id')
1652
                        ->from($table)
1653
                        ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($row['uid'], \PDO::PARAM_INT)))
1654
                        ->execute()
1655
                        ->fetch();
1656
1657
                    if (is_array($moveIDRec)) {
1658
                        $moveID = $moveIDRec['t3ver_move_id'];
1659
                    }
1660
                }
1661
            } else {
1662
                $moveID = $row['t3ver_move_id'];
1663
            }
1664
            // Find pointed-to record.
1665
            if ($moveID) {
1666
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1667
                $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1668
                $origRow = $queryBuilder->select(...array_keys($this->purgeComputedProperties($row)))
1669
                    ->from($table)
1670
                    ->where(
1671
                        $queryBuilder->expr()->eq(
1672
                            'uid',
1673
                            $queryBuilder->createNamedParameter($moveID, \PDO::PARAM_INT)
1674
                        )
1675
                    )
1676
                    ->setMaxResults(1)
1677
                    ->execute()
1678
                    ->fetch();
1679
1680
                if ($origRow) {
1681
                    $row = $origRow;
1682
                    return true;
1683
                }
1684
            }
1685
        }
1686
        return false;
1687
    }
1688
1689
    /**
1690
     * Returns move placeholder of online (live) version
1691
     *
1692
     * @param string $table Table name
1693
     * @param int $uid Record UID of online version
1694
     * @param string $fields Field list, default is *
1695
     * @return array If found, the record, otherwise nothing.
1696
     * @see BackendUtility::getMovePlaceholder()
1697
     */
1698
    public function getMovePlaceholder($table, $uid, $fields = '*')
1699
    {
1700
        if ($this->versioningPreview) {
1701
            $workspace = (int)$this->versioningWorkspaceId;
1702
            if (!empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) && $workspace !== 0) {
1703
                // Select workspace version of record:
1704
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1705
                $queryBuilder->getRestrictions()
1706
                    ->removeAll()
1707
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1708
1709
                $row = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
1710
                    ->from($table)
1711
                    ->where(
1712
                        $queryBuilder->expr()->neq('pid', $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)),
1713
                        $queryBuilder->expr()->eq(
1714
                            't3ver_state',
1715
                            $queryBuilder->createNamedParameter(
1716
                                (string)VersionState::cast(VersionState::MOVE_PLACEHOLDER),
1717
                                \PDO::PARAM_INT
1718
                            )
1719
                        ),
1720
                        $queryBuilder->expr()->eq(
1721
                            't3ver_move_id',
1722
                            $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1723
                        ),
1724
                        $queryBuilder->expr()->eq(
1725
                            't3ver_wsid',
1726
                            $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1727
                        )
1728
                    )
1729
                    ->setMaxResults(1)
1730
                    ->execute()
1731
                    ->fetch();
1732
1733
                if (is_array($row)) {
1734
                    return $row;
1735
                }
1736
            }
1737
        }
1738
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type array.
Loading history...
1739
    }
1740
1741
    /**
1742
     * Select the version of a record for a workspace
1743
     *
1744
     * @param int $workspace Workspace ID
1745
     * @param string $table Table name to select from
1746
     * @param int $uid Record uid for which to find workspace version.
1747
     * @param string $fields Field list to select
1748
     * @param bool $bypassEnableFieldsCheck If TRUE, enablefields are not checked for.
1749
     * @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.
1750
     * @see BackendUtility::getWorkspaceVersionOfRecord()
1751
     */
1752
    public function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields = '*', $bypassEnableFieldsCheck = false)
1753
    {
1754
        if ($workspace !== 0 && !empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])) {
1755
            $workspace = (int)$workspace;
1756
            $uid = (int)$uid;
1757
            // Select workspace version of record, only testing for deleted.
1758
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1759
            $queryBuilder->getRestrictions()
1760
                ->removeAll()
1761
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1762
1763
            $newrow = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
1764
                ->from($table)
1765
                ->where(
1766
                    $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)),
1767
                    $queryBuilder->expr()->eq(
1768
                        't3ver_oid',
1769
                        $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1770
                    ),
1771
                    $queryBuilder->expr()->eq(
1772
                        't3ver_wsid',
1773
                        $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1774
                    )
1775
                )
1776
                ->setMaxResults(1)
1777
                ->execute()
1778
                ->fetch();
1779
1780
            // If version found, check if it could have been selected with enableFields on
1781
            // as well:
1782
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1783
            $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1784
            // Remove the frontend workspace restriction because we are testing a version record
1785
            $queryBuilder->getRestrictions()->removeByType(FrontendWorkspaceRestriction::class);
1786
            $queryBuilder->select('uid')
1787
                ->from($table)
1788
                ->setMaxResults(1);
1789
1790
            if (is_array($newrow)) {
1791
                $queryBuilder->where(
1792
                    $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)),
1793
                    $queryBuilder->expr()->eq(
1794
                        't3ver_oid',
1795
                        $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1796
                    ),
1797
                    $queryBuilder->expr()->eq(
1798
                        't3ver_wsid',
1799
                        $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
1800
                    )
1801
                );
1802
                if ($bypassEnableFieldsCheck || $queryBuilder->execute()->fetchColumn()) {
1803
                    // Return offline version, tested for its enableFields.
1804
                    return $newrow;
1805
                }
1806
                // Return -1 because offline version was de-selected due to its enableFields.
1807
                return -1;
1808
            }
1809
            // OK, so no workspace version was found. Then check if online version can be
1810
            // selected with full enable fields and if so, return 1:
1811
            $queryBuilder->where(
1812
                    $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT))
1813
                );
1814
            if ($bypassEnableFieldsCheck || $queryBuilder->execute()->fetchColumn()) {
1815
                // Means search was done, but no version found.
1816
                return 1;
1817
            }
1818
            // Return -2 because the online record was de-selected due to its enableFields.
1819
            return -2;
1820
        }
1821
        // No look up in database because versioning not enabled / or workspace not
1822
        // offline
1823
        return false;
1824
    }
1825
1826
    /**
1827
     * Checks if user has access to workspace.
1828
     *
1829
     * @param int $wsid Workspace ID
1830
     * @return bool true if the backend user has access to a certain workspace
1831
     */
1832
    public function checkWorkspaceAccess($wsid)
1833
    {
1834
        if (!$this->getBackendUser() || !ExtensionManagementUtility::isLoaded('workspaces')) {
1835
            return false;
1836
        }
1837
        if (!isset($this->workspaceCache[$wsid])) {
1838
            $this->workspaceCache[$wsid] = $this->getBackendUser()->checkWorkspace($wsid);
1839
        }
1840
        return (string)$this->workspaceCache[$wsid]['_ACCESS'] !== '';
1841
    }
1842
1843
    /**
1844
     * Gets file references for a given record field.
1845
     *
1846
     * @param string $tableName Name of the table
1847
     * @param string $fieldName Name of the field
1848
     * @param array $element The parent element referencing to files
1849
     * @return array
1850
     */
1851
    public function getFileReferences($tableName, $fieldName, array $element)
1852
    {
1853
        /** @var $fileRepository FileRepository */
1854
        $fileRepository = GeneralUtility::makeInstance(FileRepository::class);
1855
        $currentId = !empty($element['uid']) ? $element['uid'] : 0;
1856
1857
        // Fetch the references of the default element
1858
        try {
1859
            $references = $fileRepository->findByRelation($tableName, $fieldName, $currentId);
1860
        } catch (FileDoesNotExistException $e) {
1861
            /**
1862
             * We just catch the exception here
1863
             * Reasoning: There is nothing an editor or even admin could do
1864
             */
1865
            return [];
1866
        } catch (\InvalidArgumentException $e) {
1867
            /**
1868
             * The storage does not exist anymore
1869
             * Log the exception message for admins as they maybe can restore the storage
1870
             */
1871
            $logMessage = $e->getMessage() . ' (table: "' . $tableName . '", fieldName: "' . $fieldName . '", currentId: ' . $currentId . ')';
1872
            $this->logger->error($logMessage, ['exception' => $e]);
1873
            return [];
1874
        }
1875
1876
        $localizedId = null;
1877
        if (isset($element['_LOCALIZED_UID'])) {
1878
            $localizedId = $element['_LOCALIZED_UID'];
1879
        } elseif (isset($element['_PAGES_OVERLAY_UID'])) {
1880
            $localizedId = $element['_PAGES_OVERLAY_UID'];
1881
        }
1882
1883
        $isTableLocalizable = (
1884
            !empty($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
1885
            && !empty($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
1886
        );
1887
        if ($isTableLocalizable && $localizedId !== null) {
1888
            $localizedReferences = $fileRepository->findByRelation($tableName, $fieldName, $localizedId);
1889
            $references = $localizedReferences;
1890
        }
1891
1892
        return $references;
1893
    }
1894
1895
    /**
1896
     * Purges computed properties from database rows,
1897
     * such as _ORIG_uid or _ORIG_pid for instance.
1898
     *
1899
     * @param array $row
1900
     * @return array
1901
     */
1902
    protected function purgeComputedProperties(array $row)
1903
    {
1904
        foreach ($this->computedPropertyNames as $computedPropertyName) {
1905
            if (array_key_exists($computedPropertyName, $row)) {
1906
                unset($row[$computedPropertyName]);
1907
            }
1908
        }
1909
        return $row;
1910
    }
1911
1912
    /**
1913
     * @return \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController
1914
     */
1915
    protected function getTypoScriptFrontendController()
1916
    {
1917
        return $GLOBALS['TSFE'];
1918
    }
1919
1920
    /**
1921
     * Returns the current BE user.
1922
     *
1923
     * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1924
     */
1925
    protected function getBackendUser()
1926
    {
1927
        return $GLOBALS['BE_USER'];
1928
    }
1929
}
1930