BackendUtility.php 157 KB
Newer Older
1
<?php
2

3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
7
8
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
9
 *
10
11
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
14
 * The TYPO3 project - inspiring people to share!
 */
Nicole Cordes's avatar
Nicole Cordes committed
15

16
17
namespace TYPO3\CMS\Backend\Utility;

18
use Psr\Http\Message\ServerRequestInterface;
19
use Psr\Log\LoggerInterface;
20
use TYPO3\CMS\Backend\Configuration\TranslationConfigurationProvider;
21
use TYPO3\CMS\Backend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
22
use TYPO3\CMS\Backend\Domain\Model\Element\ImmediateActionElement;
23
use TYPO3\CMS\Backend\Routing\Route;
24
use TYPO3\CMS\Backend\Routing\UriBuilder;
25
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
Markus Klein's avatar
Markus Klein committed
26
use TYPO3\CMS\Core\Cache\CacheManager;
27
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
28
29
use TYPO3\CMS\Core\Configuration\Loader\PageTsConfigLoader;
use TYPO3\CMS\Core\Configuration\Parser\PageTsConfigParser;
30
31
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Context\DateTimeAspect;
32
use TYPO3\CMS\Core\Core\Environment;
33
34
35
36
37
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
use TYPO3\CMS\Core\Database\Query\QueryHelper;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
38
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
39
use TYPO3\CMS\Core\Database\Query\Restriction\WorkspaceRestriction;
40
use TYPO3\CMS\Core\Database\RelationHandler;
41
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
42
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
43
44
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
45
use TYPO3\CMS\Core\Imaging\ImageDimension;
46
use TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection;
47
use TYPO3\CMS\Core\Localization\LanguageService;
48
use TYPO3\CMS\Core\Log\LogManager;
49
use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;
50
use TYPO3\CMS\Core\Resource\ProcessedFile;
Nicole Cordes's avatar
Nicole Cordes committed
51
use TYPO3\CMS\Core\Resource\ResourceFactory;
52
use TYPO3\CMS\Core\Routing\InvalidRouteArgumentsException;
Oliver Hader's avatar
Oliver Hader committed
53
use TYPO3\CMS\Core\Routing\RouterInterface;
54
use TYPO3\CMS\Core\Routing\UnableToLinkToPageException;
55
use TYPO3\CMS\Core\Site\SiteFinder;
56
use TYPO3\CMS\Core\Type\Bitmask\Permission;
Nicole Cordes's avatar
Nicole Cordes committed
57
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
Markus Klein's avatar
Markus Klein committed
58
use TYPO3\CMS\Core\Utility\ArrayUtility;
Nicole Cordes's avatar
Nicole Cordes committed
59
60
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
61
use TYPO3\CMS\Core\Utility\HttpUtility;
Nicole Cordes's avatar
Nicole Cordes committed
62
use TYPO3\CMS\Core\Utility\MathUtility;
Markus Klein's avatar
Markus Klein committed
63
use TYPO3\CMS\Core\Utility\PathUtility;
64
use TYPO3\CMS\Core\Utility\StringUtility;
65
use TYPO3\CMS\Core\Versioning\VersionState;
Nicole Cordes's avatar
Nicole Cordes committed
66

67
68
69
/**
 * Standard functions available for the TYPO3 backend.
 * You are encouraged to use this class in your own applications (Backend Modules)
70
 * Don't instantiate - call functions with "\TYPO3\CMS\Backend\Utility\BackendUtility::" prefixed the function name.
71
72
 *
 * Call ALL methods without making an object!
73
 * Eg. to get a page-record 51 do this: '\TYPO3\CMS\Backend\Utility\BackendUtility::getRecord('pages',51)'
74
 */
75
76
77
78
79
80
81
82
83
84
class BackendUtility
{
    /*******************************************
     *
     * SQL-related, selecting records, searching
     *
     *******************************************/
    /**
     * Gets record with uid = $uid from $table
     * You can set $field to a list of fields (default is '*')
85
     * Additional WHERE clauses can be added by $where (fx. ' AND some_field = 1')
86
87
88
89
     * Will automatically check if records has been deleted and if so, not return anything.
     * $table must be found in $GLOBALS['TCA']
     *
     * @param string $table Table name present in $GLOBALS['TCA']
90
     * @param int|string $uid UID of record
91
     * @param string $fields List of fields to select
92
     * @param string $where Additional WHERE clause, eg. ' AND some_field = 0'
93
     * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
94
     * @return array|null Returns the row if found, otherwise NULL
95
96
97
98
99
     */
    public static function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = true)
    {
        // Ensure we have a valid uid (not 0 and not NEWxxxx) and a valid TCA
        if ((int)$uid && !empty($GLOBALS['TCA'][$table])) {
100
101
102
103
104
105
106
107
108
109
110
111
112
113
            $queryBuilder = static::getQueryBuilderForTable($table);

            // do not use enabled fields here
            $queryBuilder->getRestrictions()->removeAll();

            // should the delete clause be used
            if ($useDeleteClause) {
                $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
            }

            // set table and where clause
            $queryBuilder
                ->select(...GeneralUtility::trimExplode(',', $fields, true))
                ->from($table)
114
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter((int)$uid, \PDO::PARAM_INT)));
115
116
117
118
119
120

            // add custom where clause
            if ($where) {
                $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($where));
            }

121
            $row = $queryBuilder->execute()->fetchAssociative();
122
123
124
125
126
127
128
129
130
131
132
133
134
            if ($row) {
                return $row;
            }
        }
        return null;
    }

    /**
     * Like getRecord(), but overlays workspace version if any.
     *
     * @param string $table Table name present in $GLOBALS['TCA']
     * @param int $uid UID of record
     * @param string $fields List of fields to select
135
     * @param string $where Additional WHERE clause, eg. ' AND some_field = 0'
136
137
138
139
     * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
     * @param bool $unsetMovePointers If TRUE the function does not return a "pointer" row for moved records in a workspace
     * @return array Returns the row if found, otherwise nothing
     */
140
141
142
143
144
145
146
147
    public static function getRecordWSOL(
        $table,
        $uid,
        $fields = '*',
        $where = '',
        $useDeleteClause = true,
        $unsetMovePointers = false
    ) {
148
        if ($fields !== '*') {
149
            $internalFields = StringUtility::uniqueList($fields . ',uid,pid');
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
            $row = self::getRecord($table, $uid, $internalFields, $where, $useDeleteClause);
            self::workspaceOL($table, $row, -99, $unsetMovePointers);
            if (is_array($row)) {
                foreach ($row as $key => $_) {
                    if (!GeneralUtility::inList($fields, $key) && $key[0] !== '_') {
                        unset($row[$key]);
                    }
                }
            }
        } else {
            $row = self::getRecord($table, $uid, $fields, $where, $useDeleteClause);
            self::workspaceOL($table, $row, -99, $unsetMovePointers);
        }
        return $row;
    }

166
167
168
    /**
     * Purges computed properties starting with underscore character ('_').
     *
169
170
     * @param array<string,mixed> $record
     * @return array<string,mixed>
171
     * @internal should only be used from within TYPO3 Core
172
173
174
175
176
     */
    public static function purgeComputedPropertiesFromRecord(array $record): array
    {
        return array_filter(
            $record,
177
            static function (string $propertyName): bool {
178
179
180
181
182
183
184
185
186
187
188
                return $propertyName[0] !== '_';
            },
            ARRAY_FILTER_USE_KEY
        );
    }

    /**
     * Purges computed property names starting with underscore character ('_').
     *
     * @param array $propertyNames
     * @return array
189
     * @internal should only be used from within TYPO3 Core
190
191
192
193
194
     */
    public static function purgeComputedPropertyNames(array $propertyNames): array
    {
        return array_filter(
            $propertyNames,
195
            static function (string $propertyName): bool {
196
197
198
199
200
                return $propertyName[0] !== '_';
            }
        );
    }

201
    /**
202
     * Makes a backwards explode on the $str and returns an array with ($table, $uid).
203
     * Example: tt_content_45 => ['tt_content', 45]
204
205
206
     *
     * @param string $str [tablename]_[uid] string to explode
     * @return array
207
     * @internal should only be used from within TYPO3 Core
208
209
210
     */
    public static function splitTable_Uid($str)
    {
211
212
213
        $split = explode('_', strrev($str), 2);
        $uid = $split[0];
        $table = $split[1] ?? '';
214
        return [strrev($table), strrev($uid)];
215
216
217
218
219
220
221
222
223
224
225
    }

    /**
     * Backend implementation of enableFields()
     * Notice that "fe_groups" is not selected for - only disabled, starttime and endtime.
     * Notice that deleted-fields are NOT filtered - you must ALSO call deleteClause in addition.
     * $GLOBALS["SIM_ACCESS_TIME"] is used for date.
     *
     * @param string $table The table from which to return enableFields WHERE clause. Table name must have a 'ctrl' section in $GLOBALS['TCA'].
     * @param bool $inv Means that the query will select all records NOT VISIBLE records (inverted selection)
     * @return string WHERE clause part
226
     * @internal should only be used from within TYPO3 Core, but DefaultRestrictionHandler is recommended as alternative
227
228
229
     */
    public static function BEenableFields($table, $inv = false)
    {
230
        $ctrl = $GLOBALS['TCA'][$table]['ctrl'] ?? [];
231
232
233
234
235
236
        $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getConnectionForTable($table)
            ->getExpressionBuilder();
        $query = $expressionBuilder->andX();
        $invQuery = $expressionBuilder->orX();

237
238
239
240
        $ctrl += [
            'enablecolumns' => [],
        ];

241
        if (is_array($ctrl)) {
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
            if ($ctrl['enablecolumns']['disabled'] ?? false) {
                $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
                $query->add($expressionBuilder->eq($field, 0));
                $invQuery->add($expressionBuilder->neq($field, 0));
            }
            if ($ctrl['enablecolumns']['starttime'] ?? false) {
                $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
                $query->add($expressionBuilder->lte($field, (int)$GLOBALS['SIM_ACCESS_TIME']));
                $invQuery->add(
                    $expressionBuilder->andX(
                        $expressionBuilder->neq($field, 0),
                        $expressionBuilder->gt($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
                    )
                );
            }
            if ($ctrl['enablecolumns']['endtime'] ?? false) {
                $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
                $query->add(
                    $expressionBuilder->orX(
                        $expressionBuilder->eq($field, 0),
                        $expressionBuilder->gt($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
                    )
                );
                $invQuery->add(
                    $expressionBuilder->andX(
                        $expressionBuilder->neq($field, 0),
                        $expressionBuilder->lte($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
                    )
                );
271
272
            }
        }
273
274
275
276
277
278

        if ($query->count() === 0) {
            return '';
        }

        return ' AND ' . ($inv ? $invQuery : $query);
279
280
281
282
283
284
285
286
287
    }

    /**
     * Fetches the localization for a given record.
     *
     * @param string $table Table name present in $GLOBALS['TCA']
     * @param int $uid The uid of the record
     * @param int $language The uid of the language record in sys_language
     * @param string $andWhereClause Optional additional WHERE clause (default: '')
288
     * @return mixed Multidimensional array with selected records, empty array if none exists and FALSE if table is not localizable
289
290
291
292
293
294
295
     */
    public static function getRecordLocalization($table, $uid, $language, $andWhereClause = '')
    {
        $recordLocalization = false;

        if (self::isTableLocalizable($table)) {
            $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
296

297
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
298
                ->getQueryBuilderForTable($table);
299
300
301
            $queryBuilder->getRestrictions()
                ->removeAll()
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
302
                ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, static::getBackendUserAuthentication()->workspace ?? 0));
303

304
305
306
307
            $queryBuilder->select('*')
                ->from($table)
                ->where(
                    $queryBuilder->expr()->eq(
308
                        $tcaCtrl['translationSource'] ?? $tcaCtrl['transOrigPointerField'],
309
310
311
312
313
314
315
316
                        $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
                    ),
                    $queryBuilder->expr()->eq(
                        $tcaCtrl['languageField'],
                        $queryBuilder->createNamedParameter((int)$language, \PDO::PARAM_INT)
                    )
                )
                ->setMaxResults(1);
317

318
319
320
321
            if ($andWhereClause) {
                $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($andWhereClause));
            }

322
            $recordLocalization = $queryBuilder->execute()->fetchAllAssociative();
323
        }
324

325
326
327
328
329
330
331
332
333
        return $recordLocalization;
    }

    /*******************************************
     *
     * Page tree, TCA related
     *
     *******************************************/
    /**
334
335
     * Returns what is called the 'RootLine'. That is an array with information about the page records from a page id
     * ($uid) and back to the root.
336
     * By default deleted pages are filtered.
337
338
     * This RootLine will follow the tree all the way to the root. This is opposite to another kind of root line known
     * from the frontend where the rootline stops when a root-template is found.
339
340
     *
     * @param int $uid Page id for which to create the root line.
341
342
343
344
     * @param string $clause Clause can be used to select other criteria. It would typically be where-clauses that
     *          stops the process if we meet a page, the user has no reading access to.
     * @param bool $workspaceOL If TRUE, version overlay is applied. This must be requested specifically because it is
     *          usually only wanted when the rootline is used for visual output while for permission checking you want the raw thing!
345
     * @param string[] $additionalFields Additional Fields to select for rootline records
346
     * @return array Root line array, all the way to the page tree root uid=0 (or as far as $clause allows!), including the page given as $uid
347
     */
348
    public static function BEgetRootLine($uid, $clause = '', $workspaceOL = false, array $additionalFields = [])
349
    {
350
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
351
        $beGetRootLineCache = $runtimeCache->get('backendUtilityBeGetRootLine') ?: [];
352
        $output = [];
353
        $pid = $uid;
354
        $ident = $pid . '-' . $clause . '-' . $workspaceOL . ($additionalFields ? '-' . md5(implode(',', $additionalFields)) : '');
355
356
        if (is_array($beGetRootLineCache[$ident] ?? false)) {
            $output = $beGetRootLineCache[$ident];
357
358
        } else {
            $loopCheck = 100;
359
            $theRowArray = [];
360
361
            while ($uid != 0 && $loopCheck) {
                $loopCheck--;
362
                $row = self::getPageForRootline($uid, $clause, $workspaceOL, $additionalFields);
363
364
365
366
367
368
369
                if (is_array($row)) {
                    $uid = $row['pid'];
                    $theRowArray[] = $row;
                } else {
                    break;
                }
            }
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
            $fields = [
                'uid',
                'pid',
                'title',
                'doktype',
                'slug',
                'tsconfig_includes',
                'TSconfig',
                'is_siteroot',
                't3ver_oid',
                't3ver_wsid',
                't3ver_state',
                't3ver_stage',
                'backend_layout_next_level',
                'hidden',
                'starttime',
                'endtime',
                'fe_group',
                'nav_hide',
                'content_from_pid',
                'module',
391
                'extendToSubpages',
392
393
394
            ];
            $fields = array_merge($fields, $additionalFields);
            $rootPage = array_fill_keys($fields, null);
395
            if ($uid == 0) {
396
397
                $rootPage['uid'] = 0;
                $theRowArray[] = $rootPage;
398
399
400
401
            }
            $c = count($theRowArray);
            foreach ($theRowArray as $val) {
                $c--;
402
                $output[$c] = array_intersect_key($val, $rootPage);
403
404
405
406
                if (isset($val['_ORIG_pid'])) {
                    $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
                }
            }
407
408
            $beGetRootLineCache[$ident] = $output;
            $runtimeCache->set('backendUtilityBeGetRootLine', $beGetRootLineCache);
409
410
411
412
413
414
415
416
417
418
        }
        return $output;
    }

    /**
     * Gets the cached page record for the rootline
     *
     * @param int $uid Page id for which to create the root line.
     * @param string $clause Clause can be used to select other criteria. It would typically be where-clauses that stops the process if we meet a page, the user has no reading access to.
     * @param bool $workspaceOL If TRUE, version overlay is applied. This must be requested specifically because it is usually only wanted when the rootline is used for visual output while for permission checking you want the raw thing!
419
     * @param string[] $additionalFields AdditionalFields to fetch from the root line
420
421
422
     * @return array Cached page record for the rootline
     * @see BEgetRootLine
     */
423
    protected static function getPageForRootline($uid, $clause, $workspaceOL, array $additionalFields = [])
424
    {
425
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
426
        $pageForRootlineCache = $runtimeCache->get('backendUtilityPageForRootLine') ?: [];
427
428
        $statementCacheIdent = md5($clause . ($additionalFields ? '-' . implode(',', $additionalFields) : ''));
        $ident = $uid . '-' . $workspaceOL . '-' . $statementCacheIdent;
429
430
        if (is_array($pageForRootlineCache[$ident] ?? false)) {
            $row = $pageForRootlineCache[$ident];
431
        } else {
432
433
            $statement = $runtimeCache->get('getPageForRootlineStatement-' . $statementCacheIdent);
            if (!$statement) {
434
435
436
437
                $queryBuilder = static::getQueryBuilderForTable('pages');
                $queryBuilder->getRestrictions()
                             ->removeAll()
                             ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
438

439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
                $queryBuilder
                    ->select(
                        'pid',
                        'uid',
                        'title',
                        'doktype',
                        'slug',
                        'tsconfig_includes',
                        'TSconfig',
                        'is_siteroot',
                        't3ver_oid',
                        't3ver_wsid',
                        't3ver_state',
                        't3ver_stage',
                        'backend_layout_next_level',
                        'hidden',
                        'starttime',
                        'endtime',
                        'fe_group',
                        'nav_hide',
                        'content_from_pid',
                        'module',
                        'extendToSubpages',
                        ...$additionalFields
                    )
                    ->from('pages')
                    ->where(
466
                        $queryBuilder->expr()->eq('uid', $queryBuilder->createPositionalParameter($uid, \PDO::PARAM_INT)),
467
468
                        QueryHelper::stripLogicalOperatorPrefix($clause)
                    );
469
470
471
472
473
474
475
476
                $statement = $queryBuilder->execute();
                if (class_exists(\Doctrine\DBAL\ForwardCompatibility\Result::class) && $statement instanceof \Doctrine\DBAL\ForwardCompatibility\Result) {
                    $statement = $statement->getIterator();
                }
                $runtimeCache->set('getPageForRootlineStatement-' . $statementCacheIdent, $statement);
            } else {
                $statement->bindValue(1, (int)$uid);
                $statement->execute();
477
            }
478
479
            $row = $statement->fetchAssociative();
            $statement->free();
480

481
482
483
484
485
            if ($row) {
                if ($workspaceOL) {
                    self::workspaceOL('pages', $row);
                }
                if (is_array($row)) {
486
487
                    $pageForRootlineCache[$ident] = $row;
                    $runtimeCache->set('backendUtilityPageForRootLine', $pageForRootlineCache);
488
489
490
491
492
493
494
495
496
497
498
                }
            }
        }
        return $row;
    }

    /**
     * Opens the page tree to the specified page id
     *
     * @param int $pid Page id.
     * @param bool $clearExpansion If set, then other open branches are closed.
499
     * @internal should only be used from within TYPO3 Core
500
501
502
503
504
505
     */
    public static function openPageTree($pid, $clearExpansion)
    {
        $beUser = static::getBackendUserAuthentication();
        // Get current expansion data:
        if ($clearExpansion) {
506
            $expandedPages = [];
507
        } else {
508
            $expandedPages = $beUser->uc['BackendComponents']['States']['Pagetree']['stateHash'] ?? [];
509
510
511
512
513
        }
        // Get rootline:
        $rL = self::BEgetRootLine($pid);
        // First, find out what mount index to use (if more than one DB mount exists):
        $mountIndex = 0;
514
515
        $mountKeys = $beUser->returnWebmounts();

516
517
518
519
520
521
522
523
        foreach ($rL as $rLDat) {
            if (isset($mountKeys[$rLDat['uid']])) {
                $mountIndex = $mountKeys[$rLDat['uid']];
                break;
            }
        }
        // Traverse rootline and open paths:
        foreach ($rL as $rLDat) {
524
            $expandedPages[$mountIndex . '_' . $rLDat['uid']] = '1';
525
526
        }
        // Write back:
527
        $beUser->uc['BackendComponents']['States']['Pagetree']['stateHash'] = $expandedPages;
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
        $beUser->writeUC();
    }

    /**
     * Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"
     * Each part of the path will be limited to $titleLimit characters
     * Deleted pages are filtered out.
     *
     * @param int $uid Page uid for which to create record path
     * @param string $clause Clause is additional where clauses, eg.
     * @param int $titleLimit Title limit
     * @param int $fullTitleLimit Title limit of Full title (typ. set to 1000 or so)
     * @return mixed Path of record (string) OR array with short/long title if $fullTitleLimit is set.
     */
    public static function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0)
    {
        if (!$titleLimit) {
            $titleLimit = 1000;
        }
        $output = $fullOutput = '/';
        $clause = trim($clause);
549
        if ($clause !== '' && strpos($clause, 'AND') !== 0) {
550
551
            $clause = 'AND ' . $clause;
        }
552
        $data = self::BEgetRootLine($uid, $clause, true);
553
554
555
556
557
558
559
560
561
562
        foreach ($data as $record) {
            if ($record['uid'] === 0) {
                continue;
            }
            $output = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $titleLimit) . $output;
            if ($fullTitleLimit) {
                $fullOutput = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $fullTitleLimit) . $fullOutput;
            }
        }
        if ($fullTitleLimit) {
563
            return [$output, $fullOutput];
564
        }
565
        return $output;
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
    }

    /**
     * Determines whether a table is localizable and has the languageField and transOrigPointerField set in $GLOBALS['TCA'].
     *
     * @param string $table The table to check
     * @return bool Whether a table is localizable
     */
    public static function isTableLocalizable($table)
    {
        $isLocalizable = false;
        if (isset($GLOBALS['TCA'][$table]['ctrl']) && is_array($GLOBALS['TCA'][$table]['ctrl'])) {
            $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
            $isLocalizable = isset($tcaCtrl['languageField']) && $tcaCtrl['languageField'] && isset($tcaCtrl['transOrigPointerField']) && $tcaCtrl['transOrigPointerField'];
        }
        return $isLocalizable;
    }

    /**
     * Returns a page record (of page with $id) with an extra field "_thePath" set to the record path IF the WHERE clause, $perms_clause, selects the record. Thus is works as an access check that returns a page record if access was granted, otherwise not.
     * If $id is zero a pseudo root-page with "_thePath" set is returned IF the current BE_USER is admin.
     * In any case ->isInWebMount must return TRUE for the user (regardless of $perms_clause)
     *
     * @param int $id Page uid for which to check read-access
     * @param string $perms_clause This is typically a value generated with static::getBackendUserAuthentication()->getPagePermsClause(1);
591
     * @return array|false Returns page record if OK, otherwise FALSE.
592
593
594
595
596
597
598
     */
    public static function readPageAccess($id, $perms_clause)
    {
        if ((string)$id !== '') {
            $id = (int)$id;
            if (!$id) {
                if (static::getBackendUserAuthentication()->isAdmin()) {
599
                    return ['_thePath' => '/'];
600
601
                }
            } else {
602
                $pageinfo = self::getRecord('pages', $id, '*', $perms_clause);
603
                if (($pageinfo['uid'] ?? false) && static::getBackendUserAuthentication()->isInWebMount($pageinfo, $perms_clause)) {
604
605
                    self::workspaceOL('pages', $pageinfo);
                    if (is_array($pageinfo)) {
606
                        [$pageinfo['_thePath'], $pageinfo['_thePathFull']] = self::getRecordPath((int)$pageinfo['uid'], $perms_clause, 15, 1000);
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
                        return $pageinfo;
                    }
                }
            }
        }
        return false;
    }

    /**
     * Returns the "type" value of $rec from $table which can be used to look up the correct "types" rendering section in $GLOBALS['TCA']
     * If no "type" field is configured in the "ctrl"-section of the $GLOBALS['TCA'] for the table, zero is used.
     * If zero is not an index in the "types" section of $GLOBALS['TCA'] for the table, then the $fieldValue returned will default to 1 (no matter if that is an index or not)
     *
     * Note: This method is very similar to the type determination of FormDataProvider/DatabaseRecordTypeValue,
     * however, it has two differences:
     * 1) The method in TCEForms also takes care of localization (which is difficult to do here as the whole infrastructure for language overlays is only in TCEforms).
     * 2) The $row array looks different in TCEForms, as in there it's not the raw record but the prepared data from other providers is handled, which changes e.g. how "select"
     * and "group" field values are stored, which makes different processing of the "foreign pointer field" type field variant necessary.
     *
     * @param string $table Table name present in TCA
     * @param array $row Record from $table
     * @throws \RuntimeException
     * @return string Field value
     */
    public static function getTCAtypeValue($table, $row)
    {
        $typeNum = 0;
634
635
        if ($GLOBALS['TCA'][$table] ?? false) {
            $field = $GLOBALS['TCA'][$table]['ctrl']['type'] ?? '';
636
            if (str_contains($field, ':')) {
637
                [$pointerField, $foreignTableTypeField] = explode(':', $field);
638
639
640
641
642
643
644
645
646
647
                // Get field value from database if field is not in the $row array
                if (!isset($row[$pointerField])) {
                    $localRow = self::getRecord($table, $row['uid'], $pointerField);
                    $foreignUid = $localRow[$pointerField];
                } else {
                    $foreignUid = $row[$pointerField];
                }
                if ($foreignUid) {
                    $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$pointerField]['config'];
                    $relationType = $fieldConfig['type'];
648
                    if ($relationType === 'select' || $relationType === 'category') {
649
650
651
652
653
                        $foreignTable = $fieldConfig['foreign_table'];
                    } elseif ($relationType === 'group') {
                        $allowedTables = explode(',', $fieldConfig['allowed']);
                        $foreignTable = $allowedTables[0];
                    } else {
654
655
656
657
                        throw new \RuntimeException(
                            'TCA foreign field pointer fields are only allowed to be used with group or select field types.',
                            1325862240
                        );
658
659
                    }
                    $foreignRow = self::getRecord($foreignTable, $foreignUid, $foreignTableTypeField);
660
                    if ($foreignRow[$foreignTableTypeField] ?? false) {
661
662
663
664
                        $typeNum = $foreignRow[$foreignTableTypeField];
                    }
                }
            } else {
665
                $typeNum = $row[$field] ?? 0;
666
667
668
669
670
671
672
            }
            // If that value is an empty string, set it to "0" (zero)
            if (empty($typeNum)) {
                $typeNum = 0;
            }
        }
        // If current typeNum doesn't exist, set it to 0 (or to 1 for historical reasons, if 0 doesn't exist)
673
674
        if (!isset($GLOBALS['TCA'][$table]['types'][$typeNum]) || !$GLOBALS['TCA'][$table]['types'][$typeNum]) {
            $typeNum = isset($GLOBALS['TCA'][$table]['types']['0']) ? 0 : 1;
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
        }
        // Force to string. Necessary for eg '-1' to be recognized as a type value.
        $typeNum = (string)$typeNum;
        return $typeNum;
    }

    /*******************************************
     *
     * TypoScript related
     *
     *******************************************/
    /**
     * Returns the Page TSconfig for page with id, $id
     *
     * @param int $id Page uid for which to create Page TSconfig
     * @return array Page TSconfig
     * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
     */
693
    public static function getPagesTSconfig($id)
694
695
    {
        $id = (int)$id;
696
697

        $cache = self::getRuntimeCache();
698
699
700
        $pagesTsConfigIdToHash = $cache->get('pagesTsConfigIdToHash' . $id);
        if ($pagesTsConfigIdToHash !== false) {
            return $cache->get('pagesTsConfigHashToContent' . $pagesTsConfigIdToHash);
701
702
        }

703
        $rootLine = self::BEgetRootLine($id, '', true);
704
705
706
        // Order correctly
        ksort($rootLine);

707
708
709
710
711
712
        try {
            $site = GeneralUtility::makeInstance(SiteFinder::class)->getSiteByPageId($id);
        } catch (SiteNotFoundException $exception) {
            $site = null;
        }

713
714
715
716
717
718
719
720
721
722
        // Load PageTS from all pages of the rootLine
        $pageTs = GeneralUtility::makeInstance(PageTsConfigLoader::class)->load($rootLine);

        // Parse the PageTS into an array, also applying conditions
        $parser = GeneralUtility::makeInstance(
            PageTsConfigParser::class,
            GeneralUtility::makeInstance(TypoScriptParser::class),
            GeneralUtility::makeInstance(CacheManager::class)->getCache('hash')
        );
        $matcher = GeneralUtility::makeInstance(ConditionMatcher::class, null, $id, $rootLine);
723
        $tsConfig = $parser->parse($pageTs, $matcher, $site);
724
        $cacheHash = md5((string)json_encode($tsConfig));
725

726
727
728
729
730
731
        // Get User TSconfig overlay, if no backend user is logged-in, this needs to be checked as well
        if (static::getBackendUserAuthentication()) {
            $userTSconfig = static::getBackendUserAuthentication()->getTSConfig() ?? [];
        } else {
            $userTSconfig = [];
        }
732

733
        if (is_array($userTSconfig['page.'] ?? null)) {
734
            // Override page TSconfig with user TSconfig
735
            ArrayUtility::mergeRecursiveWithOverrule($tsConfig, $userTSconfig['page.']);
736
737
738
            $cacheHash .= '_user' . static::getBackendUserAuthentication()->user['uid'];
        }

739
740
741
742
743
        // Many pages end up with the same ts config. To reduce memory usage, the cache
        // entries are a linked list: One or more pids point to content hashes which then
        // contain the cached content.
        $cache->set('pagesTsConfigHashToContent' . $cacheHash, $tsConfig, ['pagesTsConfig']);
        $cache->set('pagesTsConfigIdToHash' . $id, $cacheHash, ['pagesTsConfig']);
744
745
746
747

        return $tsConfig;
    }

748
749
750
751
752
753
754
755
756
    /*******************************************
     *
     * Users / Groups related
     *
     *******************************************/
    /**
     * Returns an array with be_users records of all user NOT DELETED sorted by their username
     * Keys in the array is the be_users uid
     *
757
     * @param string $fields Optional $fields list (default: username,usergroup,uid) can be used to set the selected fields
758
759
     * @param string $where Optional $where clause (fx. "AND username='pete'") can be used to limit query
     * @return array
760
     * @internal should only be used from within TYPO3 Core, use a direct SQL query instead to ensure proper DBAL where statements
761
     */
762
    public static function getUserNames($fields = 'username,usergroup,uid', $where = '')
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
    {
        return self::getRecordsSortedByTitle(
            GeneralUtility::trimExplode(',', $fields, true),
            'be_users',
            'username',
            'AND pid=0 ' . $where
        );
    }

    /**
     * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
     *
     * @param string $fields Field list
     * @param string $where WHERE clause
     * @return array
778
     * @internal should only be used from within TYPO3 Core, use a direct SQL query instead to ensure proper DBAL where statements
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
     */
    public static function getGroupNames($fields = 'title,uid', $where = '')
    {
        return self::getRecordsSortedByTitle(
            GeneralUtility::trimExplode(',', $fields, true),
            'be_groups',
            'title',
            'AND pid=0 ' . $where
        );
    }

    /**
     * Returns an array of all non-deleted records of a table sorted by a given title field.
     * The value of the title field will be replaced by the return value
     * of self::getRecordTitle() before the sorting is performed.
     *
     * @param array $fields Fields to select
     * @param string $table Table name
     * @param string $titleField Field that will contain the record title
     * @param string $where Additional where clause
     * @return array Array of sorted records
     */
    protected static function getRecordsSortedByTitle(array $fields, $table, $titleField, $where = '')
    {
        $fieldsIndex = array_flip($fields);
        // Make sure the titleField is amongst the fields when getting sorted
        $fieldsIndex[$titleField] = 1;

807
808
809
810
811
812
813
814
815
816
817
818
819
        $result = [];

        $queryBuilder = static::getQueryBuilderForTable($table);
        $queryBuilder->getRestrictions()
            ->removeAll()
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));

        $res = $queryBuilder
            ->select('*')
            ->from($table)
            ->where(QueryHelper::stripLogicalOperatorPrefix($where))
            ->execute();

820
        while ($record = $res->fetchAssociative()) {
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
            // store the uid, because it might be unset if it's not among the requested $fields
            $recordId = $record['uid'];
            $record[$titleField] = self::getRecordTitle($table, $record);

            // include only the requested fields in the result
            $result[$recordId] = array_intersect_key($record, $fieldsIndex);
        }

        // sort records by $sortField. This is not done in the query because the title might have been overwritten by
        // self::getRecordTitle();
        return ArrayUtility::sortArraysByKey($result, $titleField);
    }

    /*******************************************
     *
     * Output related
     *
     *******************************************/
    /**
     * Returns the difference in days between input $tstamp and $EXEC_TIME
     *
     * @param int $tstamp Time stamp, seconds
     * @return int
     */
    public static function daysUntil($tstamp)
    {
        $delta_t = $tstamp - $GLOBALS['EXEC_TIME'];
        return ceil($delta_t / (3600 * 24));
    }

    /**
     * Returns $tstamp formatted as "ddmmyy" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'])
     *
     * @param int $tstamp Time stamp, seconds
     * @return string Formatted time
     */
    public static function date($tstamp)
    {
        return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int)$tstamp);
    }

    /**
     * Returns $tstamp formatted as "ddmmyy hhmm" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] AND $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'])
     *
     * @param int $value Time stamp, seconds
     * @return string Formatted time
     */
    public static function datetime($value)
    {
870
871
872
873
        return date(
            $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'],
            $value
        );
874
875
876
877
878
879
880
881
882
883
884
885
    }

    /**
     * Returns $value (in seconds) formatted as hh:mm:ss
     * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
     *
     * @param int $value Time stamp, seconds
     * @param bool $withSeconds Output hh:mm:ss. If FALSE: hh:mm
     * @return string Formatted time
     */
    public static function time($value, $withSeconds = true)
    {
886
        return gmdate('H:i' . ($withSeconds ? ':s' : ''), (int)$value);
887
888
889
890
891
892
    }

    /**
     * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
     *
     * @param int $seconds Seconds could be the difference of a certain timestamp and time()
893
     * @param string $labels Labels should be something like ' min| hrs| days| yrs| min| hour| day| year'. This value is typically delivered by this function call: $GLOBALS["LANG"]->sL("LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears")
894
895
     * @return string Formatted time
     */
896
    public static function calcAge($seconds, $labels = 'min|hrs|days|yrs|min|hour|day|year')
897
    {
898
        $labelArr = GeneralUtility::trimExplode('|', $labels, true);
899
900
901
902
        $absSeconds = abs($seconds);
        $sign = $seconds < 0 ? -1 : 1;
        if ($absSeconds < 3600) {
            $val = round($absSeconds / 60);
903
            $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[4] : $labelArr[0]);
904
905
        } elseif ($absSeconds < 24 * 3600) {
            $val = round($absSeconds / 3600);
906
            $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[5] : $labelArr[1]);
907
908
        } elseif ($absSeconds < 365 * 24 * 3600) {
            $val = round($absSeconds / (24 * 3600));
909
            $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[6] : $labelArr[2]);
910
911
        } else {
            $val = round($absSeconds / (365 * 24 * 3600));
912
            $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[7] : $labelArr[3]);
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
        }
        return $seconds;
    }

    /**
     * Returns a formatted timestamp if $tstamp is set.
     * The date/datetime will be followed by the age in parenthesis.
     *
     * @param int $tstamp Time stamp, seconds
     * @param int $prefix 1/-1 depending on polarity of age.
     * @param string $date $date=="date" will yield "dd:mm:yy" formatting, otherwise "dd:mm:yy hh:mm
     * @return string
     */
    public static function dateTimeAge($tstamp, $prefix = 1, $date = '')
    {
        if (!$tstamp) {
            return '';
        }
931
        $label = static::getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears');
932
        $age = ' (' . self::calcAge($prefix * ($GLOBALS['EXEC_TIME'] - $tstamp), $label) . ')';
933
        return ($date === 'date' ? self::date($tstamp) : self::datetime($tstamp)) . $age;
934
935
936
937
938
939
940
941
    }

    /**
     * Resolves file references for a given record.
     *
     * @param string $tableName Name of the table of the record
     * @param string $fieldName Name of the field of the record
     * @param array $element Record data
942
943
     * @param int|null $workspaceId Workspace to fetch data for
     * @return \TYPO3\CMS\Core\Resource\FileReference[]|null
944
945
946
947
948
949
950
951
     */
    public static function resolveFileReferences($tableName, $fieldName, $element, $workspaceId = null)
    {
        if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'])) {
            return null;
        }
        $configuration = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
        if (empty($configuration['type']) || $configuration['type'] !== 'inline'
952
953
            || empty($configuration['foreign_table']) || $configuration['foreign_table'] !== 'sys_file_reference'
        ) {
954
955
956
            return null;
        }

957
        $fileReferences = [];
958
        /** @var RelationHandler $relationHandler */
959
960
961
962
        $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
        if ($workspaceId !== null) {
            $relationHandler->setWorkspaceId($workspaceId);
        }
963
964
965
        $relationHandler->start(
            $element[$fieldName],
            $configuration['foreign_table'],
966
            $configuration['MM'] ?? '',
967
968
969
970
            $element['uid'],
            $tableName,
            $configuration
        );
971
972
973
974
975
        $relationHandler->processDeletePlaceholder();
        $referenceUids = $relationHandler->tableArray[$configuration['foreign_table']];

        foreach ($referenceUids as $referenceUid) {
            try {
976
                $fileReference = GeneralUtility::makeInstance(ResourceFactory::class)->getFileReferenceObject(
977
                    $referenceUid,
978
                    [],
979
                    $workspaceId === 0
980
                );
981
                $fileReferences[$fileReference->getUid()] = $fileReference;
982
            } catch (FileDoesNotExistException $e) {
983
984
985
986
987
988
989
990
991
                /**
                 * We just catch the exception here
                 * Reasoning: There is nothing an editor or even admin could do
                 */
            } catch (\InvalidArgumentException $e) {
                /**
                 * The storage does not exist anymore
                 * Log the exception message for admins as they maybe can restore the storage
                 */
992
993
994
995
996
997
                self::getLogger()->error($e->getMessage(), [
                    'table' => $tableName,
                    'fieldName' => $fieldName,
                    'referenceUid' => $referenceUid,
                    'exception' => $e,
                ]);
998
999
1000
1001
1002
1003
1004
            }
        }

        return $fileReferences;
    }

    /**
1005
     * Returns a linked image-tag for thumbnail(s)/fileicons/truetype-font-previews from a database row with sys_file_references
1006
     * All $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] extension are made to thumbnails + ttf file (renders font-example)
1007
     * Thumbnails are linked to ShowItemController (/thumbnails route)
1008
1009
1010
     *
     * @param array $row Row is the database row from the table, $table.
     * @param string $table Table name for $row (present in TCA)
1011
     * @param string $field Field is pointing to the connecting field of sys_file_references
1012
1013
     * @param string $backPath Back path prefix for image tag src="" field
     * @param string $thumbScript UNUSED since FAL
1014
     * @param string $uploaddir UNUSED since FAL
1015
1016
1017
1018
1019
1020
     * @param int $abs UNUSED
     * @param string $tparams Optional: $tparams is additional attributes for the image tags
     * @param int|string $size Optional: $size is [w]x[h] of the thumbnail. 64 is default.
     * @param bool $linkInfoPopup Whether to wrap with a link opening the info popup
     * @return string Thumbnail image tag.
     */
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
    public static function thumbCode(
        $row,
        $table,
        $field,
        $backPath = '',
        $thumbScript = '',
        $uploaddir = null,
        $abs = 0,
        $tparams = '',
        $size = '',
        $linkInfoPopup = true
    ) {
1033
1034
        $size = (int)(trim((string)$size) ?: 64);
        $targetDimension = new ImageDimension($size, $size);
1035
1036
1037
1038
1039
1040
        $thumbData = '';
        $fileReferences = static::resolveFileReferences($table, $field, $row);
        // FAL references
        $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
        if ($fileReferences !== null) {
            foreach ($fileReferences as $fileReferenceObject) {
1041
1042
1043
1044
                // Do not show previews of hidden references
                if ($fileReferenceObject->getProperty('hidden')) {
                    continue;
                }
1045
1046
1047
                $fileObject = $fileReferenceObject->getOriginalFile();

                if ($fileObject->isMissing()) {
1048
                    $thumbData .= '<span class="label label-danger">'
1049
                        . htmlspecialchars(
1050
                            static::getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:warning.file_missing')
1051
                        )
1052
                        . '</span>&nbsp;' . htmlspecialchars($fileObject->getName()) . '<br />';
1053
1054
1055
1056
                    continue;
                }

                // Preview web image or media elements
1057
                if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails']
1058
                    && $fileReferenceObject->getOriginalFile()->isImage()
1059
                ) {
1060
1061
                    $cropVariantCollection = CropVariantCollection::create((string)$fileReferenceObject->getProperty('crop'));
                    $cropArea = $cropVariantCollection->getCropArea();
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
                    $taskType = ProcessedFile::CONTEXT_IMAGEPREVIEW;
                    $processingConfiguration = [
                        'width' => $targetDimension->getWidth(),
                        'height' => $targetDimension->getHeight(),
                    ];
                    if (!$cropArea->isEmpty()) {
                        $taskType = ProcessedFile::CONTEXT_IMAGECROPSCALEMASK;
                        $processingConfiguration = [
                            'maxWidth' => $targetDimension->getWidth(),
                            'maxHeight' => $targetDimension->getHeight(),
                            'crop' => $cropArea->makeAbsoluteBasedOnFile($fileReferenceObject),
                        ];
                    }
                    $processedImage = $fileObject->process($taskType, $processingConfiguration);
1076
                    $attributes = [
1077
                        'src' => $processedImage->getPublicUrl() ?? '',
1078
1079
                        'width' => $processedImage->getProperty('width'),
                        'height' => $processedImage->getProperty('height'),
1080
1081
                        'alt' => $fileReferenceObject->getName(),
                    ];
1082
                    $imgTag = '<img ' . GeneralUtility::implodeAttributes($attributes, true) . $tparams . '/>';
1083
1084
                } else {
                    // Icon
1085
1086
1087
                    $imgTag = '<span title="' . htmlspecialchars($fileObject->getName()) . '">'
                        . $iconFactory->getIconForResource($fileObject, Icon::SIZE_SMALL)->render()
                        . '</span>';
1088
1089
                }
                if ($linkInfoPopup) {
1090
                    // relies on module 'TYPO3/CMS/Backend/ActionDispatcher'
1091
1092
1093
1094
1095
                    $attributes = GeneralUtility::implodeAttributes([
                        'data-dispatch-action' => 'TYPO3.InfoWindow.showItem',
                        'data-dispatch-args-list' => '_FILE,' . (int)$fileObject->getUid(),
                    ], true);
                    $thumbData .= '<a href="#" ' . $attributes . '>' . $imgTag . '</a> ';
1096
1097
1098
1099
1100
1101
1102
1103
                } else {
                    $thumbData .= $imgTag;
                }
            }
        }
        return $thumbData;
    }

1104
1105
1106
1107
1108
1109
1110
    /**
     * @param int $fileId
     * @param array $configuration
     * @return string
     */
    public static function getThumbnailUrl(int $fileId, array $configuration): string
    {
1111
1112
1113
1114
1115
1116
1117
        $taskType = $configuration['_context'] ?? ProcessedFile::CONTEXT_IMAGEPREVIEW;
        unset($configuration['_context']);

        return GeneralUtility::makeInstance(ResourceFactory::class)
                ->getFileObject($fileId)
                ->process($taskType, $configuration)
                ->getPublicUrl(true);
1118
1119
    }

1120
    /**
1121
     * Returns title-attribute information for a page-record informing about id, doktype, hidden, starttime, endtime, fe_group etc.
1122
1123
1124
1125
1126
1127
1128
1129
1130
     *
     * @param array $row Input must be a page row ($row) with the proper fields set (be sure - send the full range of fields for the table)
     * @param string $perms_clause This is used to get the record path of the shortcut page, if any (and doktype==4)
     * @param bool $includeAttrib If $includeAttrib is set, then the 'title=""' attribute is wrapped about the return value, which is in any case htmlspecialchar()'ed already
     * @return string
     */
    public static function titleAttribForPages($row, $perms_clause = '', $includeAttrib = true)
    {
        $lang = static::getLanguageService();
1131
        $parts = [];
1132
        $parts[] = 'id=' . $row['uid'];
1133
1134
1135
1136
        if ($row['uid'] === 0) {
            $out = htmlspecialchars($parts[0]);
            return $includeAttrib ? 'title="' . $out . '"' : $out;
        }
1137
1138
1139
1140
1141
        switch (VersionState::cast($row['t3ver_state'])) {
            case new VersionState(VersionState::DELETE_PLACEHOLDER):
                $parts[] = 'Deleted element!';
                break;
            case new VersionState(VersionState::MOVE_POINTER):
1142
                $parts[] = 'NEW LOCATION (Move-to Pointer) WSID#' . $row['t3ver_wsid'];
1143
                break;
1144
            case new VersionState(VersionState::NEW_PLACEHOLDER):
1145
1146
1147
1148
                $parts[] = 'New element!';
                break;
        }
        if ($row['doktype'] == PageRepository::DOKTYPE_LINK) {
crell's avatar
crell committed
1149
            $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['url']['label'] ?? '') . ' ' . ($row['url'] ?? '');
1150
1151
1152
1153
        } elseif ($row['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
            if ($perms_clause) {
                $label = self::getRecordPath((int)$row['shortcut'], $perms_clause, 20);
            } else {
crell's avatar
crell committed
1154
                $row['shortcut'] = (int)($row['shortcut'] ?? 0);
1155
                $lRec = self::getRecordWSOL('pages', $row['shortcut'], 'title');
1156
                $label = ($lRec === null ? '' : $lRec['title']) . ' (id=' . $row['shortcut'] . ')';
1157
            }
crell's avatar
crell committed
1158
            if (($row['shortcut_mode'] ?? 0) != PageRepository::SHORTCUT_MODE_NONE) {
1159
1160
                $label .= ', ' . $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut_mode']['label']) . ' '
                    . $lang->sL(self::getLabelFromItemlist('pages', 'shortcut_mode', $row['shortcut_mode']));
1161
1162
1163
            }
            $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut']['label']) . ' ' . $label;
        } elseif ($row['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT) {
1164
1165
1166
1167
1168
1169
1170
1171
            if ((int)$row['mount_pid'] > 0) {
                if ($perms_clause) {
                    $label = self::getRecordPath((int)$row['mount_pid'], $perms_clause, 20);
                } else {
                    $lRec = self::getRecordWSOL('pages', (int)$row['mount_pid'], 'title');
                    $label = $lRec['title'] . ' (id=' . $row['mount_pid'] . ')';
                }
                $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid']['label']) . ' ' . $label;
crell's avatar
crell committed
1172
                if ($row['mount_pid_ol'] ?? 0) {
1173
1174
                    $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid_ol']['label']);
                }
1175
            } else {
1176
                $parts[] = $lang->sL('LLL:EXT:frontend/Resources/Private/Language/locallang_tca.xlf:no_mount_pid');
1177
1178
1179
            }
        }
        if ($row['nav_hide']) {
1180
            $parts[] = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_tca.xlf:pages.nav_hide');
1181
1182
        }
        if ($row['hidden']) {
1183
            $parts[] = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.hidden');
1184
1185
        }
        if ($row['starttime']) {
1186
1187
            $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['starttime']['label'])
                . ' ' . self::dateTimeAge($row['starttime'], -1, 'date');
1188
1189
        }
        if ($row['endtime']) {
1190
1191
            $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['endtime']['label']) . ' '
                . self::dateTimeAge($row['endtime'], -1, 'date');
1192
1193
        }
        if ($row['fe_group']) {
1194
            $fe_groups = [];
1195
1196
            foreach (GeneralUtility::intExplode(',', $row['fe_group']) as $fe_group) {
                if ($fe_group < 0