Passed
Push — master ( 2388af...d5a28b )
by
unknown
27:07 queued 14:54
created

BackendUtility::viewOnClick()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 28
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 15
c 0
b 0
f 0
nc 3
nop 7
dl 0
loc 28
rs 9.7666
1
<?php
2
3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
 * It is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License, either version 2
8
 * of the License, or any later version.
9
 *
10
 * For the full copyright and license information, please read the
11
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
 * The TYPO3 project - inspiring people to share!
14
 */
15
16
namespace TYPO3\CMS\Backend\Utility;
17
18
use Psr\Http\Message\ServerRequestInterface;
19
use Psr\Log\LoggerInterface;
20
use TYPO3\CMS\Backend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
21
use TYPO3\CMS\Backend\Routing\Route;
22
use TYPO3\CMS\Backend\Routing\UriBuilder;
23
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
24
use TYPO3\CMS\Core\Cache\CacheManager;
25
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
26
use TYPO3\CMS\Core\Configuration\Loader\PageTsConfigLoader;
27
use TYPO3\CMS\Core\Configuration\Parser\PageTsConfigParser;
28
use TYPO3\CMS\Core\Context\Context;
29
use TYPO3\CMS\Core\Context\DateTimeAspect;
30
use TYPO3\CMS\Core\Core\Environment;
31
use TYPO3\CMS\Core\Database\Connection;
32
use TYPO3\CMS\Core\Database\ConnectionPool;
33
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
34
use TYPO3\CMS\Core\Database\Query\QueryHelper;
35
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
36
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
37
use TYPO3\CMS\Core\Database\Query\Restriction\WorkspaceRestriction;
38
use TYPO3\CMS\Core\Database\RelationHandler;
39
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
40
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
41
use TYPO3\CMS\Core\Imaging\Icon;
42
use TYPO3\CMS\Core\Imaging\IconFactory;
43
use TYPO3\CMS\Core\Imaging\ImageDimension;
44
use TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection;
45
use TYPO3\CMS\Core\Localization\LanguageService;
46
use TYPO3\CMS\Core\Log\LogManager;
47
use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;
48
use TYPO3\CMS\Core\Resource\ProcessedFile;
49
use TYPO3\CMS\Core\Resource\ResourceFactory;
50
use TYPO3\CMS\Core\Routing\InvalidRouteArgumentsException;
51
use TYPO3\CMS\Core\Routing\RouterInterface;
52
use TYPO3\CMS\Core\Routing\UnableToLinkToPageException;
53
use TYPO3\CMS\Core\Site\SiteFinder;
54
use TYPO3\CMS\Core\Type\Bitmask\Permission;
55
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
56
use TYPO3\CMS\Core\Utility\ArrayUtility;
57
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
58
use TYPO3\CMS\Core\Utility\GeneralUtility;
59
use TYPO3\CMS\Core\Utility\HttpUtility;
60
use TYPO3\CMS\Core\Utility\MathUtility;
61
use TYPO3\CMS\Core\Utility\PathUtility;
62
use TYPO3\CMS\Core\Utility\StringUtility;
63
use TYPO3\CMS\Core\Versioning\VersionState;
64
65
/**
66
 * Standard functions available for the TYPO3 backend.
67
 * You are encouraged to use this class in your own applications (Backend Modules)
68
 * Don't instantiate - call functions with "\TYPO3\CMS\Backend\Utility\BackendUtility::" prefixed the function name.
69
 *
70
 * Call ALL methods without making an object!
71
 * Eg. to get a page-record 51 do this: '\TYPO3\CMS\Backend\Utility\BackendUtility::getRecord('pages',51)'
72
 */
73
class BackendUtility
74
{
75
    /*******************************************
76
     *
77
     * SQL-related, selecting records, searching
78
     *
79
     *******************************************/
80
    /**
81
     * Gets record with uid = $uid from $table
82
     * You can set $field to a list of fields (default is '*')
83
     * Additional WHERE clauses can be added by $where (fx. ' AND some_field = 1')
84
     * Will automatically check if records has been deleted and if so, not return anything.
85
     * $table must be found in $GLOBALS['TCA']
86
     *
87
     * @param string $table Table name present in $GLOBALS['TCA']
88
     * @param int $uid UID of record
89
     * @param string $fields List of fields to select
90
     * @param string $where Additional WHERE clause, eg. ' AND some_field = 0'
91
     * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
92
     * @return array|null Returns the row if found, otherwise NULL
93
     */
94
    public static function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = true)
95
    {
96
        // Ensure we have a valid uid (not 0 and not NEWxxxx) and a valid TCA
97
        if ((int)$uid && !empty($GLOBALS['TCA'][$table])) {
98
            $queryBuilder = static::getQueryBuilderForTable($table);
99
100
            // do not use enabled fields here
101
            $queryBuilder->getRestrictions()->removeAll();
102
103
            // should the delete clause be used
104
            if ($useDeleteClause) {
105
                $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
106
            }
107
108
            // set table and where clause
109
            $queryBuilder
110
                ->select(...GeneralUtility::trimExplode(',', $fields, true))
111
                ->from($table)
112
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter((int)$uid, \PDO::PARAM_INT)));
113
114
            // add custom where clause
115
            if ($where) {
116
                $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($where));
117
            }
118
119
            $row = $queryBuilder->execute()->fetch();
120
            if ($row) {
121
                return $row;
122
            }
123
        }
124
        return null;
125
    }
126
127
    /**
128
     * Like getRecord(), but overlays workspace version if any.
129
     *
130
     * @param string $table Table name present in $GLOBALS['TCA']
131
     * @param int $uid UID of record
132
     * @param string $fields List of fields to select
133
     * @param string $where Additional WHERE clause, eg. ' AND some_field = 0'
134
     * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
135
     * @param bool $unsetMovePointers If TRUE the function does not return a "pointer" row for moved records in a workspace
136
     * @return array Returns the row if found, otherwise nothing
137
     */
138
    public static function getRecordWSOL(
139
        $table,
140
        $uid,
141
        $fields = '*',
142
        $where = '',
143
        $useDeleteClause = true,
144
        $unsetMovePointers = false
145
    ) {
146
        if ($fields !== '*') {
147
            $internalFields = StringUtility::uniqueList($fields . ',uid,pid');
148
            $row = self::getRecord($table, $uid, $internalFields, $where, $useDeleteClause);
149
            self::workspaceOL($table, $row, -99, $unsetMovePointers);
150
            if (is_array($row)) {
151
                foreach ($row as $key => $_) {
152
                    if (!GeneralUtility::inList($fields, $key) && $key[0] !== '_') {
153
                        unset($row[$key]);
154
                    }
155
                }
156
            }
157
        } else {
158
            $row = self::getRecord($table, $uid, $fields, $where, $useDeleteClause);
159
            self::workspaceOL($table, $row, -99, $unsetMovePointers);
160
        }
161
        return $row;
162
    }
163
164
    /**
165
     * Purges computed properties starting with underscore character ('_').
166
     *
167
     * @param array<string,mixed> $record
168
     * @return array<string,mixed>
169
     * @internal should only be used from within TYPO3 Core
170
     */
171
    public static function purgeComputedPropertiesFromRecord(array $record): array
172
    {
173
        return array_filter(
174
            $record,
175
            function (string $propertyName): bool {
176
                return $propertyName[0] !== '_';
177
            },
178
            ARRAY_FILTER_USE_KEY
179
        );
180
    }
181
182
    /**
183
     * Purges computed property names starting with underscore character ('_').
184
     *
185
     * @param array $propertyNames
186
     * @return array
187
     * @internal should only be used from within TYPO3 Core
188
     */
189
    public static function purgeComputedPropertyNames(array $propertyNames): array
190
    {
191
        return array_filter(
192
            $propertyNames,
193
            function (string $propertyName): bool {
194
                return $propertyName[0] !== '_';
195
            }
196
        );
197
    }
198
199
    /**
200
     * Makes a backwards explode on the $str and returns an array with ($table, $uid).
201
     * Example: tt_content_45 => ['tt_content', 45]
202
     *
203
     * @param string $str [tablename]_[uid] string to explode
204
     * @return array
205
     * @internal should only be used from within TYPO3 Core
206
     */
207
    public static function splitTable_Uid($str)
208
    {
209
        $split = explode('_', strrev($str), 2);
210
        $uid = $split[0];
211
        $table = $split[1] ?? '';
212
        return [strrev($table), strrev($uid)];
213
    }
214
215
    /**
216
     * Backend implementation of enableFields()
217
     * Notice that "fe_groups" is not selected for - only disabled, starttime and endtime.
218
     * Notice that deleted-fields are NOT filtered - you must ALSO call deleteClause in addition.
219
     * $GLOBALS["SIM_ACCESS_TIME"] is used for date.
220
     *
221
     * @param string $table The table from which to return enableFields WHERE clause. Table name must have a 'ctrl' section in $GLOBALS['TCA'].
222
     * @param bool $inv Means that the query will select all records NOT VISIBLE records (inverted selection)
223
     * @return string WHERE clause part
224
     * @internal should only be used from within TYPO3 Core, but DefaultRestrictionHandler is recommended as alternative
225
     */
226
    public static function BEenableFields($table, $inv = false)
227
    {
228
        $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
229
        $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
230
            ->getConnectionForTable($table)
231
            ->getExpressionBuilder();
232
        $query = $expressionBuilder->andX();
233
        $invQuery = $expressionBuilder->orX();
234
235
        if (is_array($ctrl)) {
236
            if (is_array($ctrl['enablecolumns'])) {
237
                if ($ctrl['enablecolumns']['disabled'] ?? false) {
238
                    $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
239
                    $query->add($expressionBuilder->eq($field, 0));
240
                    $invQuery->add($expressionBuilder->neq($field, 0));
241
                }
242
                if ($ctrl['enablecolumns']['starttime'] ?? false) {
243
                    $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
244
                    $query->add($expressionBuilder->lte($field, (int)$GLOBALS['SIM_ACCESS_TIME']));
245
                    $invQuery->add(
246
                        $expressionBuilder->andX(
247
                            $expressionBuilder->neq($field, 0),
248
                            $expressionBuilder->gt($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
249
                        )
250
                    );
251
                }
252
                if ($ctrl['enablecolumns']['endtime'] ?? false) {
253
                    $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
254
                    $query->add(
255
                        $expressionBuilder->orX(
256
                            $expressionBuilder->eq($field, 0),
257
                            $expressionBuilder->gt($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
258
                        )
259
                    );
260
                    $invQuery->add(
261
                        $expressionBuilder->andX(
262
                            $expressionBuilder->neq($field, 0),
263
                            $expressionBuilder->lte($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
264
                        )
265
                    );
266
                }
267
            }
268
        }
269
270
        if ($query->count() === 0) {
271
            return '';
272
        }
273
274
        return ' AND ' . ($inv ? $invQuery : $query);
275
    }
276
277
    /**
278
     * Fetches the localization for a given record.
279
     *
280
     * @param string $table Table name present in $GLOBALS['TCA']
281
     * @param int $uid The uid of the record
282
     * @param int $language The uid of the language record in sys_language
283
     * @param string $andWhereClause Optional additional WHERE clause (default: '')
284
     * @return mixed Multidimensional array with selected records, empty array if none exists and FALSE if table is not localizable
285
     */
286
    public static function getRecordLocalization($table, $uid, $language, $andWhereClause = '')
287
    {
288
        $recordLocalization = false;
289
290
        if (self::isTableLocalizable($table)) {
291
            $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
292
293
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
294
                ->getQueryBuilderForTable($table);
295
            $queryBuilder->getRestrictions()
296
                ->removeAll()
297
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
298
                ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, static::getBackendUserAuthentication()->workspace ?? 0));
299
300
            $queryBuilder->select('*')
301
                ->from($table)
302
                ->where(
303
                    $queryBuilder->expr()->eq(
304
                        $tcaCtrl['translationSource'] ?? $tcaCtrl['transOrigPointerField'],
305
                        $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
306
                    ),
307
                    $queryBuilder->expr()->eq(
308
                        $tcaCtrl['languageField'],
309
                        $queryBuilder->createNamedParameter((int)$language, \PDO::PARAM_INT)
310
                    )
311
                )
312
                ->setMaxResults(1);
313
314
            if ($andWhereClause) {
315
                $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($andWhereClause));
316
            }
317
318
            $recordLocalization = $queryBuilder->execute()->fetchAll();
319
        }
320
321
        return $recordLocalization;
322
    }
323
324
    /*******************************************
325
     *
326
     * Page tree, TCA related
327
     *
328
     *******************************************/
329
    /**
330
     * Returns what is called the 'RootLine'. That is an array with information about the page records from a page id
331
     * ($uid) and back to the root.
332
     * By default deleted pages are filtered.
333
     * This RootLine will follow the tree all the way to the root. This is opposite to another kind of root line known
334
     * from the frontend where the rootline stops when a root-template is found.
335
     *
336
     * @param int $uid Page id for which to create the root line.
337
     * @param string $clause Clause can be used to select other criteria. It would typically be where-clauses that
338
     *          stops the process if we meet a page, the user has no reading access to.
339
     * @param bool $workspaceOL If TRUE, version overlay is applied. This must be requested specifically because it is
340
     *          usually only wanted when the rootline is used for visual output while for permission checking you want the raw thing!
341
     * @param string[] $additionalFields Additional Fields to select for rootline records
342
     * @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
343
     */
344
    public static function BEgetRootLine($uid, $clause = '', $workspaceOL = false, array $additionalFields = [])
345
    {
346
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
347
        $beGetRootLineCache = $runtimeCache->get('backendUtilityBeGetRootLine') ?: [];
348
        $output = [];
349
        $pid = $uid;
350
        $ident = $pid . '-' . $clause . '-' . $workspaceOL . ($additionalFields ? '-' . md5(implode(',', $additionalFields)) : '');
351
        if (is_array($beGetRootLineCache[$ident] ?? false)) {
352
            $output = $beGetRootLineCache[$ident];
353
        } else {
354
            $loopCheck = 100;
355
            $theRowArray = [];
356
            while ($uid != 0 && $loopCheck) {
357
                $loopCheck--;
358
                $row = self::getPageForRootline($uid, $clause, $workspaceOL, $additionalFields);
359
                if (is_array($row)) {
360
                    $uid = $row['pid'];
361
                    $theRowArray[] = $row;
362
                } else {
363
                    break;
364
                }
365
            }
366
            $fields = [
367
                'uid',
368
                'pid',
369
                'title',
370
                'doktype',
371
                'slug',
372
                'tsconfig_includes',
373
                'TSconfig',
374
                'is_siteroot',
375
                't3ver_oid',
376
                't3ver_wsid',
377
                't3ver_state',
378
                't3ver_stage',
379
                'backend_layout_next_level',
380
                'hidden',
381
                'starttime',
382
                'endtime',
383
                'fe_group',
384
                'nav_hide',
385
                'content_from_pid',
386
                'module',
387
                'extendToSubpages'
388
            ];
389
            $fields = array_merge($fields, $additionalFields);
390
            $rootPage = array_fill_keys($fields, null);
391
            if ($uid == 0) {
392
                $rootPage['uid'] = 0;
393
                $theRowArray[] = $rootPage;
394
            }
395
            $c = count($theRowArray);
396
            foreach ($theRowArray as $val) {
397
                $c--;
398
                $output[$c] = array_intersect_key($val, $rootPage);
399
                if (isset($val['_ORIG_pid'])) {
400
                    $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
401
                }
402
            }
403
            $beGetRootLineCache[$ident] = $output;
404
            $runtimeCache->set('backendUtilityBeGetRootLine', $beGetRootLineCache);
405
        }
406
        return $output;
407
    }
408
409
    /**
410
     * Gets the cached page record for the rootline
411
     *
412
     * @param int $uid Page id for which to create the root line.
413
     * @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.
414
     * @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!
415
     * @param string[] $additionalFields AdditionalFields to fetch from the root line
416
     * @return array Cached page record for the rootline
417
     * @see BEgetRootLine
418
     */
419
    protected static function getPageForRootline($uid, $clause, $workspaceOL, array $additionalFields = [])
420
    {
421
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
422
        $pageForRootlineCache = $runtimeCache->get('backendUtilityPageForRootLine') ?: [];
423
        $statementCacheIdent = md5($clause . ($additionalFields ? '-' . implode(',', $additionalFields) : ''));
424
        $ident = $uid . '-' . $workspaceOL . '-' . $statementCacheIdent;
425
        if (is_array($pageForRootlineCache[$ident] ?? false)) {
426
            $row = $pageForRootlineCache[$ident];
427
        } else {
428
            $statement = $runtimeCache->get('getPageForRootlineStatement-' . $statementCacheIdent);
429
            if (!$statement) {
430
                $queryBuilder = static::getQueryBuilderForTable('pages');
431
                $queryBuilder->getRestrictions()
432
                             ->removeAll()
433
                             ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
434
435
                $queryBuilder
436
                    ->select(
437
                        'pid',
438
                        'uid',
439
                        'title',
440
                        'doktype',
441
                        'slug',
442
                        'tsconfig_includes',
443
                        'TSconfig',
444
                        'is_siteroot',
445
                        't3ver_oid',
446
                        't3ver_wsid',
447
                        't3ver_state',
448
                        't3ver_stage',
449
                        'backend_layout_next_level',
450
                        'hidden',
451
                        'starttime',
452
                        'endtime',
453
                        'fe_group',
454
                        'nav_hide',
455
                        'content_from_pid',
456
                        'module',
457
                        'extendToSubpages',
458
                        ...$additionalFields
459
                    )
460
                    ->from('pages')
461
                    ->where(
462
                        $queryBuilder->expr()->eq('uid', $queryBuilder->createPositionalParameter($uid, \PDO::PARAM_INT)),
463
                        QueryHelper::stripLogicalOperatorPrefix($clause)
464
                    );
465
                $statement = $queryBuilder->execute();
466
                if (class_exists(\Doctrine\DBAL\ForwardCompatibility\Result::class) && $statement instanceof \Doctrine\DBAL\ForwardCompatibility\Result) {
0 ignored issues
show
Bug introduced by
The type Doctrine\DBAL\ForwardCompatibility\Result was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
467
                    $statement = $statement->getIterator();
468
                }
469
                $runtimeCache->set('getPageForRootlineStatement-' . $statementCacheIdent, $statement);
470
            } else {
471
                $statement->bindValue(1, (int)$uid);
472
                $statement->execute();
473
            }
474
            $row = $statement->fetch();
475
            if (method_exists($statement, 'free')) {
476
                $statement->free();
477
            } else {
478
                $statement->closeCursor();
479
            }
480
481
            if ($row) {
482
                if ($workspaceOL) {
483
                    self::workspaceOL('pages', $row);
484
                }
485
                if (is_array($row)) {
486
                    $pageForRootlineCache[$ident] = $row;
487
                    $runtimeCache->set('backendUtilityPageForRootLine', $pageForRootlineCache);
488
                }
489
            }
490
        }
491
        return $row;
492
    }
493
494
    /**
495
     * Opens the page tree to the specified page id
496
     *
497
     * @param int $pid Page id.
498
     * @param bool $clearExpansion If set, then other open branches are closed.
499
     * @internal should only be used from within TYPO3 Core
500
     */
501
    public static function openPageTree($pid, $clearExpansion)
502
    {
503
        $beUser = static::getBackendUserAuthentication();
504
        // Get current expansion data:
505
        if ($clearExpansion) {
506
            $expandedPages = [];
507
        } else {
508
            $expandedPages = json_decode($beUser->uc['browseTrees']['browsePages'], true);
509
        }
510
        // Get rootline:
511
        $rL = self::BEgetRootLine($pid);
512
        // First, find out what mount index to use (if more than one DB mount exists):
513
        $mountIndex = 0;
514
        $mountKeys = array_flip($beUser->returnWebmounts());
515
        foreach ($rL as $rLDat) {
516
            if (isset($mountKeys[$rLDat['uid']])) {
517
                $mountIndex = $mountKeys[$rLDat['uid']];
518
                break;
519
            }
520
        }
521
        // Traverse rootline and open paths:
522
        foreach ($rL as $rLDat) {
523
            $expandedPages[$mountIndex][$rLDat['uid']] = 1;
524
        }
525
        // Write back:
526
        $beUser->uc['browseTrees']['browsePages'] = json_encode($expandedPages);
527
        $beUser->writeUC();
528
    }
529
530
    /**
531
     * Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"
532
     * Each part of the path will be limited to $titleLimit characters
533
     * Deleted pages are filtered out.
534
     *
535
     * @param int $uid Page uid for which to create record path
536
     * @param string $clause Clause is additional where clauses, eg.
537
     * @param int $titleLimit Title limit
538
     * @param int $fullTitleLimit Title limit of Full title (typ. set to 1000 or so)
539
     * @return mixed Path of record (string) OR array with short/long title if $fullTitleLimit is set.
540
     */
541
    public static function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0)
542
    {
543
        if (!$titleLimit) {
544
            $titleLimit = 1000;
545
        }
546
        $output = $fullOutput = '/';
547
        $clause = trim($clause);
548
        if ($clause !== '' && strpos($clause, 'AND') !== 0) {
549
            $clause = 'AND ' . $clause;
550
        }
551
        $data = self::BEgetRootLine($uid, $clause, true);
552
        foreach ($data as $record) {
553
            if ($record['uid'] === 0) {
554
                continue;
555
            }
556
            $output = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $titleLimit) . $output;
557
            if ($fullTitleLimit) {
558
                $fullOutput = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $fullTitleLimit) . $fullOutput;
559
            }
560
        }
561
        if ($fullTitleLimit) {
562
            return [$output, $fullOutput];
563
        }
564
        return $output;
565
    }
566
567
    /**
568
     * Determines whether a table is localizable and has the languageField and transOrigPointerField set in $GLOBALS['TCA'].
569
     *
570
     * @param string $table The table to check
571
     * @return bool Whether a table is localizable
572
     */
573
    public static function isTableLocalizable($table)
574
    {
575
        $isLocalizable = false;
576
        if (isset($GLOBALS['TCA'][$table]['ctrl']) && is_array($GLOBALS['TCA'][$table]['ctrl'])) {
577
            $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
578
            $isLocalizable = isset($tcaCtrl['languageField']) && $tcaCtrl['languageField'] && isset($tcaCtrl['transOrigPointerField']) && $tcaCtrl['transOrigPointerField'];
579
        }
580
        return $isLocalizable;
581
    }
582
583
    /**
584
     * 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.
585
     * If $id is zero a pseudo root-page with "_thePath" set is returned IF the current BE_USER is admin.
586
     * In any case ->isInWebMount must return TRUE for the user (regardless of $perms_clause)
587
     *
588
     * @param int $id Page uid for which to check read-access
589
     * @param string $perms_clause This is typically a value generated with static::getBackendUserAuthentication()->getPagePermsClause(1);
590
     * @return array|false Returns page record if OK, otherwise FALSE.
591
     */
592
    public static function readPageAccess($id, $perms_clause)
593
    {
594
        if ((string)$id !== '') {
595
            $id = (int)$id;
596
            if (!$id) {
597
                if (static::getBackendUserAuthentication()->isAdmin()) {
598
                    return ['_thePath' => '/'];
599
                }
600
            } else {
601
                $pageinfo = self::getRecord('pages', $id, '*', $perms_clause);
602
                if ($pageinfo['uid'] && static::getBackendUserAuthentication()->isInWebMount($pageinfo, $perms_clause)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression static::getBackendUserAu...ageinfo, $perms_clause) of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
603
                    self::workspaceOL('pages', $pageinfo);
604
                    if (is_array($pageinfo)) {
605
                        [$pageinfo['_thePath'], $pageinfo['_thePathFull']] = self::getRecordPath((int)$pageinfo['uid'], $perms_clause, 15, 1000);
606
                        return $pageinfo;
607
                    }
608
                }
609
            }
610
        }
611
        return false;
612
    }
613
614
    /**
615
     * Returns the "type" value of $rec from $table which can be used to look up the correct "types" rendering section in $GLOBALS['TCA']
616
     * If no "type" field is configured in the "ctrl"-section of the $GLOBALS['TCA'] for the table, zero is used.
617
     * 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)
618
     *
619
     * Note: This method is very similar to the type determination of FormDataProvider/DatabaseRecordTypeValue,
620
     * however, it has two differences:
621
     * 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).
622
     * 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"
623
     * and "group" field values are stored, which makes different processing of the "foreign pointer field" type field variant necessary.
624
     *
625
     * @param string $table Table name present in TCA
626
     * @param array $row Record from $table
627
     * @throws \RuntimeException
628
     * @return string Field value
629
     */
630
    public static function getTCAtypeValue($table, $row)
631
    {
632
        $typeNum = 0;
633
        if ($GLOBALS['TCA'][$table] ?? false) {
634
            $field = $GLOBALS['TCA'][$table]['ctrl']['type'] ?? '';
635
            if (strpos($field, ':') !== false) {
636
                [$pointerField, $foreignTableTypeField] = explode(':', $field);
637
                // Get field value from database if field is not in the $row array
638
                if (!isset($row[$pointerField])) {
639
                    $localRow = self::getRecord($table, $row['uid'], $pointerField);
640
                    $foreignUid = $localRow[$pointerField];
641
                } else {
642
                    $foreignUid = $row[$pointerField];
643
                }
644
                if ($foreignUid) {
645
                    $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$pointerField]['config'];
646
                    $relationType = $fieldConfig['type'];
647
                    if ($relationType === 'select') {
648
                        $foreignTable = $fieldConfig['foreign_table'];
649
                    } elseif ($relationType === 'group') {
650
                        $allowedTables = explode(',', $fieldConfig['allowed']);
651
                        $foreignTable = $allowedTables[0];
652
                    } else {
653
                        throw new \RuntimeException(
654
                            'TCA foreign field pointer fields are only allowed to be used with group or select field types.',
655
                            1325862240
656
                        );
657
                    }
658
                    $foreignRow = self::getRecord($foreignTable, $foreignUid, $foreignTableTypeField);
659
                    if ($foreignRow[$foreignTableTypeField]) {
660
                        $typeNum = $foreignRow[$foreignTableTypeField];
661
                    }
662
                }
663
            } else {
664
                $typeNum = $row[$field] ?? 0;
665
            }
666
            // If that value is an empty string, set it to "0" (zero)
667
            if (empty($typeNum)) {
668
                $typeNum = 0;
669
            }
670
        }
671
        // If current typeNum doesn't exist, set it to 0 (or to 1 for historical reasons, if 0 doesn't exist)
672
        if (!isset($GLOBALS['TCA'][$table]['types'][$typeNum]) || !$GLOBALS['TCA'][$table]['types'][$typeNum]) {
673
            $typeNum = isset($GLOBALS['TCA'][$table]['types']['0']) ? 0 : 1;
674
        }
675
        // Force to string. Necessary for eg '-1' to be recognized as a type value.
676
        $typeNum = (string)$typeNum;
677
        return $typeNum;
678
    }
679
680
    /*******************************************
681
     *
682
     * TypoScript related
683
     *
684
     *******************************************/
685
    /**
686
     * Returns the Page TSconfig for page with id, $id
687
     *
688
     * @param int $id Page uid for which to create Page TSconfig
689
     * @return array Page TSconfig
690
     * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
691
     */
692
    public static function getPagesTSconfig($id)
693
    {
694
        $id = (int)$id;
695
696
        $cache = self::getRuntimeCache();
697
        $pagesTsConfigIdToHash = $cache->get('pagesTsConfigIdToHash' . $id);
698
        if ($pagesTsConfigIdToHash !== false) {
699
            return $cache->get('pagesTsConfigHashToContent' . $pagesTsConfigIdToHash);
700
        }
701
702
        $rootLine = self::BEgetRootLine($id, '', true);
703
        // Order correctly
704
        ksort($rootLine);
705
706
        try {
707
            $site = GeneralUtility::makeInstance(SiteFinder::class)->getSiteByPageId($id);
708
        } catch (SiteNotFoundException $exception) {
709
            $site = null;
710
        }
711
712
        // Load PageTS from all pages of the rootLine
713
        $pageTs = GeneralUtility::makeInstance(PageTsConfigLoader::class)->load($rootLine);
714
715
        // Parse the PageTS into an array, also applying conditions
716
        $parser = GeneralUtility::makeInstance(
717
            PageTsConfigParser::class,
718
            GeneralUtility::makeInstance(TypoScriptParser::class),
719
            GeneralUtility::makeInstance(CacheManager::class)->getCache('hash')
720
        );
721
        $matcher = GeneralUtility::makeInstance(ConditionMatcher::class, null, $id, $rootLine);
722
        $tsConfig = $parser->parse($pageTs, $matcher, $site);
723
        $cacheHash = md5((string)json_encode($tsConfig));
724
725
        // Get User TSconfig overlay, if no backend user is logged-in, this needs to be checked as well
726
        if (static::getBackendUserAuthentication()) {
727
            $userTSconfig = static::getBackendUserAuthentication()->getTSConfig() ?? [];
728
        } else {
729
            $userTSconfig = [];
730
        }
731
732
        if (is_array($userTSconfig['page.'] ?? null)) {
733
            // Override page TSconfig with user TSconfig
734
            ArrayUtility::mergeRecursiveWithOverrule($tsConfig, $userTSconfig['page.']);
735
            $cacheHash .= '_user' . static::getBackendUserAuthentication()->user['uid'];
736
        }
737
738
        // Many pages end up with the same ts config. To reduce memory usage, the cache
739
        // entries are a linked list: One or more pids point to content hashes which then
740
        // contain the cached content.
741
        $cache->set('pagesTsConfigHashToContent' . $cacheHash, $tsConfig, ['pagesTsConfig']);
742
        $cache->set('pagesTsConfigIdToHash' . $id, $cacheHash, ['pagesTsConfig']);
743
744
        return $tsConfig;
745
    }
746
747
    /*******************************************
748
     *
749
     * Users / Groups related
750
     *
751
     *******************************************/
752
    /**
753
     * Returns an array with be_users records of all user NOT DELETED sorted by their username
754
     * Keys in the array is the be_users uid
755
     *
756
     * @param string $fields Optional $fields list (default: username,usergroup,uid) can be used to set the selected fields
757
     * @param string $where Optional $where clause (fx. "AND username='pete'") can be used to limit query
758
     * @return array
759
     * @internal should only be used from within TYPO3 Core, use a direct SQL query instead to ensure proper DBAL where statements
760
     */
761
    public static function getUserNames($fields = 'username,usergroup,uid', $where = '')
762
    {
763
        return self::getRecordsSortedByTitle(
764
            GeneralUtility::trimExplode(',', $fields, true),
765
            'be_users',
766
            'username',
767
            'AND pid=0 ' . $where
768
        );
769
    }
770
771
    /**
772
     * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
773
     *
774
     * @param string $fields Field list
775
     * @param string $where WHERE clause
776
     * @return array
777
     * @internal should only be used from within TYPO3 Core, use a direct SQL query instead to ensure proper DBAL where statements
778
     */
779
    public static function getGroupNames($fields = 'title,uid', $where = '')
780
    {
781
        return self::getRecordsSortedByTitle(
782
            GeneralUtility::trimExplode(',', $fields, true),
783
            'be_groups',
784
            'title',
785
            'AND pid=0 ' . $where
786
        );
787
    }
788
789
    /**
790
     * Returns an array of all non-deleted records of a table sorted by a given title field.
791
     * The value of the title field will be replaced by the return value
792
     * of self::getRecordTitle() before the sorting is performed.
793
     *
794
     * @param array $fields Fields to select
795
     * @param string $table Table name
796
     * @param string $titleField Field that will contain the record title
797
     * @param string $where Additional where clause
798
     * @return array Array of sorted records
799
     */
800
    protected static function getRecordsSortedByTitle(array $fields, $table, $titleField, $where = '')
801
    {
802
        $fieldsIndex = array_flip($fields);
803
        // Make sure the titleField is amongst the fields when getting sorted
804
        $fieldsIndex[$titleField] = 1;
805
806
        $result = [];
807
808
        $queryBuilder = static::getQueryBuilderForTable($table);
809
        $queryBuilder->getRestrictions()
810
            ->removeAll()
811
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
812
813
        $res = $queryBuilder
814
            ->select('*')
815
            ->from($table)
816
            ->where(QueryHelper::stripLogicalOperatorPrefix($where))
817
            ->execute();
818
819
        while ($record = $res->fetch()) {
820
            // store the uid, because it might be unset if it's not among the requested $fields
821
            $recordId = $record['uid'];
822
            $record[$titleField] = self::getRecordTitle($table, $record);
823
824
            // include only the requested fields in the result
825
            $result[$recordId] = array_intersect_key($record, $fieldsIndex);
826
        }
827
828
        // sort records by $sortField. This is not done in the query because the title might have been overwritten by
829
        // self::getRecordTitle();
830
        return ArrayUtility::sortArraysByKey($result, $titleField);
831
    }
832
833
    /*******************************************
834
     *
835
     * Output related
836
     *
837
     *******************************************/
838
    /**
839
     * Returns the difference in days between input $tstamp and $EXEC_TIME
840
     *
841
     * @param int $tstamp Time stamp, seconds
842
     * @return int
843
     */
844
    public static function daysUntil($tstamp)
845
    {
846
        $delta_t = $tstamp - $GLOBALS['EXEC_TIME'];
847
        return ceil($delta_t / (3600 * 24));
848
    }
849
850
    /**
851
     * Returns $tstamp formatted as "ddmmyy" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'])
852
     *
853
     * @param int $tstamp Time stamp, seconds
854
     * @return string Formatted time
855
     */
856
    public static function date($tstamp)
857
    {
858
        return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int)$tstamp);
859
    }
860
861
    /**
862
     * Returns $tstamp formatted as "ddmmyy hhmm" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] AND $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'])
863
     *
864
     * @param int $value Time stamp, seconds
865
     * @return string Formatted time
866
     */
867
    public static function datetime($value)
868
    {
869
        return date(
870
            $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'],
871
            $value
872
        );
873
    }
874
875
    /**
876
     * Returns $value (in seconds) formatted as hh:mm:ss
877
     * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
878
     *
879
     * @param int $value Time stamp, seconds
880
     * @param bool $withSeconds Output hh:mm:ss. If FALSE: hh:mm
881
     * @return string Formatted time
882
     */
883
    public static function time($value, $withSeconds = true)
884
    {
885
        return gmdate('H:i' . ($withSeconds ? ':s' : ''), (int)$value);
886
    }
887
888
    /**
889
     * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
890
     *
891
     * @param int $seconds Seconds could be the difference of a certain timestamp and time()
892
     * @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")
893
     * @return string Formatted time
894
     */
895
    public static function calcAge($seconds, $labels = 'min|hrs|days|yrs|min|hour|day|year')
896
    {
897
        $labelArr = GeneralUtility::trimExplode('|', $labels, true);
898
        $absSeconds = abs($seconds);
899
        $sign = $seconds < 0 ? -1 : 1;
900
        if ($absSeconds < 3600) {
901
            $val = round($absSeconds / 60);
902
            $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[4] : $labelArr[0]);
903
        } elseif ($absSeconds < 24 * 3600) {
904
            $val = round($absSeconds / 3600);
905
            $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[5] : $labelArr[1]);
906
        } elseif ($absSeconds < 365 * 24 * 3600) {
907
            $val = round($absSeconds / (24 * 3600));
908
            $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[6] : $labelArr[2]);
909
        } else {
910
            $val = round($absSeconds / (365 * 24 * 3600));
911
            $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[7] : $labelArr[3]);
912
        }
913
        return $seconds;
914
    }
915
916
    /**
917
     * Returns a formatted timestamp if $tstamp is set.
918
     * The date/datetime will be followed by the age in parenthesis.
919
     *
920
     * @param int $tstamp Time stamp, seconds
921
     * @param int $prefix 1/-1 depending on polarity of age.
922
     * @param string $date $date=="date" will yield "dd:mm:yy" formatting, otherwise "dd:mm:yy hh:mm
923
     * @return string
924
     */
925
    public static function dateTimeAge($tstamp, $prefix = 1, $date = '')
926
    {
927
        if (!$tstamp) {
928
            return '';
929
        }
930
        $label = static::getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears');
931
        $age = ' (' . self::calcAge($prefix * ($GLOBALS['EXEC_TIME'] - $tstamp), $label) . ')';
932
        return ($date === 'date' ? self::date($tstamp) : self::datetime($tstamp)) . $age;
933
    }
934
935
    /**
936
     * Resolves file references for a given record.
937
     *
938
     * @param string $tableName Name of the table of the record
939
     * @param string $fieldName Name of the field of the record
940
     * @param array $element Record data
941
     * @param int|null $workspaceId Workspace to fetch data for
942
     * @return \TYPO3\CMS\Core\Resource\FileReference[]|null
943
     */
944
    public static function resolveFileReferences($tableName, $fieldName, $element, $workspaceId = null)
945
    {
946
        if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'])) {
947
            return null;
948
        }
949
        $configuration = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
950
        if (empty($configuration['type']) || $configuration['type'] !== 'inline'
951
            || empty($configuration['foreign_table']) || $configuration['foreign_table'] !== 'sys_file_reference'
952
        ) {
953
            return null;
954
        }
955
956
        $fileReferences = [];
957
        /** @var RelationHandler $relationHandler */
958
        $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
959
        if ($workspaceId !== null) {
960
            $relationHandler->setWorkspaceId($workspaceId);
961
        }
962
        $relationHandler->start(
963
            $element[$fieldName],
964
            $configuration['foreign_table'],
965
            $configuration['MM'] ?? '',
966
            $element['uid'],
967
            $tableName,
968
            $configuration
969
        );
970
        $relationHandler->processDeletePlaceholder();
971
        $referenceUids = $relationHandler->tableArray[$configuration['foreign_table']];
972
973
        foreach ($referenceUids as $referenceUid) {
974
            try {
975
                $fileReference = GeneralUtility::makeInstance(ResourceFactory::class)->getFileReferenceObject(
976
                    $referenceUid,
977
                    [],
978
                    $workspaceId === 0
979
                );
980
                $fileReferences[$fileReference->getUid()] = $fileReference;
981
            } catch (FileDoesNotExistException $e) {
982
                /**
983
                 * We just catch the exception here
984
                 * Reasoning: There is nothing an editor or even admin could do
985
                 */
986
            } catch (\InvalidArgumentException $e) {
987
                /**
988
                 * The storage does not exist anymore
989
                 * Log the exception message for admins as they maybe can restore the storage
990
                 */
991
                self::getLogger()->error($e->getMessage(), ['table' => $tableName, 'fieldName' => $fieldName, 'referenceUid' => $referenceUid, 'exception' => $e]);
992
            }
993
        }
994
995
        return $fileReferences;
996
    }
997
998
    /**
999
     * Returns a linked image-tag for thumbnail(s)/fileicons/truetype-font-previews from a database row with sys_file_references
1000
     * All $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] extension are made to thumbnails + ttf file (renders font-example)
1001
     * Thumbnails are linked to ShowItemController (/thumbnails route)
1002
     *
1003
     * @param array $row Row is the database row from the table, $table.
1004
     * @param string $table Table name for $row (present in TCA)
1005
     * @param string $field Field is pointing to the connecting field of sys_file_references
1006
     * @param string $backPath Back path prefix for image tag src="" field
1007
     * @param string $thumbScript UNUSED since FAL
1008
     * @param string $uploaddir UNUSED since FAL
1009
     * @param int $abs UNUSED
1010
     * @param string $tparams Optional: $tparams is additional attributes for the image tags
1011
     * @param int|string $size Optional: $size is [w]x[h] of the thumbnail. 64 is default.
1012
     * @param bool $linkInfoPopup Whether to wrap with a link opening the info popup
1013
     * @return string Thumbnail image tag.
1014
     */
1015
    public static function thumbCode(
1016
        $row,
1017
        $table,
1018
        $field,
1019
        $backPath = '',
1020
        $thumbScript = '',
1021
        $uploaddir = null,
1022
        $abs = 0,
1023
        $tparams = '',
1024
        $size = '',
1025
        $linkInfoPopup = true
1026
    ) {
1027
        $size = (int)(trim((string)$size) ?: 64);
1028
        $targetDimension = new ImageDimension($size, $size);
1029
        $thumbData = '';
1030
        $fileReferences = static::resolveFileReferences($table, $field, $row);
1031
        // FAL references
1032
        $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
1033
        if ($fileReferences !== null) {
1034
            foreach ($fileReferences as $fileReferenceObject) {
1035
                // Do not show previews of hidden references
1036
                if ($fileReferenceObject->getProperty('hidden')) {
1037
                    continue;
1038
                }
1039
                $fileObject = $fileReferenceObject->getOriginalFile();
1040
1041
                if ($fileObject->isMissing()) {
1042
                    $thumbData .= '<span class="label label-danger">'
1043
                        . htmlspecialchars(
1044
                            static::getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:warning.file_missing')
1045
                        )
1046
                        . '</span>&nbsp;' . htmlspecialchars($fileObject->getName()) . '<br />';
1047
                    continue;
1048
                }
1049
1050
                // Preview web image or media elements
1051
                if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails']
1052
                    && $fileReferenceObject->getOriginalFile()->isImage()
1053
                ) {
1054
                    $cropVariantCollection = CropVariantCollection::create((string)$fileReferenceObject->getProperty('crop'));
1055
                    $cropArea = $cropVariantCollection->getCropArea();
1056
                    $taskType = ProcessedFile::CONTEXT_IMAGEPREVIEW;
1057
                    $processingConfiguration = [
1058
                        'width' => $targetDimension->getWidth(),
1059
                        'height' => $targetDimension->getHeight(),
1060
                    ];
1061
                    if (!$cropArea->isEmpty()) {
1062
                        $taskType = ProcessedFile::CONTEXT_IMAGECROPSCALEMASK;
1063
                        $processingConfiguration = [
1064
                            'maxWidth' => $targetDimension->getWidth(),
1065
                            'maxHeight' => $targetDimension->getHeight(),
1066
                            'crop' => $cropArea->makeAbsoluteBasedOnFile($fileReferenceObject),
1067
                        ];
1068
                    }
1069
                    $processedImage = $fileObject->process($taskType, $processingConfiguration);
1070
                    $attributes = [
1071
                        'src' => PathUtility::getAbsoluteWebPath($processedImage->getPublicUrl() ?? ''),
1072
                        'width' => $processedImage->getProperty('width'),
1073
                        'height' => $processedImage->getProperty('height'),
1074
                        'alt' => $fileReferenceObject->getName(),
1075
                    ];
1076
                    $imgTag = '<img ' . GeneralUtility::implodeAttributes($attributes, true) . $tparams . '/>';
1077
                } else {
1078
                    // Icon
1079
                    $imgTag = '<span title="' . htmlspecialchars($fileObject->getName()) . '">'
1080
                        . $iconFactory->getIconForResource($fileObject, Icon::SIZE_SMALL)->render()
1081
                        . '</span>';
1082
                }
1083
                if ($linkInfoPopup) {
1084
                    // relies on module 'TYPO3/CMS/Backend/ActionDispatcher'
1085
                    $attributes = GeneralUtility::implodeAttributes([
1086
                        'data-dispatch-action' => 'TYPO3.InfoWindow.showItem',
1087
                        'data-dispatch-args-list' => '_FILE,' . (int)$fileObject->getUid(),
1088
                    ], true);
1089
                    $thumbData .= '<a href="#" ' . $attributes . '>' . $imgTag . '</a> ';
1090
                } else {
1091
                    $thumbData .= $imgTag;
1092
                }
1093
            }
1094
        }
1095
        return $thumbData;
1096
    }
1097
1098
    /**
1099
     * @param int $fileId
1100
     * @param array $configuration
1101
     * @return string
1102
     */
1103
    public static function getThumbnailUrl(int $fileId, array $configuration): string
1104
    {
1105
        $taskType = $configuration['_context'] ?? ProcessedFile::CONTEXT_IMAGEPREVIEW;
1106
        unset($configuration['_context']);
1107
1108
        return GeneralUtility::makeInstance(ResourceFactory::class)
1109
                ->getFileObject($fileId)
1110
                ->process($taskType, $configuration)
1111
                ->getPublicUrl(true);
1112
    }
1113
1114
    /**
1115
     * Returns title-attribute information for a page-record informing about id, doktype, hidden, starttime, endtime, fe_group etc.
1116
     *
1117
     * @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)
1118
     * @param string $perms_clause This is used to get the record path of the shortcut page, if any (and doktype==4)
1119
     * @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
1120
     * @return string
1121
     */
1122
    public static function titleAttribForPages($row, $perms_clause = '', $includeAttrib = true)
1123
    {
1124
        $lang = static::getLanguageService();
1125
        $parts = [];
1126
        $parts[] = 'id=' . $row['uid'];
1127
        if ($row['uid'] === 0) {
1128
            $out = htmlspecialchars($parts[0]);
1129
            return $includeAttrib ? 'title="' . $out . '"' : $out;
1130
        }
1131
        switch (VersionState::cast($row['t3ver_state'])) {
1132
            case new VersionState(VersionState::DELETE_PLACEHOLDER):
1133
                $parts[] = 'Deleted element!';
1134
                break;
1135
            case new VersionState(VersionState::MOVE_POINTER):
1136
                $parts[] = 'NEW LOCATION (Move-to Pointer) WSID#' . $row['t3ver_wsid'];
1137
                break;
1138
            case new VersionState(VersionState::NEW_PLACEHOLDER):
1139
                $parts[] = 'New element!';
1140
                break;
1141
        }
1142
        if ($row['doktype'] == PageRepository::DOKTYPE_LINK) {
1143
            $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['url']['label']) . ' ' . $row['url'];
1144
        } elseif ($row['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1145
            if ($perms_clause) {
1146
                $label = self::getRecordPath((int)$row['shortcut'], $perms_clause, 20);
1147
            } else {
1148
                $row['shortcut'] = (int)$row['shortcut'];
1149
                $lRec = self::getRecordWSOL('pages', $row['shortcut'], 'title');
1150
                $label = $lRec['title'] . ' (id=' . $row['shortcut'] . ')';
1151
            }
1152
            if ($row['shortcut_mode'] != PageRepository::SHORTCUT_MODE_NONE) {
1153
                $label .= ', ' . $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut_mode']['label']) . ' '
1154
                    . $lang->sL(self::getLabelFromItemlist('pages', 'shortcut_mode', $row['shortcut_mode']));
1155
            }
1156
            $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut']['label']) . ' ' . $label;
0 ignored issues
show
Bug introduced by
Are you sure $label of type array<integer,string>|string can be used in concatenation? ( Ignorable by Annotation )

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

1156
            $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut']['label']) . ' ' . /** @scrutinizer ignore-type */ $label;
Loading history...
1157
        } elseif ($row['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT) {
1158
            if ((int)$row['mount_pid'] > 0) {
1159
                if ($perms_clause) {
1160
                    $label = self::getRecordPath((int)$row['mount_pid'], $perms_clause, 20);
1161
                } else {
1162
                    $lRec = self::getRecordWSOL('pages', (int)$row['mount_pid'], 'title');
1163
                    $label = $lRec['title'] . ' (id=' . $row['mount_pid'] . ')';
1164
                }
1165
                $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid']['label']) . ' ' . $label;
1166
                if ($row['mount_pid_ol']) {
1167
                    $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid_ol']['label']);
1168
                }
1169
            } else {
1170
                $parts[] = $lang->sL('LLL:EXT:frontend/Resources/Private/Language/locallang_tca.xlf:no_mount_pid');
1171
            }
1172
        }
1173
        if ($row['nav_hide']) {
1174
            $parts[] = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_tca.xlf:pages.nav_hide');
1175
        }
1176
        if ($row['hidden']) {
1177
            $parts[] = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.hidden');
1178
        }
1179
        if ($row['starttime']) {
1180
            $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['starttime']['label'])
1181
                . ' ' . self::dateTimeAge($row['starttime'], -1, 'date');
1182
        }
1183
        if ($row['endtime']) {
1184
            $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['endtime']['label']) . ' '
1185
                . self::dateTimeAge($row['endtime'], -1, 'date');
1186
        }
1187
        if ($row['fe_group']) {
1188
            $fe_groups = [];
1189
            foreach (GeneralUtility::intExplode(',', $row['fe_group']) as $fe_group) {
1190
                if ($fe_group < 0) {
1191
                    $fe_groups[] = $lang->sL(self::getLabelFromItemlist('pages', 'fe_group', (string)$fe_group));
1192
                } else {
1193
                    $lRec = self::getRecordWSOL('fe_groups', $fe_group, 'title');
1194
                    $fe_groups[] = $lRec['title'];
1195
                }
1196
            }
1197
            $label = implode(', ', $fe_groups);
1198
            $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['fe_group']['label']) . ' ' . $label;
1199
        }
1200
        $out = htmlspecialchars(implode(' - ', $parts));
1201
        return $includeAttrib ? 'title="' . $out . '"' : $out;
1202
    }
1203
1204
    /**
1205
     * Returns the combined markup for Bootstraps tooltips
1206
     *
1207
     * @param array $row
1208
     * @param string $table
1209
     * @return string
1210
     */
1211
    public static function getRecordToolTip(array $row, $table = 'pages')
1212
    {
1213
        $toolTipText = self::getRecordIconAltText($row, $table);
1214
        $toolTipCode = 'data-bs-toggle="tooltip" title=" '
1215
            . str_replace(' - ', '<br>', $toolTipText)
1216
            . '" data-bs-html="true" data-bs-placement="right"';
1217
        return $toolTipCode;
1218
    }
1219
1220
    /**
1221
     * Returns title-attribute information for ANY record (from a table defined in TCA of course)
1222
     * The included information depends on features of the table, but if hidden, starttime, endtime and fe_group fields are configured for, information about the record status in regard to these features are is included.
1223
     * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
1224
     *
1225
     * @param array $row Table row; $row is a row from the table, $table
1226
     * @param string $table Table name
1227
     * @return string
1228
     */
1229
    public static function getRecordIconAltText($row, $table = 'pages')
1230
    {
1231
        if ($table === 'pages') {
1232
            $out = self::titleAttribForPages($row, '', false);
1233
        } else {
1234
            $out = !empty(trim($GLOBALS['TCA'][$table]['ctrl']['descriptionColumn'])) ? $row[$GLOBALS['TCA'][$table]['ctrl']['descriptionColumn']] . ' ' : '';
1235
            $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
1236
            // Uid is added
1237
            $out .= 'id=' . $row['uid'];
1238
            if (static::isTableWorkspaceEnabled($table)) {
1239
                switch (VersionState::cast($row['t3ver_state'])) {
1240
                    case new VersionState(VersionState::DELETE_PLACEHOLDER):
1241
                        $out .= ' - Deleted element!';
1242
                        break;
1243
                    case new VersionState(VersionState::MOVE_POINTER):
1244
                        $out .= ' - NEW LOCATION (Move-to Pointer) WSID#' . $row['t3ver_wsid'];
1245
                        break;
1246
                    case new VersionState(VersionState::NEW_PLACEHOLDER):
1247
                        $out .= ' - New element!';
1248
                        break;
1249
                }
1250
            }
1251
            // Hidden
1252
            $lang = static::getLanguageService();
1253
            if ($ctrl['disabled']) {
1254
                $out .= $row[$ctrl['disabled']] ? ' - ' . $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.hidden') : '';
1255
            }
1256
            if ($ctrl['starttime']) {
1257
                if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
1258
                    $out .= ' - ' . $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.starttime') . ':' . self::date($row[$ctrl['starttime']]) . ' (' . self::daysUntil($row[$ctrl['starttime']]) . ' ' . $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.days') . ')';
1259
                }
1260
            }
1261
            if ($row[$ctrl['endtime']]) {
1262
                $out .= ' - ' . $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.endtime') . ': ' . self::date($row[$ctrl['endtime']]) . ' (' . self::daysUntil($row[$ctrl['endtime']]) . ' ' . $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.days') . ')';
1263
            }
1264
        }
1265
        return htmlspecialchars($out);
1266
    }
1267
1268
    /**
1269
     * Returns the label of the first found entry in an "items" array from $GLOBALS['TCA'] (tablename = $table/fieldname = $col) where the value is $key
1270
     *
1271
     * @param string $table Table name, present in $GLOBALS['TCA']
1272
     * @param string $col Field name, present in $GLOBALS['TCA']
1273
     * @param string $key items-array value to match
1274
     * @return string Label for item entry
1275
     */
1276
    public static function getLabelFromItemlist($table, $col, $key)
1277
    {
1278
        // Check, if there is an "items" array:
1279
        if (is_array($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'] ?? false)) {
1280
            // Traverse the items-array...
1281
            foreach ($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'] as $v) {
1282
                // ... and return the first found label where the value was equal to $key
1283
                if ((string)$v[1] === (string)$key) {
1284
                    return $v[0];
1285
                }
1286
            }
1287
        }
1288
        return '';
1289
    }
1290
1291
    /**
1292
     * Return the label of a field by additionally checking TsConfig values
1293
     *
1294
     * @param int $pageId Page id
1295
     * @param string $table Table name
1296
     * @param string $column Field Name
1297
     * @param string $key item value
1298
     * @return string Label for item entry
1299
     */
1300
    public static function getLabelFromItemListMerged($pageId, $table, $column, $key)
1301
    {
1302
        $pageTsConfig = static::getPagesTSconfig($pageId);
1303
        $label = '';
1304
        if (isset($pageTsConfig['TCEFORM.'])
1305
            && \is_array($pageTsConfig['TCEFORM.'])
1306
            && \is_array($pageTsConfig['TCEFORM.'][$table . '.'])
1307
            && \is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.'])
1308
        ) {
1309
            if (\is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'])
1310
                && isset($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'][$key])
1311
            ) {
1312
                $label = $pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'][$key];
1313
            } elseif (\is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'])
1314
                && isset($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'][$key])
1315
            ) {
1316
                $label = $pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'][$key];
1317
            }
1318
        }
1319
        if (empty($label)) {
1320
            $tcaValue = self::getLabelFromItemlist($table, $column, $key);
1321
            if (!empty($tcaValue)) {
1322
                $label = $tcaValue;
1323
            }
1324
        }
1325
        return $label;
1326
    }
1327
1328
    /**
1329
     * Splits the given key with commas and returns the list of all the localized items labels, separated by a comma.
1330
     * NOTE: this does not take itemsProcFunc into account
1331
     *
1332
     * @param string $table Table name, present in TCA
1333
     * @param string $column Field name
1334
     * @param string $keyList Key or comma-separated list of keys.
1335
     * @param array $columnTsConfig page TSConfig for $column (TCEMAIN.<table>.<column>)
1336
     * @return string Comma-separated list of localized labels
1337
     */
1338
    public static function getLabelsFromItemsList($table, $column, $keyList, array $columnTsConfig = [])
1339
    {
1340
        // Check if there is an "items" array
1341
        if (
1342
            !isset($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])
1343
            || !is_array($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])
1344
            || $keyList === ''
1345
        ) {
1346
            return '';
1347
        }
1348
1349
        $keys = GeneralUtility::trimExplode(',', $keyList, true);
1350
        $labels = [];
1351
        // Loop on all selected values
1352
        foreach ($keys as $key) {
1353
            $label = null;
1354
            if ($columnTsConfig) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $columnTsConfig of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1355
                // Check if label has been defined or redefined via pageTsConfig
1356
                if (isset($columnTsConfig['addItems.'][$key])) {
1357
                    $label = $columnTsConfig['addItems.'][$key];
1358
                } elseif (isset($columnTsConfig['altLabels.'][$key])) {
1359
                    $label = $columnTsConfig['altLabels.'][$key];
1360
                }
1361
            }
1362
            if ($label === null) {
1363
                // Otherwise lookup the label in TCA items list
1364
                foreach ($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'] as $itemConfiguration) {
1365
                    [$currentLabel, $currentKey] = $itemConfiguration;
1366
                    if ((string)$key === (string)$currentKey) {
1367
                        $label = $currentLabel;
1368
                        break;
1369
                    }
1370
                }
1371
            }
1372
            if ($label !== null) {
1373
                $labels[] = static::getLanguageService()->sL($label);
1374
            }
1375
        }
1376
        return implode(', ', $labels);
1377
    }
1378
1379
    /**
1380
     * Returns the label-value for fieldname $col in table, $table
1381
     * If $printAllWrap is set (to a "wrap") then it's wrapped around the $col value IF THE COLUMN $col DID NOT EXIST in TCA!, eg. $printAllWrap = '<strong>|</strong>' and the fieldname was 'not_found_field' then the return value would be '<strong>not_found_field</strong>'
1382
     *
1383
     * @param string $table Table name, present in $GLOBALS['TCA']
1384
     * @param string $col Field name
1385
     * @return string or NULL if $col is not found in the TCA table
1386
     */
1387
    public static function getItemLabel($table, $col)
1388
    {
1389
        // Check if column exists
1390
        if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
1391
            return $GLOBALS['TCA'][$table]['columns'][$col]['label'];
1392
        }
1393
1394
        return null;
1395
    }
1396
1397
    /**
1398
     * Returns the "title"-value in record, $row, from table, $table
1399
     * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
1400
     *
1401
     * @param string $table Table name, present in TCA
1402
     * @param array $row Row from table
1403
     * @param bool $prep If set, result is prepared for output: The output is cropped to a limited length (depending on BE_USER->uc['titleLen']) and if no value is found for the title, '<em>[No title]</em>' is returned (localized). Further, the output is htmlspecialchars()'ed
1404
     * @param bool $forceResult If set, the function always returns an output. If no value is found for the title, '[No title]' is returned (localized).
1405
     * @return string
1406
     */
1407
    public static function getRecordTitle($table, $row, $prep = false, $forceResult = true)
1408
    {
1409
        $params = [];
1410
        $recordTitle = '';
1411
        if (isset($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table])) {
1412
            // If configured, call userFunc
1413
            if (!empty($GLOBALS['TCA'][$table]['ctrl']['label_userFunc'])) {
1414
                $params['table'] = $table;
1415
                $params['row'] = $row;
1416
                $params['title'] = '';
1417
                $params['options'] = $GLOBALS['TCA'][$table]['ctrl']['label_userFunc_options'] ?? [];
1418
1419
                // Create NULL-reference
1420
                $null = null;
1421
                GeneralUtility::callUserFunction($GLOBALS['TCA'][$table]['ctrl']['label_userFunc'], $params, $null);
1422
                $recordTitle = $params['title'];
1423
            } else {
1424
                // No userFunc: Build label
1425
                $ctrlLabel = $GLOBALS['TCA'][$table]['ctrl']['label'] ?? '';
1426
                $recordTitle = self::getProcessedValue(
1427
                    $table,
1428
                    $ctrlLabel,
1429
                    $row[$ctrlLabel] ?? '',
1430
                    0,
1431
                    false,
1432
                    false,
1433
                    $row['uid'] ?? null,
1434
                    $forceResult
1435
                ) ?? '';
1436
                if (!empty($GLOBALS['TCA'][$table]['ctrl']['label_alt'])
1437
                    && (!empty($GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) || (string)$recordTitle === '')
1438
                ) {
1439
                    $altFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], true);
1440
                    $tA = [];
1441
                    if (!empty($recordTitle)) {
1442
                        $tA[] = $recordTitle;
1443
                    }
1444
                    foreach ($altFields as $fN) {
1445
                        $recordTitle = trim(strip_tags($row[$fN] ?? ''));
1446
                        if ((string)$recordTitle !== '') {
1447
                            $recordTitle = self::getProcessedValue($table, $fN, $recordTitle, 0, false, false, $row['uid']);
1448
                            if (!($GLOBALS['TCA'][$table]['ctrl']['label_alt_force'] ?? false)) {
1449
                                break;
1450
                            }
1451
                            $tA[] = $recordTitle;
1452
                        }
1453
                    }
1454
                    if ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force'] ?? false) {
1455
                        $recordTitle = implode(', ', $tA);
1456
                    }
1457
                }
1458
            }
1459
            // If the current result is empty, set it to '[No title]' (localized) and prepare for output if requested
1460
            if ($prep || $forceResult) {
1461
                if ($prep) {
1462
                    $recordTitle = self::getRecordTitlePrep($recordTitle);
1463
                }
1464
                if (trim($recordTitle) === '') {
0 ignored issues
show
Bug introduced by
It seems like $recordTitle can also be of type null; however, parameter $string of trim() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

1464
                if (trim(/** @scrutinizer ignore-type */ $recordTitle) === '') {
Loading history...
1465
                    $recordTitle = self::getNoRecordTitle($prep);
1466
                }
1467
            }
1468
        }
1469
1470
        return $recordTitle;
1471
    }
1472
1473
    /**
1474
     * Crops a title string to a limited length and if it really was cropped, wrap it in a <span title="...">|</span>,
1475
     * which offers a tooltip with the original title when moving mouse over it.
1476
     *
1477
     * @param string $title The title string to be cropped
1478
     * @param int $titleLength Crop title after this length - if not set, BE_USER->uc['titleLen'] is used
1479
     * @return string The processed title string, wrapped in <span title="...">|</span> if cropped
1480
     */
1481
    public static function getRecordTitlePrep($title, $titleLength = 0)
1482
    {
1483
        // If $titleLength is not a valid positive integer, use BE_USER->uc['titleLen']:
1484
        if (!$titleLength || !MathUtility::canBeInterpretedAsInteger($titleLength) || $titleLength < 0) {
1485
            $titleLength = static::getBackendUserAuthentication()->uc['titleLen'];
1486
        }
1487
        $titleOrig = htmlspecialchars($title);
1488
        $title = htmlspecialchars(GeneralUtility::fixed_lgd_cs($title, $titleLength));
1489
        // If title was cropped, offer a tooltip:
1490
        if ($titleOrig != $title) {
1491
            $title = '<span title="' . $titleOrig . '">' . $title . '</span>';
1492
        }
1493
        return $title;
1494
    }
1495
1496
    /**
1497
     * Get a localized [No title] string, wrapped in <em>|</em> if $prep is TRUE.
1498
     *
1499
     * @param bool $prep Wrap result in <em>|</em>
1500
     * @return string Localized [No title] string
1501
     */
1502
    public static function getNoRecordTitle($prep = false)
1503
    {
1504
        $noTitle = '[' .
1505
            htmlspecialchars(static::getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.no_title'))
1506
            . ']';
1507
        if ($prep) {
1508
            $noTitle = '<em>' . $noTitle . '</em>';
1509
        }
1510
        return $noTitle;
1511
    }
1512
1513
    /**
1514
     * Returns a human readable output of a value from a record
1515
     * For instance a database record relation would be looked up to display the title-value of that record. A checkbox with a "1" value would be "Yes", etc.
1516
     * $table/$col is tablename and fieldname
1517
     * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
1518
     *
1519
     * @param string $table Table name, present in TCA
1520
     * @param string $col Field name, present in TCA
1521
     * @param string $value The value of that field from a selected record
1522
     * @param int $fixed_lgd_chars The max amount of characters the value may occupy
1523
     * @param bool $defaultPassthrough Flag means that values for columns that has no conversion will just be pass through directly (otherwise cropped to 200 chars or returned as "N/A")
1524
     * @param bool $noRecordLookup If set, no records will be looked up, UIDs are just shown.
1525
     * @param int $uid Uid of the current record
1526
     * @param bool $forceResult If BackendUtility::getRecordTitle is used to process the value, this parameter is forwarded.
1527
     * @param int $pid Optional page uid is used to evaluate page TSConfig for the given field
1528
     * @throws \InvalidArgumentException
1529
     * @return string|null
1530
     */
1531
    public static function getProcessedValue(
1532
        $table,
1533
        $col,
1534
        $value,
1535
        $fixed_lgd_chars = 0,
1536
        $defaultPassthrough = false,
1537
        $noRecordLookup = false,
1538
        $uid = 0,
1539
        $forceResult = true,
1540
        $pid = 0
1541
    ) {
1542
        if ($col === 'uid') {
1543
            // uid is not in TCA-array
1544
            return $value;
1545
        }
1546
        // Check if table and field is configured
1547
        if (!isset($GLOBALS['TCA'][$table]['columns'][$col]) || !is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
1548
            return null;
1549
        }
1550
        // Depending on the fields configuration, make a meaningful output value.
1551
        $theColConf = $GLOBALS['TCA'][$table]['columns'][$col]['config'] ?? [];
1552
        /*****************
1553
         *HOOK: pre-processing the human readable output from a record
1554
         ****************/
1555
        $referenceObject = new \stdClass();
1556
        $referenceObject->table = $table;
1557
        $referenceObject->fieldName = $col;
1558
        $referenceObject->uid = $uid;
1559
        $referenceObject->value = &$value;
1560
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] ?? [] as $_funcRef) {
1561
            GeneralUtility::callUserFunction($_funcRef, $theColConf, $referenceObject);
1562
        }
1563
1564
        $l = '';
1565
        $lang = static::getLanguageService();
1566
        switch ((string)($theColConf['type'] ?? '')) {
1567
            case 'radio':
1568
                $l = self::getLabelFromItemlist($table, $col, $value);
1569
                $l = $lang->sL($l);
1570
                break;
1571
            case 'inline':
1572
            case 'select':
1573
                if (!empty($theColConf['MM'])) {
1574
                    if ($uid) {
1575
                        // Display the title of MM related records in lists
1576
                        if ($noRecordLookup) {
1577
                            $MMfields = [];
1578
                            $MMfields[] = $theColConf['foreign_table'] . '.uid';
1579
                        } else {
1580
                            $MMfields = [$theColConf['foreign_table'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']];
1581
                            if (isset($GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt'])) {
1582
                                foreach (GeneralUtility::trimExplode(
1583
                                    ',',
1584
                                    $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt'],
1585
                                    true
1586
                                ) as $f) {
1587
                                    $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
1588
                                }
1589
                            }
1590
                        }
1591
                        /** @var RelationHandler $dbGroup */
1592
                        $dbGroup = GeneralUtility::makeInstance(RelationHandler::class);
1593
                        $dbGroup->start(
1594
                            $value,
1595
                            $theColConf['foreign_table'],
1596
                            $theColConf['MM'],
1597
                            $uid,
1598
                            $table,
1599
                            $theColConf
1600
                        );
1601
                        $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
1602
                        if (is_array($selectUids) && !empty($selectUids)) {
1603
                            $queryBuilder = static::getQueryBuilderForTable($theColConf['foreign_table']);
1604
                            $queryBuilder->getRestrictions()
1605
                                ->removeAll()
1606
                                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1607
1608
                            $result = $queryBuilder
1609
                                ->select('uid', ...$MMfields)
1610
                                ->from($theColConf['foreign_table'])
1611
                                ->where(
1612
                                    $queryBuilder->expr()->in(
1613
                                        'uid',
1614
                                        $queryBuilder->createNamedParameter($selectUids, Connection::PARAM_INT_ARRAY)
1615
                                    )
1616
                                )
1617
                                ->execute();
1618
1619
                            $mmlA = [];
1620
                            while ($MMrow = $result->fetch()) {
1621
                                // Keep sorting of $selectUids
1622
                                $selectedUid = array_search($MMrow['uid'], $selectUids);
1623
                                $mmlA[$selectedUid] = $MMrow['uid'];
1624
                                if (!$noRecordLookup) {
1625
                                    $mmlA[$selectedUid] = static::getRecordTitle(
1626
                                        $theColConf['foreign_table'],
1627
                                        $MMrow,
1628
                                        false,
1629
                                        $forceResult
1630
                                    );
1631
                                }
1632
                            }
1633
1634
                            if (!empty($mmlA)) {
1635
                                ksort($mmlA);
1636
                                $l = implode('; ', $mmlA);
1637
                            } else {
1638
                                $l = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:notAvailableAbbreviation');
1639
                            }
1640
                        } else {
1641
                            $l = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:notAvailableAbbreviation');
1642
                        }
1643
                    } else {
1644
                        $l = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:notAvailableAbbreviation');
1645
                    }
1646
                } else {
1647
                    $columnTsConfig = [];
1648
                    if ($pid) {
1649
                        $pageTsConfig = self::getPagesTSconfig($pid);
1650
                        if (isset($pageTsConfig['TCEFORM.'][$table . '.'][$col . '.']) && is_array($pageTsConfig['TCEFORM.'][$table . '.'][$col . '.'])) {
1651
                            $columnTsConfig = $pageTsConfig['TCEFORM.'][$table . '.'][$col . '.'];
1652
                        }
1653
                    }
1654
                    $l = self::getLabelsFromItemsList($table, $col, $value, $columnTsConfig);
1655
                    if (!empty($theColConf['foreign_table']) && !$l && !empty($GLOBALS['TCA'][$theColConf['foreign_table']])) {
1656
                        if ($noRecordLookup) {
1657
                            $l = $value;
1658
                        } else {
1659
                            $rParts = [];
1660
                            if ($uid && isset($theColConf['foreign_field']) && $theColConf['foreign_field'] !== '') {
1661
                                $queryBuilder = static::getQueryBuilderForTable($theColConf['foreign_table']);
1662
                                $queryBuilder->getRestrictions()
1663
                                    ->removeAll()
1664
                                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
1665
                                    ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, static::getBackendUserAuthentication()->workspace));
1666
                                $constraints = [
1667
                                    $queryBuilder->expr()->eq(
1668
                                        $theColConf['foreign_field'],
1669
                                        $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1670
                                    )
1671
                                ];
1672
1673
                                if (!empty($theColConf['foreign_table_field'])) {
1674
                                    $constraints[] = $queryBuilder->expr()->eq(
1675
                                        $theColConf['foreign_table_field'],
1676
                                        $queryBuilder->createNamedParameter($table, \PDO::PARAM_STR)
1677
                                    );
1678
                                }
1679
1680
                                // Add additional where clause if foreign_match_fields are defined
1681
                                $foreignMatchFields = [];
1682
                                if (is_array($theColConf['foreign_match_fields'])) {
1683
                                    $foreignMatchFields = $theColConf['foreign_match_fields'];
1684
                                }
1685
1686
                                foreach ($foreignMatchFields as $matchField => $matchValue) {
1687
                                    $constraints[] = $queryBuilder->expr()->eq(
1688
                                        $matchField,
1689
                                        $queryBuilder->createNamedParameter($matchValue)
1690
                                    );
1691
                                }
1692
1693
                                $result = $queryBuilder
1694
                                    ->select('*')
1695
                                    ->from($theColConf['foreign_table'])
1696
                                    ->where(...$constraints)
1697
                                    ->execute();
1698
1699
                                while ($record = $result->fetch()) {
1700
                                    $rParts[] = $record['uid'];
1701
                                }
1702
                            }
1703
                            if (empty($rParts)) {
1704
                                $rParts = GeneralUtility::trimExplode(',', $value, true);
1705
                            }
1706
                            $lA = [];
1707
                            foreach ($rParts as $rVal) {
1708
                                $rVal = (int)$rVal;
1709
                                $r = self::getRecordWSOL($theColConf['foreign_table'], $rVal);
1710
                                if (is_array($r)) {
1711
                                    $lA[] = $lang->sL($theColConf['foreign_table_prefix'])
1712
                                        . self::getRecordTitle($theColConf['foreign_table'], $r, false, $forceResult);
1713
                                } else {
1714
                                    $lA[] = $rVal ? '[' . $rVal . '!]' : '';
1715
                                }
1716
                            }
1717
                            $l = implode(', ', $lA);
1718
                        }
1719
                    }
1720
                    if (empty($l) && !empty($value)) {
1721
                        // Use plain database value when label is empty
1722
                        $l = $value;
1723
                    }
1724
                }
1725
                break;
1726
            case 'group':
1727
                // resolve the titles for DB records
1728
                if (isset($theColConf['internal_type']) && $theColConf['internal_type'] === 'db') {
1729
                    if (isset($theColConf['MM']) && $theColConf['MM']) {
1730
                        if ($uid) {
1731
                            // Display the title of MM related records in lists
1732
                            if ($noRecordLookup) {
1733
                                $MMfields = [];
1734
                                $MMfields[] = $theColConf['foreign_table'] . '.uid';
1735
                            } else {
1736
                                $MMfields = [$theColConf['foreign_table'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']];
1737
                                $altLabelFields = explode(
1738
                                    ',',
1739
                                    $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt']
1740
                                );
1741
                                foreach ($altLabelFields as $f) {
1742
                                    $f = trim($f);
1743
                                    if ($f !== '') {
1744
                                        $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
1745
                                    }
1746
                                }
1747
                            }
1748
                            /** @var RelationHandler $dbGroup */
1749
                            $dbGroup = GeneralUtility::makeInstance(RelationHandler::class);
1750
                            $dbGroup->start(
1751
                                $value,
1752
                                $theColConf['foreign_table'],
1753
                                $theColConf['MM'],
1754
                                $uid,
1755
                                $table,
1756
                                $theColConf
1757
                            );
1758
                            $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
1759
                            if (!empty($selectUids) && is_array($selectUids)) {
1760
                                $queryBuilder = static::getQueryBuilderForTable($theColConf['foreign_table']);
1761
                                $queryBuilder->getRestrictions()
1762
                                    ->removeAll()
1763
                                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1764
1765
                                $result = $queryBuilder
1766
                                    ->select('uid', ...$MMfields)
1767
                                    ->from($theColConf['foreign_table'])
1768
                                    ->where(
1769
                                        $queryBuilder->expr()->in(
1770
                                            'uid',
1771
                                            $queryBuilder->createNamedParameter(
1772
                                                $selectUids,
1773
                                                Connection::PARAM_INT_ARRAY
1774
                                            )
1775
                                        )
1776
                                    )
1777
                                    ->execute();
1778
1779
                                $mmlA = [];
1780
                                while ($MMrow = $result->fetch()) {
1781
                                    // Keep sorting of $selectUids
1782
                                    $selectedUid = array_search($MMrow['uid'], $selectUids);
1783
                                    $mmlA[$selectedUid] = $MMrow['uid'];
1784
                                    if (!$noRecordLookup) {
1785
                                        $mmlA[$selectedUid] = static::getRecordTitle(
1786
                                            $theColConf['foreign_table'],
1787
                                            $MMrow,
1788
                                            false,
1789
                                            $forceResult
1790
                                        );
1791
                                    }
1792
                                }
1793
1794
                                if (!empty($mmlA)) {
1795
                                    ksort($mmlA);
1796
                                    $l = implode('; ', $mmlA);
1797
                                } else {
1798
                                    $l = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:notAvailableAbbreviation');
1799
                                }
1800
                            } else {
1801
                                $l = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:notAvailableAbbreviation');
1802
                            }
1803
                        } else {
1804
                            $l = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:notAvailableAbbreviation');
1805
                        }
1806
                    } else {
1807
                        $finalValues = [];
1808
                        $relationTableName = $theColConf['allowed'];
1809
                        $explodedValues = GeneralUtility::trimExplode(',', $value, true);
1810
1811
                        foreach ($explodedValues as $explodedValue) {
1812
                            if (MathUtility::canBeInterpretedAsInteger($explodedValue)) {
1813
                                $relationTableNameForField = $relationTableName;
1814
                            } else {
1815
                                [$relationTableNameForField, $explodedValue] = self::splitTable_Uid($explodedValue);
1816
                            }
1817
1818
                            $relationRecord = static::getRecordWSOL($relationTableNameForField, $explodedValue);
0 ignored issues
show
Bug introduced by
$explodedValue of type string is incompatible with the type integer expected by parameter $uid of TYPO3\CMS\Backend\Utilit...tility::getRecordWSOL(). ( Ignorable by Annotation )

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

1818
                            $relationRecord = static::getRecordWSOL($relationTableNameForField, /** @scrutinizer ignore-type */ $explodedValue);
Loading history...
1819
                            $finalValues[] = static::getRecordTitle($relationTableNameForField, $relationRecord);
1820
                        }
1821
                        $l = implode(', ', $finalValues);
1822
                    }
1823
                } else {
1824
                    $l = implode(', ', GeneralUtility::trimExplode(',', $value, true));
1825
                }
1826
                break;
1827
            case 'check':
1828
                if (!is_array($theColConf['items'])) {
1829
                    $l = $value ? $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:yes') : $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:no');
1830
                } elseif (count($theColConf['items']) === 1) {
1831
                    reset($theColConf['items']);
1832
                    $invertStateDisplay = current($theColConf['items'])['invertStateDisplay'] ?? false;
1833
                    if ($invertStateDisplay) {
1834
                        $value = !$value;
1835
                    }
1836
                    $l = $value ? $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:yes') : $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:no');
1837
                } else {
1838
                    $lA = [];
1839
                    foreach ($theColConf['items'] as $key => $val) {
1840
                        if ($value & 2 ** $key) {
1841
                            $lA[] = $lang->sL($val[0]);
1842
                        }
1843
                    }
1844
                    $l = implode(', ', $lA);
1845
                }
1846
                break;
1847
            case 'input':
1848
                // Hide value 0 for dates, but show it for everything else
1849
                // todo: phpstan states that $value always exists and is not nullable. At the moment, this is a false
1850
                //       positive as null can be passed into this method via $value. As soon as more strict types are
1851
                //       used, this isset check must be replaced with a more appropriate check.
1852
                if (isset($value)) {
1853
                    $dateTimeFormats = QueryHelper::getDateTimeFormats();
1854
1855
                    if (GeneralUtility::inList($theColConf['eval'] ?? '', 'date')) {
1856
                        // Handle native date field
1857
                        if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'date') {
1858
                            $value = $value === $dateTimeFormats['date']['empty'] ? 0 : (int)strtotime($value);
1859
                        } else {
1860
                            $value = (int)$value;
1861
                        }
1862
                        if (!empty($value)) {
1863
                            $ageSuffix = '';
1864
                            $dateColumnConfiguration = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
1865
                            $ageDisplayKey = 'disableAgeDisplay';
1866
1867
                            // generate age suffix as long as not explicitly suppressed
1868
                            if (!isset($dateColumnConfiguration[$ageDisplayKey])
1869
                                // non typesafe comparison on intention
1870
                                || $dateColumnConfiguration[$ageDisplayKey] == false
1871
                            ) {
1872
                                $ageSuffix = ' (' . ($GLOBALS['EXEC_TIME'] - $value > 0 ? '-' : '')
1873
                                    . self::calcAge(
1874
                                        (int)abs($GLOBALS['EXEC_TIME'] - $value),
1875
                                        $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears')
1876
                                    )
1877
                                    . ')';
1878
                            }
1879
1880
                            $l = self::date($value) . $ageSuffix;
1881
                        }
1882
                    } elseif (GeneralUtility::inList($theColConf['eval'] ?? '', 'time')) {
1883
                        // Handle native time field
1884
                        if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'time') {
1885
                            $value = $value === $dateTimeFormats['time']['empty'] ? 0 : (int)strtotime('1970-01-01 ' . $value);
1886
                        } else {
1887
                            $value = (int)$value;
1888
                        }
1889
                        if (!empty($value)) {
1890
                            $l = gmdate('H:i', (int)$value);
1891
                        }
1892
                    } elseif (GeneralUtility::inList($theColConf['eval'] ?? '', 'timesec')) {
1893
                        // Handle native time field
1894
                        if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'time') {
1895
                            $value = $value === $dateTimeFormats['time']['empty'] ? 0 : (int)strtotime('1970-01-01 ' . $value);
1896
                        } else {
1897
                            $value = (int)$value;
1898
                        }
1899
                        if (!empty($value)) {
1900
                            $l = gmdate('H:i:s', (int)$value);
1901
                        }
1902
                    } elseif (GeneralUtility::inList($theColConf['eval'] ?? '', 'datetime')) {
1903
                        // Handle native datetime field
1904
                        if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'datetime') {
1905
                            $value = $value === $dateTimeFormats['datetime']['empty'] ? 0 : (int)strtotime($value);
1906
                        } else {
1907
                            $value = (int)$value;
1908
                        }
1909
                        if (!empty($value)) {
1910
                            $l = self::datetime($value);
1911
                        }
1912
                    } else {
1913
                        $l = $value;
1914
                    }
1915
                }
1916
                break;
1917
            case 'flex':
1918
                $l = strip_tags($value);
1919
                break;
1920
            default:
1921
                if ($defaultPassthrough) {
1922
                    $l = $value;
1923
                } elseif (isset($theColConf['MM'])) {
1924
                    $l = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:notAvailableAbbreviation');
1925
                } elseif ($value) {
1926
                    $l = GeneralUtility::fixed_lgd_cs(strip_tags($value), 200);
1927
                }
1928
        }
1929
        // If this field is a password field, then hide the password by changing it to a random number of asterisk (*)
1930
        if (!empty($theColConf['eval']) && stripos($theColConf['eval'], 'password') !== false) {
1931
            $l = '';
1932
            $randomNumber = random_int(5, 12);
1933
            for ($i = 0; $i < $randomNumber; $i++) {
1934
                $l .= '*';
1935
            }
1936
        }
1937
        /*****************
1938
         *HOOK: post-processing the human readable output from a record
1939
         ****************/
1940
        $null = null;
1941
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] ?? [] as $_funcRef) {
1942
            $params = [
1943
                'value' => $l,
1944
                'colConf' => $theColConf
1945
            ];
1946
            $l = GeneralUtility::callUserFunction($_funcRef, $params, $null);
1947
        }
1948
        if ($fixed_lgd_chars) {
1949
            return GeneralUtility::fixed_lgd_cs($l, $fixed_lgd_chars);
1950
        }
1951
        return $l;
1952
    }
1953
1954
    /**
1955
     * Same as ->getProcessedValue() but will go easy on fields like "tstamp" and "pid" which are not configured in TCA - they will be formatted by this function instead.
1956
     *
1957
     * @param string $table Table name, present in TCA
1958
     * @param string $fN Field name
1959
     * @param string $fV Field value
1960
     * @param int $fixed_lgd_chars The max amount of characters the value may occupy
1961
     * @param int $uid Uid of the current record
1962
     * @param bool $forceResult If BackendUtility::getRecordTitle is used to process the value, this parameter is forwarded.
1963
     * @param int $pid Optional page uid is used to evaluate page TSConfig for the given field
1964
     * @return string
1965
     * @see getProcessedValue()
1966
     */
1967
    public static function getProcessedValueExtra(
1968
        $table,
1969
        $fN,
1970
        $fV,
1971
        $fixed_lgd_chars = 0,
1972
        $uid = 0,
1973
        $forceResult = true,
1974
        $pid = 0
1975
    ) {
1976
        $fVnew = self::getProcessedValue($table, $fN, $fV, $fixed_lgd_chars, true, false, $uid, $forceResult, $pid);
1977
        if (!isset($fVnew)) {
1978
            if (is_array($GLOBALS['TCA'][$table])) {
1979
                if ($fN == $GLOBALS['TCA'][$table]['ctrl']['tstamp'] || $fN == $GLOBALS['TCA'][$table]['ctrl']['crdate']) {
1980
                    $fVnew = self::datetime((int)$fV);
1981
                } elseif ($fN === 'pid') {
1982
                    // Fetches the path with no regard to the users permissions to select pages.
1983
                    $fVnew = self::getRecordPath((int)$fV, '1=1', 20);
1984
                } else {
1985
                    $fVnew = $fV;
1986
                }
1987
            }
1988
        }
1989
        return $fVnew;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $fVnew also could return the type array<integer,string> which is incompatible with the documented return type string.
Loading history...
1990
    }
1991
1992
    /**
1993
     * Returns fields for a table, $table, which would typically be interesting to select
1994
     * This includes uid, the fields defined for title, icon-field.
1995
     * Returned as a list ready for query ($prefix can be set to eg. "pages." if you are selecting from the pages table and want the table name prefixed)
1996
     *
1997
     * @param string $table Table name, present in $GLOBALS['TCA']
1998
     * @param string $prefix Table prefix
1999
     * @param array $fields Preset fields (must include prefix if that is used)
2000
     * @return string List of fields.
2001
     * @internal should only be used from within TYPO3 Core
2002
     */
2003
    public static function getCommonSelectFields($table, $prefix = '', $fields = [])
2004
    {
2005
        $fields[] = $prefix . 'uid';
2006
        if (isset($GLOBALS['TCA'][$table]['ctrl']['label']) && $GLOBALS['TCA'][$table]['ctrl']['label'] != '') {
2007
            $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['label'];
2008
        }
2009
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['label_alt'])) {
2010
            $secondFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], true);
2011
            foreach ($secondFields as $fieldN) {
2012
                $fields[] = $prefix . $fieldN;
2013
            }
2014
        }
2015
        if (static::isTableWorkspaceEnabled($table)) {
2016
            $fields[] = $prefix . 't3ver_state';
2017
            $fields[] = $prefix . 't3ver_wsid';
2018
        }
2019
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['selicon_field'])) {
2020
            $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['selicon_field'];
2021
        }
2022
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['typeicon_column'])) {
2023
            $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['typeicon_column'];
2024
        }
2025
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'])) {
2026
            $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'];
2027
        }
2028
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime'])) {
2029
            $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime'];
2030
        }
2031
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime'])) {
2032
            $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime'];
2033
        }
2034
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group'])) {
2035
            $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group'];
2036
        }
2037
        return implode(',', array_unique($fields));
2038
    }
2039
2040
    /*******************************************
2041
     *
2042
     * Backend Modules API functions
2043
     *
2044
     *******************************************/
2045
2046
    /**
2047
     * Returns CSH help text (description), if configured for, as an array (title, description)
2048
     *
2049
     * @param string $table Table name
2050
     * @param string $field Field name
2051
     * @return array With keys 'description' (raw, as available in locallang), 'title' (optional), 'moreInfo'
2052
     * @internal should only be used from within TYPO3 Core
2053
     */
2054
    public static function helpTextArray($table, $field)
2055
    {
2056
        if (!isset($GLOBALS['TCA_DESCR'][$table]['columns'])) {
2057
            static::getLanguageService()->loadSingleTableDescription($table);
2058
        }
2059
        $output = [
2060
            'description' => null,
2061
            'title' => null,
2062
            'moreInfo' => false
2063
        ];
2064
        if (isset($GLOBALS['TCA_DESCR'][$table]['columns'][$field]) && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field])) {
2065
            $data = $GLOBALS['TCA_DESCR'][$table]['columns'][$field];
2066
            // Add alternative title, if defined
2067
            if ($data['alttitle']) {
2068
                $output['title'] = $data['alttitle'];
2069
            }
2070
            // If we have more information to show and access to the cshmanual
2071
            if (($data['image_descr'] || $data['seeAlso'] || $data['details'] || $data['syntax'])
2072
                && static::getBackendUserAuthentication()->check('modules', 'help_CshmanualCshmanual')
2073
            ) {
2074
                $output['moreInfo'] = true;
2075
            }
2076
            // Add description
2077
            if ($data['description']) {
2078
                $output['description'] = $data['description'];
2079
            }
2080
        }
2081
        return $output;
2082
    }
2083
2084
    /**
2085
     * Returns CSH help text
2086
     *
2087
     * @param string $table Table name
2088
     * @param string $field Field name
2089
     * @return string HTML content for help text
2090
     * @see cshItem()
2091
     * @internal should only be used from within TYPO3 Core
2092
     */
2093
    public static function helpText($table, $field)
2094
    {
2095
        $helpTextArray = self::helpTextArray($table, $field);
2096
        $output = '';
2097
        $arrow = '';
2098
        // Put header before the rest of the text
2099
        if ($helpTextArray['title'] !== null) {
2100
            $output .= '<h2>' . $helpTextArray['title'] . '</h2>';
2101
        }
2102
        // Add see also arrow if we have more info
2103
        if ($helpTextArray['moreInfo']) {
2104
            /** @var IconFactory $iconFactory */
2105
            $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
2106
            $arrow = $iconFactory->getIcon('actions-view-go-forward', Icon::SIZE_SMALL)->render();
2107
        }
2108
        // Wrap description and arrow in p tag
2109
        if ($helpTextArray['description'] !== null || $arrow) {
2110
            $output .= '<p class="help-short">' . nl2br(htmlspecialchars($helpTextArray['description'])) . $arrow . '</p>';
2111
        }
2112
        return $output;
2113
    }
2114
2115
    /**
2116
     * API function that wraps the text / html in help text, so if a user hovers over it
2117
     * the help text will show up
2118
     *
2119
     * @param string $table The table name for which the help should be shown
2120
     * @param string $field The field name for which the help should be shown
2121
     * @param string $text The text which should be wrapped with the help text
2122
     * @param array $overloadHelpText Array with text to overload help text
2123
     * @return string the HTML code ready to render
2124
     * @internal should only be used from within TYPO3 Core
2125
     */
2126
    public static function wrapInHelp($table, $field, $text = '', array $overloadHelpText = [])
2127
    {
2128
        // Initialize some variables
2129
        $helpText = '';
2130
        $abbrClassAdd = '';
2131
        $hasHelpTextOverload = !empty($overloadHelpText);
2132
        // Get the help text that should be shown on hover
2133
        if (!$hasHelpTextOverload) {
2134
            $helpText = self::helpText($table, $field);
2135
        }
2136
        // If there's a help text or some overload information, proceed with preparing an output
2137
        if (!empty($helpText) || $hasHelpTextOverload) {
2138
            // If no text was given, just use the regular help icon
2139
            if ($text == '') {
2140
                $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
2141
                $text = $iconFactory->getIcon('actions-system-help-open', Icon::SIZE_SMALL)->render();
2142
                $abbrClassAdd = ' help-teaser-icon';
2143
            }
2144
            $text = '<abbr class="help-teaser' . $abbrClassAdd . '">' . $text . '</abbr>';
2145
            $wrappedText = '<span class="help-link" data-table="' . $table . '" data-field="' . $field . '"';
2146
            // The overload array may provide a title and a description
2147
            // If either one is defined, add them to the "data" attributes
2148
            if ($hasHelpTextOverload) {
2149
                if (isset($overloadHelpText['title'])) {
2150
                    $wrappedText .= ' data-title="' . htmlspecialchars($overloadHelpText['title']) . '"';
2151
                }
2152
                if (isset($overloadHelpText['description'])) {
2153
                    $wrappedText .= ' data-description="' . htmlspecialchars($overloadHelpText['description']) . '"';
2154
                }
2155
            }
2156
            $wrappedText .= '>' . $text . '</span>';
2157
            return $wrappedText;
2158
        }
2159
        return $text;
2160
    }
2161
2162
    /**
2163
     * API for getting CSH icons/text for use in backend modules.
2164
     * TCA_DESCR will be loaded if it isn't already
2165
     *
2166
     * @param string $table Table name ('_MOD_'+module name)
2167
     * @param string $field Field name (CSH locallang main key)
2168
     * @param string $_ (unused)
2169
     * @param string $wrap Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
2170
     * @return string HTML content for help text
2171
     */
2172
    public static function cshItem($table, $field, $_ = '', $wrap = '')
2173
    {
2174
        static::getLanguageService()->loadSingleTableDescription($table);
2175
        if (is_array($GLOBALS['TCA_DESCR'][$table])
2176
            && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field])
2177
        ) {
2178
            // Creating short description
2179
            $output = self::wrapInHelp($table, $field);
2180
            if ($output && $wrap) {
2181
                $wrParts = explode('|', $wrap);
2182
                $output = $wrParts[0] . $output . $wrParts[1];
2183
            }
2184
            return $output;
2185
        }
2186
        return '';
2187
    }
2188
2189
    /**
2190
     * Returns a JavaScript string for viewing the page id, $id
2191
     * It will re-use any window already open.
2192
     *
2193
     * @param int $pageUid Page UID
2194
     * @param string $backPath Must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2195
     * @param array|null $rootLine If root line is supplied the function will look for the first found domain record and use that URL instead (if found)
2196
     * @param string $anchorSection Optional anchor to the URL
2197
     * @param string $alternativeUrl An alternative URL that, if set, will ignore other parameters except $switchFocus: It will return the window.open command wrapped around this URL!
2198
     * @param string $additionalGetVars Additional GET variables.
2199
     * @param bool $switchFocus If TRUE, then the preview window will gain the focus.
2200
     * @return string
2201
     */
2202
    public static function viewOnClick(
2203
        $pageUid,
2204
        $backPath = '',
2205
        $rootLine = null,
2206
        $anchorSection = '',
2207
        $alternativeUrl = '',
2208
        $additionalGetVars = '',
2209
        $switchFocus = true
2210
    ) {
2211
        try {
2212
            $previewUrl = self::getPreviewUrl(
2213
                $pageUid,
2214
                $backPath,
2215
                $rootLine,
2216
                $anchorSection,
2217
                $alternativeUrl,
2218
                $additionalGetVars,
2219
                $switchFocus
2220
            );
2221
        } catch (UnableToLinkToPageException $e) {
2222
            return '';
2223
        }
2224
2225
        $onclickCode = 'var previewWin = window.open(' . GeneralUtility::quoteJSvalue($previewUrl) . ',\'newTYPO3frontendWindow\');'
2226
            . ($switchFocus ? 'previewWin.focus();' : '') . LF
2227
            . 'if (previewWin.location.href === ' . GeneralUtility::quoteJSvalue($previewUrl) . ') { previewWin.location.reload(); };';
2228
2229
        return $onclickCode;
2230
    }
2231
2232
    /**
2233
     * Returns the preview url
2234
     *
2235
     * It will detect the correct domain name if needed and provide the link with the right back path.
2236
     *
2237
     * @param int $pageUid Page UID
2238
     * @param string $backPath Must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2239
     * @param array|null $rootLine If root line is supplied the function will look for the first found domain record and use that URL instead (if found)
2240
     * @param string $anchorSection Optional anchor to the URL
2241
     * @param string $alternativeUrl An alternative URL that, if set, will ignore other parameters except $switchFocus: It will return the window.open command wrapped around this URL!
2242
     * @param string $additionalGetVars Additional GET variables.
2243
     * @param bool $switchFocus If TRUE, then the preview window will gain the focus.
2244
     * @return string
2245
     */
2246
    public static function getPreviewUrl(
2247
        $pageUid,
2248
        $backPath = '',
2249
        $rootLine = null,
2250
        $anchorSection = '',
2251
        $alternativeUrl = '',
2252
        $additionalGetVars = '',
2253
        &$switchFocus = true
2254
    ): string {
2255
        $viewScript = '/index.php?id=';
2256
        if ($alternativeUrl) {
2257
            $viewScript = $alternativeUrl;
2258
        }
2259
2260
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] ?? [] as $className) {
2261
            $hookObj = GeneralUtility::makeInstance($className);
2262
            if (method_exists($hookObj, 'preProcess')) {
2263
                $hookObj->preProcess(
2264
                    $pageUid,
2265
                    $backPath,
2266
                    $rootLine,
2267
                    $anchorSection,
2268
                    $viewScript,
2269
                    $additionalGetVars,
2270
                    $switchFocus
2271
                );
2272
            }
2273
        }
2274
2275
        // If there is an alternative URL or the URL has been modified by a hook, use that one.
2276
        if ($alternativeUrl || $viewScript !== '/index.php?id=') {
2277
            $previewUrl = $viewScript;
2278
        } else {
2279
            $permissionClause = $GLOBALS['BE_USER']->getPagePermsClause(Permission::PAGE_SHOW);
2280
            $pageInfo = self::readPageAccess($pageUid, $permissionClause) ?: [];
2281
            // prepare custom context for link generation (to allow for example time based previews)
2282
            $context = clone GeneralUtility::makeInstance(Context::class);
2283
            $additionalGetVars .= self::ADMCMD_previewCmds($pageInfo, $context);
2284
2285
            // Build the URL with a site as prefix, if configured
2286
            $siteFinder = GeneralUtility::makeInstance(SiteFinder::class);
2287
            // Check if the page (= its rootline) has a site attached, otherwise just keep the URL as is
2288
            $rootLine = $rootLine ?? BackendUtility::BEgetRootLine($pageUid);
2289
            try {
2290
                $site = $siteFinder->getSiteByPageId((int)$pageUid, $rootLine);
2291
            } catch (SiteNotFoundException $e) {
2292
                throw new UnableToLinkToPageException('The page ' . $pageUid . ' had no proper connection to a site, no link could be built.', 1559794919);
2293
            }
2294
            // Create a multi-dimensional array out of the additional get vars
2295
            $additionalQueryParams = [];
2296
            parse_str($additionalGetVars, $additionalQueryParams);
2297
            if (isset($additionalQueryParams['L'])) {
2298
                $additionalQueryParams['_language'] = $additionalQueryParams['_language'] ?? $additionalQueryParams['L'];
2299
                unset($additionalQueryParams['L']);
2300
            }
2301
            try {
2302
                $previewUrl = (string)$site->getRouter($context)->generateUri(
2303
                    $pageUid,
2304
                    $additionalQueryParams,
2305
                    $anchorSection,
2306
                    RouterInterface::ABSOLUTE_URL
2307
                );
2308
            } catch (\InvalidArgumentException | InvalidRouteArgumentsException $e) {
2309
                throw new UnableToLinkToPageException('The page ' . $pageUid . ' had no proper connection to a site, no link could be built.', 1559794914);
2310
            }
2311
        }
2312
2313
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] ?? [] as $className) {
2314
            $hookObj = GeneralUtility::makeInstance($className);
2315
            if (method_exists($hookObj, 'postProcess')) {
2316
                $previewUrl = $hookObj->postProcess(
2317
                    $previewUrl,
2318
                    $pageUid,
2319
                    $rootLine,
2320
                    $anchorSection,
2321
                    $viewScript,
2322
                    $additionalGetVars,
2323
                    $switchFocus
2324
                );
2325
            }
2326
        }
2327
2328
        return $previewUrl;
2329
    }
2330
2331
    /**
2332
     * Makes click menu link (context sensitive menu)
2333
     *
2334
     * Returns $str wrapped in a link which will activate the context sensitive
2335
     * menu for the record ($table/$uid) or file ($table = file)
2336
     * The link will load the top frame with the parameter "&item" which is the table, uid
2337
     * and context arguments imploded by "|": rawurlencode($table.'|'.$uid.'|'.$context)
2338
     *
2339
     * @param string $content String to be wrapped in link, typ. image tag.
2340
     * @param string $table Table name/File path. If the icon is for a database
2341
     * record, enter the tablename from $GLOBALS['TCA']. If a file then enter
2342
     * the absolute filepath
2343
     * @param int|string $uid If icon is for database record this is the UID for the
2344
     * record from $table or identifier for sys_file record
2345
     * @param string $context Set tree if menu is called from tree view
2346
     * @param string $_addParams NOT IN USE Deprecated since TYPO3 11, will be removed in TYPO3 12.
2347
     * @param string $_enDisItems NOT IN USE Deprecated since TYPO3 11, will be removed in TYPO3 12.
2348
     * @param bool $returnTagParameters If set, will return only the onclick
2349
     * JavaScript, not the whole link. Deprecated since TYPO3 11, will be removed in TYPO3 12.
2350
     *
2351
     * @return string|array The link wrapped input string.
2352
     */
2353
    public static function wrapClickMenuOnIcon(
2354
        $content,
2355
        $table,
2356
        $uid = 0,
2357
        $context = '',
2358
        $_addParams = '',
2359
        $_enDisItems = '',
2360
        $returnTagParameters = false
2361
    ) {
2362
        $tagParameters = self::getClickMenuOnIconTagParameters((string)$table, $uid, (string)$context);
2363
2364
        if ($_addParams !== '') {
2365
            trigger_error('Calling BackendUtility::wrapClickMenuOnIcon() with unused 5th parameter is deprecated and will be removed in v12.', E_USER_DEPRECATED);
2366
        }
2367
        if ($_enDisItems !== '') {
2368
            trigger_error('Calling BackendUtility::wrapClickMenuOnIcon() with unused 6th parameter is deprecated and will be removed in v12.', E_USER_DEPRECATED);
2369
        }
2370
        if ($returnTagParameters) {
2371
            trigger_error('Calling BackendUtility::wrapClickMenuOnIcon() with 7th parameter set to true is deprecated and will be removed in v12. Please use BackendUtility::getClickMenuOnIconTagParameters() instead.', E_USER_DEPRECATED);
2372
            return $tagParameters;
2373
        }
2374
        return '<a href="#" ' . GeneralUtility::implodeAttributes($tagParameters, true) . '>' . $content . '</a>';
2375
    }
2376
2377
    /**
2378
     * @param string $table Table name/File path. If the icon is for a database
2379
     * record, enter the tablename from $GLOBALS['TCA']. If a file then enter
2380
     * the absolute filepath
2381
     * @param int|string $uid If icon is for database record this is the UID for the
2382
     * record from $table or identifier for sys_file record
2383
     * @param string $context Set tree if menu is called from tree view
2384
     * @return array
2385
     */
2386
    public static function getClickMenuOnIconTagParameters(string $table, $uid = 0, string $context = ''): array
2387
    {
2388
        return [
2389
            'class' => 't3js-contextmenutrigger',
2390
            'data-table' => $table,
2391
            'data-uid' => (string)$uid,
2392
            'data-context' => $context
2393
        ];
2394
    }
2395
2396
    /**
2397
     * Returns a URL with a command to TYPO3 Datahandler
2398
     *
2399
     * @param string $parameters Set of GET params to send. Example: "&cmd[tt_content][123][move]=456" or "&data[tt_content][123][hidden]=1&data[tt_content][123][title]=Hello%20World
2400
     * @param string $redirectUrl Redirect URL, default is to use $GLOBALS['TYPO3_REQUEST']->getAttribute('normalizedParams')->getRequestUri()
2401
     * @return string
2402
     */
2403
    public static function getLinkToDataHandlerAction($parameters, $redirectUrl = '')
2404
    {
2405
        $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
2406
        $url = (string)$uriBuilder->buildUriFromRoute('tce_db') . $parameters . '&redirect=';
2407
        $url .= rawurlencode($redirectUrl ?: $GLOBALS['TYPO3_REQUEST']->getAttribute('normalizedParams')->getRequestUri());
2408
        return $url;
2409
    }
2410
2411
    /**
2412
     * Returns a selector box "function menu" for a module
2413
     * See Inside TYPO3 for details about how to use / make Function menus
2414
     *
2415
     * @param mixed $mainParams The "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
2416
     * @param string $elementName The form elements name, probably something like "SET[...]
2417
     * @param string $currentValue The value to be selected currently.
2418
     * @param array $menuItems An array with the menu items for the selector box
2419
     * @param string $script The script to send the &id to, if empty it's automatically found
2420
     * @param string $addParams Additional parameters to pass to the script.
2421
     * @return string HTML code for selector box
2422
     */
2423
    public static function getFuncMenu(
2424
        $mainParams,
2425
        $elementName,
2426
        $currentValue,
2427
        $menuItems,
2428
        $script = '',
2429
        $addParams = ''
2430
    ) {
2431
        if (!is_array($menuItems) || count($menuItems) <= 1) {
0 ignored issues
show
introduced by
The condition is_array($menuItems) is always true.
Loading history...
2432
            return '';
2433
        }
2434
        $scriptUrl = self::buildScriptUrl($mainParams, $addParams, $script);
2435
        $options = [];
2436
        foreach ($menuItems as $value => $label) {
2437
            $options[] = '<option value="'
2438
                . htmlspecialchars($value) . '"'
2439
                . ((string)$currentValue === (string)$value ? ' selected="selected"' : '') . '>'
2440
                . htmlspecialchars($label, ENT_COMPAT, 'UTF-8', false) . '</option>';
2441
        }
2442
        $dataMenuIdentifier = str_replace(['SET[', ']'], '', $elementName);
2443
        $dataMenuIdentifier = GeneralUtility::camelCaseToLowerCaseUnderscored($dataMenuIdentifier);
2444
        $dataMenuIdentifier = str_replace('_', '-', $dataMenuIdentifier);
2445
        if (!empty($options)) {
2446
            // relies on module 'TYPO3/CMS/Backend/ActionDispatcher'
2447
            $attributes = GeneralUtility::implodeAttributes([
2448
                'name' => $elementName,
2449
                'class' => 'form-select mb-3',
2450
                'data-menu-identifier' => $dataMenuIdentifier,
2451
                'data-global-event' => 'change',
2452
                'data-action-navigate' => '$data=~s/$value/',
2453
                'data-navigate-value' => $scriptUrl . '&' . $elementName . '=${value}',
2454
            ], true);
2455
            return sprintf(
2456
                '<select %s>%s</select>',
2457
                $attributes,
2458
                implode('', $options)
2459
            );
2460
        }
2461
        return '';
2462
    }
2463
2464
    /**
2465
     * Returns a selector box to switch the view
2466
     * Based on BackendUtility::getFuncMenu() but done as new function because it has another purpose.
2467
     * Mingling with getFuncMenu would harm the docHeader Menu.
2468
     *
2469
     * @param mixed $mainParams The "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
2470
     * @param string $elementName The form elements name, probably something like "SET[...]
2471
     * @param string $currentValue The value to be selected currently.
2472
     * @param array $menuItems An array with the menu items for the selector box
2473
     * @param string $script The script to send the &id to, if empty it's automatically found
2474
     * @param string $addParams Additional parameters to pass to the script.
2475
     * @return string HTML code for selector box
2476
     */
2477
    public static function getDropdownMenu(
2478
        $mainParams,
2479
        $elementName,
2480
        $currentValue,
2481
        $menuItems,
2482
        $script = '',
2483
        $addParams = ''
2484
    ) {
2485
        if (!is_array($menuItems) || count($menuItems) <= 1) {
0 ignored issues
show
introduced by
The condition is_array($menuItems) is always true.
Loading history...
2486
            return '';
2487
        }
2488
        $scriptUrl = self::buildScriptUrl($mainParams, $addParams, $script);
2489
        $options = [];
2490
        foreach ($menuItems as $value => $label) {
2491
            $options[] = '<option value="'
2492
                . htmlspecialchars($value) . '"'
2493
                . ((string)$currentValue === (string)$value ? ' selected="selected"' : '') . '>'
2494
                . htmlspecialchars($label, ENT_COMPAT, 'UTF-8', false) . '</option>';
2495
        }
2496
        $dataMenuIdentifier = str_replace(['SET[', ']'], '', $elementName);
2497
        $dataMenuIdentifier = GeneralUtility::camelCaseToLowerCaseUnderscored($dataMenuIdentifier);
2498
        $dataMenuIdentifier = str_replace('_', '-', $dataMenuIdentifier);
2499
        if (!empty($options)) {
2500
            // relies on module 'TYPO3/CMS/Backend/ActionDispatcher'
2501
            $attributes = GeneralUtility::implodeAttributes([
2502
                'name' => $elementName,
2503
                'data-menu-identifier' => $dataMenuIdentifier,
2504
                'data-global-event' => 'change',
2505
                'data-action-navigate' => '$data=~s/$value/',
2506
                'data-navigate-value' => $scriptUrl . '&' . $elementName . '=${value}',
2507
            ], true);
2508
            return '
2509
			<div class="input-group">
2510
				<!-- Function Menu of module -->
2511
				<select class="form-select form-select-sm" ' . $attributes . '>
2512
					' . implode(LF, $options) . '
2513
				</select>
2514
			</div>
2515
						';
2516
        }
2517
        return '';
2518
    }
2519
2520
    /**
2521
     * Checkbox function menu.
2522
     * Works like ->getFuncMenu() but takes no $menuItem array since this is a simple checkbox.
2523
     *
2524
     * @param mixed $mainParams $id is the "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
2525
     * @param string $elementName The form elements name, probably something like "SET[...]
2526
     * @param string $currentValue The value to be selected currently.
2527
     * @param string $script The script to send the &id to, if empty it's automatically found
2528
     * @param string $addParams Additional parameters to pass to the script.
2529
     * @param string $tagParams Additional attributes for the checkbox input tag
2530
     * @return string HTML code for checkbox
2531
     * @see getFuncMenu()
2532
     */
2533
    public static function getFuncCheck(
2534
        $mainParams,
2535
        $elementName,
2536
        $currentValue,
2537
        $script = '',
2538
        $addParams = '',
2539
        $tagParams = ''
2540
    ) {
2541
        // relies on module 'TYPO3/CMS/Backend/ActionDispatcher'
2542
        $scriptUrl = self::buildScriptUrl($mainParams, $addParams, $script);
2543
        $attributes = GeneralUtility::implodeAttributes([
2544
            'type' => 'checkbox',
2545
            'class' => 'form-check-input',
2546
            'name' => $elementName,
2547
            'value' => '1',
2548
            'data-global-event' => 'change',
2549
            'data-action-navigate' => '$data=~s/$value/',
2550
            'data-navigate-value' => sprintf('%s&%s=${value}', $scriptUrl, $elementName),
2551
            'data-empty-value' => '0',
2552
        ], true);
2553
        return
2554
            '<input ' . $attributes .
2555
            ($currentValue ? ' checked="checked"' : '') .
2556
            ($tagParams ? ' ' . $tagParams : '') .
2557
            ' />';
2558
    }
2559
2560
    /**
2561
     * Input field function menu
2562
     * Works like ->getFuncMenu() / ->getFuncCheck() but displays an input field instead which updates the script "onchange"
2563
     *
2564
     * @param mixed $mainParams $id is the "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
2565
     * @param string $elementName The form elements name, probably something like "SET[...]
2566
     * @param string $currentValue The value to be selected currently.
2567
     * @param int $size Relative size of input field, max is 48
2568
     * @param string $script The script to send the &id to, if empty it's automatically found
2569
     * @param string $addParams Additional parameters to pass to the script.
2570
     * @return string HTML code for input text field.
2571
     * @see getFuncMenu()
2572
     */
2573
    public static function getFuncInput(
2574
        $mainParams,
2575
        $elementName,
2576
        $currentValue,
2577
        $size = 10,
2578
        $script = '',
2579
        $addParams = ''
2580
    ) {
2581
        $scriptUrl = self::buildScriptUrl($mainParams, $addParams, $script);
2582
        $onChange = 'window.location.href = ' . GeneralUtility::quoteJSvalue($scriptUrl . '&' . $elementName . '=') . '+escape(this.value);';
2583
        return '<input type="text" class="form-control" name="' . $elementName . '" value="' . htmlspecialchars($currentValue) . '" onchange="' . htmlspecialchars($onChange) . '" />';
2584
    }
2585
2586
    /**
2587
     * Builds the URL to the current script with given arguments
2588
     *
2589
     * @param mixed $mainParams $id is the "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
2590
     * @param string $addParams Additional parameters to pass to the script.
2591
     * @param string $script The script to send the &id to, if empty it's automatically found
2592
     * @return string The complete script URL
2593
     * @todo Check if this can be removed or replaced by routing
2594
     */
2595
    protected static function buildScriptUrl($mainParams, $addParams, $script = '')
2596
    {
2597
        if (!is_array($mainParams)) {
2598
            $mainParams = ['id' => $mainParams];
2599
        }
2600
        if (!$script) {
2601
            $script = PathUtility::basename(Environment::getCurrentScript());
2602
        }
2603
2604
        if (($GLOBALS['TYPO3_REQUEST'] ?? null) instanceof ServerRequestInterface
2605
            && ($route = $GLOBALS['TYPO3_REQUEST']->getAttribute('route')) instanceof Route
2606
        ) {
2607
            $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
2608
            $scriptUrl = (string)$uriBuilder->buildUriFromRoutePath($route->getPath(), $mainParams);
2609
            $scriptUrl .= $addParams;
2610
        } else {
2611
            $scriptUrl = $script . HttpUtility::buildQueryString($mainParams, '?') . $addParams;
2612
        }
2613
2614
        return $scriptUrl;
2615
    }
2616
2617
    /**
2618
     * Call to update the page tree frame (or something else..?) after
2619
     * use 'updatePageTree' as a first parameter will set the page tree to be updated.
2620
     *
2621
     * @param string $set Key to set the update signal. When setting, this value contains strings telling WHAT to set. At this point it seems that the value "updatePageTree" is the only one it makes sense to set. If empty, all update signals will be removed.
2622
     * @param mixed $params Additional information for the update signal, used to only refresh a branch of the tree
2623
     * @see BackendUtility::getUpdateSignalCode()
2624
     */
2625
    public static function setUpdateSignal($set = '', $params = '')
2626
    {
2627
        $beUser = static::getBackendUserAuthentication();
2628
        $modData = $beUser->getModuleData(
2629
            \TYPO3\CMS\Backend\Utility\BackendUtility::class . '::getUpdateSignal',
2630
            'ses'
2631
        );
2632
        if ($set) {
2633
            $modData[$set] = [
2634
                'set' => $set,
2635
                'parameter' => $params
2636
            ];
2637
        } else {
2638
            // clear the module data
2639
            $modData = [];
2640
        }
2641
        $beUser->pushModuleData(\TYPO3\CMS\Backend\Utility\BackendUtility::class . '::getUpdateSignal', $modData);
2642
    }
2643
2644
    /**
2645
     * Call to update the page tree frame (or something else..?) if this is set by the function
2646
     * setUpdateSignal(). It will return some JavaScript that does the update
2647
     *
2648
     * @return string HTML javascript code
2649
     * @see BackendUtility::setUpdateSignal()
2650
     */
2651
    public static function getUpdateSignalCode()
2652
    {
2653
        $signals = [];
2654
        $modData = static::getBackendUserAuthentication()->getModuleData(
2655
            \TYPO3\CMS\Backend\Utility\BackendUtility::class . '::getUpdateSignal',
2656
            'ses'
2657
        );
2658
        if (empty($modData)) {
2659
            return '';
2660
        }
2661
        // Hook: Allows to let TYPO3 execute your JS code
2662
        $updateSignals = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['updateSignalHook'] ?? [];
2663
        // Loop through all setUpdateSignals and get the JS code
2664
        foreach ($modData as $set => $val) {
2665
            if (isset($updateSignals[$set])) {
2666
                $params = ['set' => $set, 'parameter' => $val['parameter'], 'JScode' => ''];
2667
                $ref = null;
2668
                GeneralUtility::callUserFunction($updateSignals[$set], $params, $ref);
2669
                $signals[] = $params['JScode'];
2670
            } else {
2671
                switch ($set) {
2672
                    case 'updatePageTree':
2673
                        $signals[] = '
2674
								if (top) {
2675
									top.document.dispatchEvent(new CustomEvent("typo3:pagetree:refresh"));
2676
								}';
2677
                        break;
2678
                    case 'updateFolderTree':
2679
                        $signals[] = '
2680
								if (top) {
2681
									top.document.dispatchEvent(new CustomEvent("typo3:filestoragetree:refresh"));
2682
								}';
2683
                        break;
2684
                    case 'updateModuleMenu':
2685
                        $signals[] = '
2686
								if (top && top.TYPO3.ModuleMenu && top.TYPO3.ModuleMenu.App) {
2687
									top.TYPO3.ModuleMenu.App.refreshMenu();
2688
								}';
2689
                        break;
2690
                    case 'updateTopbar':
2691
                        $signals[] = '
2692
								if (top && top.TYPO3.Backend && top.TYPO3.Backend.Topbar) {
2693
									top.TYPO3.Backend.Topbar.refresh();
2694
								}';
2695
                        break;
2696
                }
2697
            }
2698
        }
2699
        $content = implode(LF, $signals);
2700
        // For backwards compatibility, should be replaced
2701
        self::setUpdateSignal();
2702
        return $content;
2703
    }
2704
2705
    /**
2706
     * Returns an array which is most backend modules becomes MOD_SETTINGS containing values from function menus etc. determining the function of the module.
2707
     * This is kind of session variable management framework for the backend users.
2708
     * If a key from MOD_MENU is set in the CHANGED_SETTINGS array (eg. a value is passed to the script from the outside), this value is put into the settings-array
2709
     * Ultimately, see Inside TYPO3 for how to use this function in relation to your modules.
2710
     *
2711
     * @param array $MOD_MENU MOD_MENU is an array that defines the options in menus.
2712
     * @param array $CHANGED_SETTINGS CHANGED_SETTINGS represents the array used when passing values to the script from the menus.
2713
     * @param string $modName modName is the name of this module. Used to get the correct module data.
2714
     * @param string $type If type is 'ses' then the data is stored as session-lasting data. This means that it'll be wiped out the next time the user logs in.
2715
     * @param string $dontValidateList dontValidateList can be used to list variables that should not be checked if their value is found in the MOD_MENU array. Used for dynamically generated menus.
2716
     * @param string $setDefaultList List of default values from $MOD_MENU to set in the output array (only if the values from MOD_MENU are not arrays)
2717
     * @throws \RuntimeException
2718
     * @return array The array $settings, which holds a key for each MOD_MENU key and the values of each key will be within the range of values for each menuitem
2719
     */
2720
    public static function getModuleData(
2721
        $MOD_MENU,
2722
        $CHANGED_SETTINGS,
2723
        $modName,
2724
        $type = '',
2725
        $dontValidateList = '',
2726
        $setDefaultList = ''
2727
    ) {
2728
        if ($modName && is_string($modName)) {
2729
            // Getting stored user-data from this module:
2730
            $beUser = static::getBackendUserAuthentication();
2731
            $settings = $beUser->getModuleData($modName, $type);
2732
            $changed = 0;
2733
            if (!is_array($settings)) {
2734
                $changed = 1;
2735
                $settings = [];
2736
            }
2737
            if (is_array($MOD_MENU)) {
0 ignored issues
show
introduced by
The condition is_array($MOD_MENU) is always true.
Loading history...
2738
                foreach ($MOD_MENU as $key => $var) {
2739
                    // If a global var is set before entering here. eg if submitted, then it's substituting the current value the array.
2740
                    if (is_array($CHANGED_SETTINGS) && isset($CHANGED_SETTINGS[$key])) {
2741
                        if (is_array($CHANGED_SETTINGS[$key])) {
2742
                            $serializedSettings = serialize($CHANGED_SETTINGS[$key]);
2743
                            if ((string)$settings[$key] !== $serializedSettings) {
2744
                                $settings[$key] = $serializedSettings;
2745
                                $changed = 1;
2746
                            }
2747
                        } else {
2748
                            if ((string)$settings[$key] !== (string)$CHANGED_SETTINGS[$key]) {
2749
                                $settings[$key] = $CHANGED_SETTINGS[$key];
2750
                                $changed = 1;
2751
                            }
2752
                        }
2753
                    }
2754
                    // If the $var is an array, which denotes the existence of a menu, we check if the value is permitted
2755
                    if (is_array($var) && (!$dontValidateList || !GeneralUtility::inList($dontValidateList, $key))) {
2756
                        // If the setting is an array or not present in the menu-array, MOD_MENU, then the default value is inserted.
2757
                        if (is_array($settings[$key]) || !isset($MOD_MENU[$key][$settings[$key]])) {
2758
                            $settings[$key] = (string)key($var);
2759
                            $changed = 1;
2760
                        }
2761
                    }
2762
                    // Sets default values (only strings/checkboxes, not menus)
2763
                    if ($setDefaultList && !is_array($var)) {
2764
                        if (GeneralUtility::inList($setDefaultList, $key) && !isset($settings[$key])) {
2765
                            $settings[$key] = (string)$var;
2766
                        }
2767
                    }
2768
                }
2769
            } else {
2770
                throw new \RuntimeException('No menu', 1568119229);
2771
            }
2772
            if ($changed) {
2773
                $beUser->pushModuleData($modName, $settings);
2774
            }
2775
            return $settings;
2776
        }
2777
        throw new \RuntimeException('Wrong module name "' . $modName . '"', 1568119221);
2778
    }
2779
2780
    /*******************************************
2781
     *
2782
     * Core
2783
     *
2784
     *******************************************/
2785
    /**
2786
     * Unlock or Lock a record from $table with $uid
2787
     * If $table and $uid is not set, then all locking for the current BE_USER is removed!
2788
     *
2789
     * @param string $table Table name
2790
     * @param int $uid Record uid
2791
     * @param int $pid Record pid
2792
     * @internal
2793
     */
2794
    public static function lockRecords($table = '', $uid = 0, $pid = 0)
2795
    {
2796
        $beUser = static::getBackendUserAuthentication();
2797
        if (isset($beUser->user['uid'])) {
2798
            $userId = (int)$beUser->user['uid'];
2799
            if ($table && $uid) {
2800
                $fieldsValues = [
2801
                    'userid' => $userId,
2802
                    'feuserid' => 0,
2803
                    'tstamp' => $GLOBALS['EXEC_TIME'],
2804
                    'record_table' => $table,
2805
                    'record_uid' => $uid,
2806
                    'username' => $beUser->user['username'],
2807
                    'record_pid' => $pid
2808
                ];
2809
                GeneralUtility::makeInstance(ConnectionPool::class)
2810
                    ->getConnectionForTable('sys_lockedrecords')
2811
                    ->insert(
2812
                        'sys_lockedrecords',
2813
                        $fieldsValues
2814
                    );
2815
            } else {
2816
                GeneralUtility::makeInstance(ConnectionPool::class)
2817
                    ->getConnectionForTable('sys_lockedrecords')
2818
                    ->delete(
2819
                        'sys_lockedrecords',
2820
                        ['userid' => (int)$userId]
2821
                    );
2822
            }
2823
        }
2824
    }
2825
2826
    /**
2827
     * Returns information about whether the record from table, $table, with uid, $uid is currently locked
2828
     * (edited by another user - which should issue a warning).
2829
     * Notice: Locking is not strictly carried out since locking is abandoned when other backend scripts
2830
     * are activated - which means that a user CAN have a record "open" without having it locked.
2831
     * So this just serves as a warning that counts well in 90% of the cases, which should be sufficient.
2832
     *
2833
     * @param string $table Table name
2834
     * @param int $uid Record uid
2835
     * @return array|bool
2836
     * @internal
2837
     */
2838
    public static function isRecordLocked($table, $uid)
2839
    {
2840
        $runtimeCache = self::getRuntimeCache();
2841
        $cacheId = 'backend-recordLocked';
2842
        $recordLockedCache = $runtimeCache->get($cacheId);
2843
        if ($recordLockedCache !== false) {
2844
            $lockedRecords = $recordLockedCache;
2845
        } else {
2846
            $lockedRecords = [];
2847
2848
            $queryBuilder = static::getQueryBuilderForTable('sys_lockedrecords');
2849
            $result = $queryBuilder
2850
                ->select('*')
2851
                ->from('sys_lockedrecords')
2852
                ->where(
2853
                    $queryBuilder->expr()->neq(
2854
                        'sys_lockedrecords.userid',
2855
                        $queryBuilder->createNamedParameter(
2856
                            static::getBackendUserAuthentication()->user['uid'],
2857
                            \PDO::PARAM_INT
2858
                        )
2859
                    ),
2860
                    $queryBuilder->expr()->gt(
2861
                        'sys_lockedrecords.tstamp',
2862
                        $queryBuilder->createNamedParameter(
2863
                            $GLOBALS['EXEC_TIME'] - 2 * 3600,
2864
                            \PDO::PARAM_INT
2865
                        )
2866
                    )
2867
                )
2868
                ->execute();
2869
2870
            $lang = static::getLanguageService();
2871
            while ($row = $result->fetch()) {
2872
                // Get the type of the user that locked this record:
2873
                if ($row['userid']) {
2874
                    $userTypeLabel = 'beUser';
2875
                } elseif ($row['feuserid']) {
2876
                    $userTypeLabel = 'feUser';
2877
                } else {
2878
                    $userTypeLabel = 'user';
2879
                }
2880
                $userType = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.' . $userTypeLabel);
2881
                // Get the username (if available):
2882
                if ($row['username']) {
2883
                    $userName = $row['username'];
2884
                } else {
2885
                    $userName = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.unknownUser');
2886
                }
2887
                $lockedRecords[$row['record_table'] . ':' . $row['record_uid']] = $row;
2888
                $lockedRecords[$row['record_table'] . ':' . $row['record_uid']]['msg'] = sprintf(
2889
                    $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.lockedRecordUser'),
2890
                    $userType,
2891
                    $userName,
2892
                    self::calcAge(
2893
                        $GLOBALS['EXEC_TIME'] - $row['tstamp'],
2894
                        $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears')
2895
                    )
2896
                );
2897
                if ($row['record_pid'] && !isset($lockedRecords[$row['record_table'] . ':' . $row['record_pid']])) {
2898
                    $lockedRecords['pages:' . $row['record_pid']]['msg'] = sprintf(
2899
                        $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.lockedRecordUser_content'),
2900
                        $userType,
2901
                        $userName,
2902
                        self::calcAge(
2903
                            $GLOBALS['EXEC_TIME'] - $row['tstamp'],
2904
                            $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears')
2905
                        )
2906
                    );
2907
                }
2908
            }
2909
            $runtimeCache->set($cacheId, $lockedRecords);
2910
        }
2911
2912
        return $lockedRecords[$table . ':' . $uid] ?? false;
2913
    }
2914
2915
    /**
2916
     * Returns TSConfig for the TCEFORM object in Page TSconfig.
2917
     * Used in TCEFORMs
2918
     *
2919
     * @param string $table Table name present in TCA
2920
     * @param array $row Row from table
2921
     * @return array
2922
     */
2923
    public static function getTCEFORM_TSconfig($table, $row)
2924
    {
2925
        $res = [];
2926
        // Get main config for the table
2927
        [$TScID, $cPid] = self::getTSCpid($table, $row['uid'], $row['pid']);
2928
        if ($TScID >= 0) {
2929
            $tsConfig = static::getPagesTSconfig($TScID)['TCEFORM.'][$table . '.'] ?? [];
2930
            $typeVal = self::getTCAtypeValue($table, $row);
2931
            foreach ($tsConfig as $key => $val) {
2932
                if (is_array($val)) {
2933
                    $fieldN = substr($key, 0, -1);
2934
                    $res[$fieldN] = $val;
2935
                    unset($res[$fieldN]['types.']);
2936
                    if ((string)$typeVal !== '' && is_array($val['types.'][$typeVal . '.'])) {
2937
                        ArrayUtility::mergeRecursiveWithOverrule($res[$fieldN], $val['types.'][$typeVal . '.']);
2938
                    }
2939
                }
2940
            }
2941
        }
2942
        $res['_CURRENT_PID'] = $cPid;
2943
        $res['_THIS_UID'] = $row['uid'];
2944
        // So the row will be passed to foreign_table_where_query()
2945
        $res['_THIS_ROW'] = $row;
2946
        return $res;
2947
    }
2948
2949
    /**
2950
     * Find the real PID of the record (with $uid from $table).
2951
     * This MAY be impossible if the pid is set as a reference to the former record or a page (if two records are created at one time).
2952
     *
2953
     * @param string $table Table name
2954
     * @param int $uid Record uid
2955
     * @param int|string $pid Record pid, could be negative then pointing to a record from same table whose pid to find and return
2956
     * @return int|null
2957
     * @internal
2958
     * @see \TYPO3\CMS\Core\DataHandling\DataHandler::copyRecord()
2959
     * @see \TYPO3\CMS\Backend\Utility\BackendUtility::getTSCpid()
2960
     */
2961
    public static function getTSconfig_pidValue($table, $uid, $pid)
2962
    {
2963
        // If pid is an integer this takes precedence in our lookup.
2964
        if (MathUtility::canBeInterpretedAsInteger($pid)) {
2965
            $thePidValue = (int)$pid;
2966
            // If ref to another record, look that record up.
2967
            if ($thePidValue < 0) {
2968
                $pidRec = self::getRecord($table, abs($thePidValue), 'pid');
0 ignored issues
show
Bug introduced by
It seems like abs($thePidValue) can also be of type double; however, parameter $uid of TYPO3\CMS\Backend\Utilit...endUtility::getRecord() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

2968
                $pidRec = self::getRecord($table, /** @scrutinizer ignore-type */ abs($thePidValue), 'pid');
Loading history...
2969
                $thePidValue = is_array($pidRec) ? $pidRec['pid'] : -2;
2970
            }
2971
        } else {
2972
            // Try to fetch the record pid from uid. If the uid is 'NEW...' then this will of course return nothing
2973
            $rr = self::getRecord($table, $uid);
2974
            $thePidValue = null;
2975
            if (is_array($rr)) {
2976
                // First check if the pid is -1 which means it is a workspaced element. Get the "real" record:
2977
                if ($rr['pid'] == '-1') {
2978
                    $rr = self::getRecord($table, $rr['t3ver_oid'], 'pid');
2979
                    if (is_array($rr)) {
2980
                        $thePidValue = $rr['pid'];
2981
                    }
2982
                } else {
2983
                    // Returning the "pid" of the record
2984
                    $thePidValue = $rr['pid'];
2985
                }
2986
            }
2987
            if (!$thePidValue) {
2988
                // Returns -1 if the record with this pid was not found.
2989
                $thePidValue = -1;
2990
            }
2991
        }
2992
        return $thePidValue;
2993
    }
2994
2995
    /**
2996
     * Return the real pid of a record and caches the result.
2997
     * The non-cached method needs database queries to do the job, so this method
2998
     * can be used if code sometimes calls the same record multiple times to save
2999
     * some queries. This should not be done if the calling code may change the
3000
     * same record meanwhile.
3001
     *
3002
     * @param string $table Tablename
3003
     * @param string $uid UID value
3004
     * @param string $pid PID value
3005
     * @return array Array of two integers; first is the real PID of a record, second is the PID value for TSconfig.
3006
     */
3007
    public static function getTSCpidCached($table, $uid, $pid)
3008
    {
3009
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
3010
        $firstLevelCache = $runtimeCache->get('backendUtilityTscPidCached') ?: [];
3011
        $key = $table . ':' . $uid . ':' . $pid;
3012
        if (!isset($firstLevelCache[$key])) {
3013
            $firstLevelCache[$key] = static::getTSCpid($table, (int)$uid, (int)$pid);
3014
            $runtimeCache->set('backendUtilityTscPidCached', $firstLevelCache);
3015
        }
3016
        return $firstLevelCache[$key];
3017
    }
3018
3019
    /**
3020
     * Returns the REAL pid of the record, if possible. If both $uid and $pid is strings, then pid=-1 is returned as an error indication.
3021
     *
3022
     * @param string $table Table name
3023
     * @param int $uid Record uid
3024
     * @param int|string $pid Record pid
3025
     * @return array Array of two integers; first is the REAL PID of a record and if its a new record negative values are resolved to the true PID,
3026
     * second value is the PID value for TSconfig (uid if table is pages, otherwise the pid)
3027
     * @internal
3028
     * @see \TYPO3\CMS\Core\DataHandling\DataHandler::setHistory()
3029
     * @see \TYPO3\CMS\Core\DataHandling\DataHandler::process_datamap()
3030
     */
3031
    public static function getTSCpid($table, $uid, $pid)
3032
    {
3033
        // If pid is negative (referring to another record) the pid of the other record is fetched and returned.
3034
        $cPid = self::getTSconfig_pidValue($table, $uid, $pid);
3035
        // $TScID is the id of $table = pages, else it's the pid of the record.
3036
        $TScID = $table === 'pages' && MathUtility::canBeInterpretedAsInteger($uid) ? $uid : $cPid;
3037
        return [$TScID, $cPid];
3038
    }
3039
3040
    /**
3041
     * Returns soft-reference parser for the softRef processing type
3042
     * Usage: $softRefObj = BackendUtility::softRefParserObj('[parser key]');
3043
     *
3044
     * @param string $spKey softRef parser key
3045
     * @return mixed If available, returns Soft link parser object, otherwise false.
3046
     * @internal should only be used from within TYPO3 Core
3047
     */
3048
    public static function softRefParserObj($spKey)
3049
    {
3050
        $className = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser'][$spKey] ?? false;
3051
        if ($className) {
3052
            return GeneralUtility::makeInstance($className);
3053
        }
3054
        return false;
3055
    }
3056
3057
    /**
3058
     * Gets an instance of the runtime cache.
3059
     *
3060
     * @return FrontendInterface
3061
     */
3062
    protected static function getRuntimeCache()
3063
    {
3064
        return GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
3065
    }
3066
3067
    /**
3068
     * Returns array of soft parser references
3069
     *
3070
     * @param string $parserList softRef parser list
3071
     * @return array|bool Array where the parser key is the key and the value is the parameter string, FALSE if no parsers were found
3072
     * @throws \InvalidArgumentException
3073
     * @internal should only be used from within TYPO3 Core
3074
     */
3075
    public static function explodeSoftRefParserList($parserList)
3076
    {
3077
        // Return immediately if list is blank:
3078
        if ((string)$parserList === '') {
3079
            return false;
3080
        }
3081
3082
        $runtimeCache = self::getRuntimeCache();
3083
        $cacheId = 'backend-softRefList-' . md5($parserList);
3084
        $parserListCache = $runtimeCache->get($cacheId);
3085
        if ($parserListCache !== false) {
3086
            return $parserListCache;
3087
        }
3088
3089
        // Otherwise parse the list:
3090
        $keyList = GeneralUtility::trimExplode(',', $parserList, true);
3091
        $output = [];
3092
        foreach ($keyList as $val) {
3093
            $reg = [];
3094
            if (preg_match('/^([[:alnum:]_-]+)\\[(.*)\\]$/', $val, $reg)) {
3095
                $output[$reg[1]] = GeneralUtility::trimExplode(';', $reg[2], true);
3096
            } else {
3097
                $output[$val] = '';
3098
            }
3099
        }
3100
        $runtimeCache->set($cacheId, $output);
3101
        return $output;
3102
    }
3103
3104
    /**
3105
     * Returns TRUE if $modName is set and is found as a main- or submodule in $TBE_MODULES array
3106
     *
3107
     * @param string $modName Module name
3108
     * @return bool
3109
     */
3110
    public static function isModuleSetInTBE_MODULES($modName)
3111
    {
3112
        $loaded = [];
3113
        foreach ($GLOBALS['TBE_MODULES'] as $mkey => $list) {
3114
            $loaded[$mkey] = 1;
3115
            if (!is_array($list) && trim($list)) {
3116
                $subList = GeneralUtility::trimExplode(',', $list, true);
3117
                foreach ($subList as $skey) {
3118
                    $loaded[$mkey . '_' . $skey] = 1;
3119
                }
3120
            }
3121
        }
3122
        return $modName && isset($loaded[$modName]);
3123
    }
3124
3125
    /**
3126
     * Counting references to a record/file
3127
     *
3128
     * @param string $table Table name (or "_FILE" if its a file)
3129
     * @param string $ref Reference: If table, then int-uid, if _FILE, then file reference (relative to Environment::getPublicPath())
3130
     * @param string $msg Message with %s, eg. "There were %s records pointing to this file!
3131
     * @param string|int|null $count Reference count
3132
     * @return string|int Output string (or int count value if no msg string specified)
3133
     */
3134
    public static function referenceCount($table, $ref, $msg = '', $count = null)
3135
    {
3136
        if ($count === null) {
3137
3138
            // Build base query
3139
            $queryBuilder = static::getQueryBuilderForTable('sys_refindex');
3140
            $queryBuilder
3141
                ->count('*')
3142
                ->from('sys_refindex')
3143
                ->where(
3144
                    $queryBuilder->expr()->eq('ref_table', $queryBuilder->createNamedParameter($table, \PDO::PARAM_STR))
3145
                );
3146
3147
            // Look up the path:
3148
            if ($table === '_FILE') {
3149
                if (!GeneralUtility::isFirstPartOfStr($ref, Environment::getPublicPath())) {
3150
                    return '';
3151
                }
3152
3153
                $ref = PathUtility::stripPathSitePrefix($ref);
3154
                $queryBuilder->andWhere(
3155
                    $queryBuilder->expr()->eq('ref_string', $queryBuilder->createNamedParameter($ref, \PDO::PARAM_STR))
3156
                );
3157
            } else {
3158
                $queryBuilder->andWhere(
3159
                    $queryBuilder->expr()->eq('ref_uid', $queryBuilder->createNamedParameter($ref, \PDO::PARAM_INT))
3160
                );
3161
                if ($table === 'sys_file') {
3162
                    $queryBuilder->andWhere($queryBuilder->expr()->neq('tablename', $queryBuilder->quote('sys_file_metadata')));
3163
                }
3164
            }
3165
3166
            $count = $queryBuilder->execute()->fetchColumn(0);
3167
        }
3168
3169
        if ($count) {
3170
            return $msg ? sprintf($msg, $count) : $count;
3171
        }
3172
        return $msg ? '' : 0;
3173
    }
3174
3175
    /**
3176
     * Counting translations of records
3177
     *
3178
     * @param string $table Table name
3179
     * @param string $ref Reference: the record's uid
3180
     * @param string $msg Message with %s, eg. "This record has %s translation(s) which will be deleted, too!
3181
     * @return string Output string (or int count value if no msg string specified)
3182
     */
3183
    public static function translationCount($table, $ref, $msg = '')
3184
    {
3185
        $count = null;
3186
        if ($GLOBALS['TCA'][$table]['ctrl']['languageField']
3187
            && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
3188
        ) {
3189
            $queryBuilder = static::getQueryBuilderForTable($table);
3190
            $queryBuilder->getRestrictions()
3191
                ->removeAll()
3192
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
3193
3194
            $count = (int)$queryBuilder
3195
                ->count('*')
3196
                ->from($table)
3197
                ->where(
3198
                    $queryBuilder->expr()->eq(
3199
                        $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
3200
                        $queryBuilder->createNamedParameter($ref, \PDO::PARAM_INT)
3201
                    ),
3202
                    $queryBuilder->expr()->neq(
3203
                        $GLOBALS['TCA'][$table]['ctrl']['languageField'],
3204
                        $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
3205
                    )
3206
                )
3207
                ->execute()
3208
                ->fetchColumn(0);
3209
        }
3210
3211
        if ($count && $msg) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $count of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
3212
            return sprintf($msg, $count);
3213
        }
3214
3215
        if ($count) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $count of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
3216
            return $msg ? sprintf($msg, $count) : $count;
3217
        }
3218
        return $msg ? '' : 0;
3219
    }
3220
3221
    /*******************************************
3222
     *
3223
     * Workspaces / Versioning
3224
     *
3225
     *******************************************/
3226
    /**
3227
     * Select all versions of a record, ordered by latest created version (uid DESC)
3228
     *
3229
     * @param string $table Table name to select from
3230
     * @param int $uid Record uid for which to find versions.
3231
     * @param string $fields Field list to select
3232
     * @param int|null $workspace Search in workspace ID and Live WS, if 0 search only in LiveWS, if NULL search in all WS.
3233
     * @param bool $includeDeletedRecords If set, deleted-flagged versions are included! (Only for clean-up script!)
3234
     * @param array $row The current record
3235
     * @return array|null Array of versions of table/uid
3236
     * @internal should only be used from within TYPO3 Core
3237
     */
3238
    public static function selectVersionsOfRecord(
3239
        $table,
3240
        $uid,
3241
        $fields = '*',
3242
        $workspace = 0,
3243
        $includeDeletedRecords = false,
3244
        $row = null
3245
    ) {
3246
        $outputRows = [];
3247
        if (static::isTableWorkspaceEnabled($table)) {
3248
            if (is_array($row) && !$includeDeletedRecords) {
3249
                $row['_CURRENT_VERSION'] = true;
3250
                $outputRows[] = $row;
3251
            } else {
3252
                // Select UID version:
3253
                $row = self::getRecord($table, $uid, $fields, '', !$includeDeletedRecords);
3254
                // Add rows to output array:
3255
                if ($row) {
3256
                    $row['_CURRENT_VERSION'] = true;
3257
                    $outputRows[] = $row;
3258
                }
3259
            }
3260
3261
            $queryBuilder = static::getQueryBuilderForTable($table);
3262
            $queryBuilder->getRestrictions()->removeAll();
3263
3264
            // build fields to select
3265
            $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields));
3266
3267
            $queryBuilder
3268
                ->from($table)
3269
                ->where(
3270
                    $queryBuilder->expr()->neq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)),
3271
                    $queryBuilder->expr()->eq('t3ver_oid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT))
3272
                )
3273
                ->orderBy('uid', 'DESC');
3274
3275
            if (!$includeDeletedRecords) {
3276
                $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
3277
            }
3278
3279
            if ($workspace === 0) {
3280
                // Only in Live WS
3281
                $queryBuilder->andWhere(
3282
                    $queryBuilder->expr()->eq(
3283
                        't3ver_wsid',
3284
                        $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
3285
                    )
3286
                );
3287
            } elseif ($workspace !== null) {
3288
                // In Live WS and Workspace with given ID
3289
                $queryBuilder->andWhere(
3290
                    $queryBuilder->expr()->in(
3291
                        't3ver_wsid',
3292
                        $queryBuilder->createNamedParameter([0, (int)$workspace], Connection::PARAM_INT_ARRAY)
3293
                    )
3294
                );
3295
            }
3296
3297
            $rows = $queryBuilder->execute()->fetchAll();
3298
3299
            // Add rows to output array:
3300
            if (is_array($rows)) {
0 ignored issues
show
introduced by
The condition is_array($rows) is always true.
Loading history...
3301
                $outputRows = array_merge($outputRows, $rows);
3302
            }
3303
            return $outputRows;
3304
        }
3305
        return null;
3306
    }
3307
3308
    /**
3309
     * Find page-tree PID for versionized record
3310
     * Used whenever you are tracking something back, like making the root line.
3311
     * Will only translate if the workspace of the input record matches that of the current user (unless flag set)
3312
     * Principle; Record offline! => Find online?
3313
     *
3314
     * If the record had its pid corrected to the online versions pid,
3315
     * then "_ORIG_pid" is set for moved records to the PID of the moved location.
3316
     *
3317
     * @param string $table Table name
3318
     * @param array $rr Record array passed by reference. As minimum, "pid" and "uid" fields must exist! "t3ver_oid", "t3ver_state" and "t3ver_wsid" is nice and will save you a DB query.
3319
     * @param bool $ignoreWorkspaceMatch Ignore workspace match
3320
     * @see PageRepository::fixVersioningPid()
3321
     * @internal should only be used from within TYPO3 Core
3322
     * @deprecated will be removed in TYPO3 v12, use workspaceOL() or getRecordWSOL() directly to achieve the same result.
3323
     */
3324
    public static function fixVersioningPid($table, &$rr, $ignoreWorkspaceMatch = false)
3325
    {
3326
        trigger_error('BackendUtility::fixVersioningPid() will be removed in TYPO3 v12, use BackendUtility::workspaceOL() or BackendUtility::getRecordWSOL() directly.', E_USER_DEPRECATED);
3327
        if (!ExtensionManagementUtility::isLoaded('workspaces')) {
3328
            return;
3329
        }
3330
        if (!static::isTableWorkspaceEnabled($table)) {
3331
            return;
3332
        }
3333
        // Check that the input record is an offline version from a table that supports versioning
3334
        if (!is_array($rr)) {
0 ignored issues
show
introduced by
The condition is_array($rr) is always true.
Loading history...
3335
            return;
3336
        }
3337
        $incomingPid = $rr['pid'] ?? null;
3338
        // Check values for t3ver_oid and t3ver_wsid:
3339
        if (isset($rr['t3ver_oid']) && isset($rr['t3ver_wsid']) && isset($rr['t3ver_state'])) {
3340
            // If "t3ver_oid" is already a field, just set this:
3341
            $oid = $rr['t3ver_oid'];
3342
            $workspaceId = (int)$rr['t3ver_wsid'];
3343
            $versionState = (int)$rr['t3ver_state'];
3344
        } else {
3345
            $oid = 0;
3346
            $workspaceId = 0;
3347
            $versionState = 0;
3348
            // Otherwise we have to expect "uid" to be in the record and look up based on this:
3349
            $newPidRec = self::getRecord($table, $rr['uid'], 'pid,t3ver_oid,t3ver_wsid,t3ver_state');
3350
            if (is_array($newPidRec)) {
3351
                $incomingPid = $newPidRec['pid'];
3352
                $oid = $newPidRec['t3ver_oid'];
3353
                $workspaceId = $newPidRec['t3ver_wsid'];
3354
                $versionState = $newPidRec['t3ver_state'];
3355
            }
3356
        }
3357
        if ($oid && ($ignoreWorkspaceMatch || (static::getBackendUserAuthentication() instanceof BackendUserAuthentication && $workspaceId === (int)static::getBackendUserAuthentication()->workspace))) {
3358
            // Use moved PID in case of move pointer
3359
            if ($versionState === VersionState::MOVE_POINTER) {
3360
                if ($incomingPid !== null) {
3361
                    $movedPageIdInWorkspace = $incomingPid;
3362
                } else {
3363
                    $versionedMovePointer = self::getRecord($table, $rr['uid'], 'pid');
3364
                    $movedPageIdInWorkspace = $versionedMovePointer['pid'];
3365
                }
3366
                $rr['_ORIG_pid'] = $incomingPid;
3367
                $rr['pid'] = $movedPageIdInWorkspace;
3368
            }
3369
        }
3370
    }
3371
3372
    /**
3373
     * Workspace Preview Overlay.
3374
     *
3375
     * Generally ALWAYS used when records are selected based on uid or pid.
3376
     * Principle; Record online! => Find offline?
3377
     * The function MAY set $row to FALSE. This happens if a moved record is given and
3378
     * $unsetMovePointers is set to true. In other words, you should check if the input record
3379
     * is still an array afterwards when using this function.
3380
     *
3381
     * If the versioned record is a moved record the "pid" value will then contain the newly moved location
3382
     * and "ORIG_pid" will contain the live pid.
3383
     *
3384
     * @param string $table Table name
3385
     * @param array $row Record by reference. At least "uid", "pid", "t3ver_oid" and "t3ver_state" must be set. Keys not prefixed with '_' are used as field names in SQL.
3386
     * @param int $wsid Workspace ID, if not specified will use static::getBackendUserAuthentication()->workspace
3387
     * @param bool $unsetMovePointers If TRUE the function does not return a "pointer" row for moved records in a workspace
3388
     * @see fixVersioningPid()
3389
     */
3390
    public static function workspaceOL($table, &$row, $wsid = -99, $unsetMovePointers = false)
3391
    {
3392
        if (!ExtensionManagementUtility::isLoaded('workspaces') || !is_array($row) || !static::isTableWorkspaceEnabled($table)) {
3393
            return;
3394
        }
3395
3396
        // Initialize workspace ID
3397
        $wsid = (int)$wsid;
3398
        if ($wsid === -99 && static::getBackendUserAuthentication() instanceof BackendUserAuthentication) {
3399
            $wsid = (int)static::getBackendUserAuthentication()->workspace;
3400
        }
3401
        if ($wsid === 0) {
3402
            // Return early if in live workspace
3403
            return;
3404
        }
3405
3406
        // Check if input record is a moved record
3407
        $incomingRecordIsAMoveVersion = false;
3408
        if (isset($row['t3ver_oid'], $row['t3ver_state'])
3409
            && $row['t3ver_oid'] > 0
3410
            && (int)$row['t3ver_state'] === VersionState::MOVE_POINTER
3411
        ) {
3412
            // @todo: This handling needs a review, together with the 4th param $unsetMovePointers
3413
            $incomingRecordIsAMoveVersion = true;
3414
        }
3415
3416
        $wsAlt = self::getWorkspaceVersionOfRecord(
3417
            $wsid,
3418
            $table,
3419
            $row['uid'],
3420
            implode(',', static::purgeComputedPropertyNames(array_keys($row)))
3421
        );
3422
3423
        // If version was found, swap the default record with that one.
3424
        if (is_array($wsAlt)) {
3425
            // If t3ver_state is not found, then find it... (but we like best if it is here...)
3426
            if (!isset($wsAlt['t3ver_state'])) {
3427
                $stateRec = self::getRecord($table, $wsAlt['uid'], 't3ver_state');
3428
                $versionState = VersionState::cast($stateRec['t3ver_state']);
3429
            } else {
3430
                $versionState = VersionState::cast($wsAlt['t3ver_state']);
3431
            }
3432
            // Check if this is in move-state
3433
            if ($versionState->equals(VersionState::MOVE_POINTER)) {
3434
                // @todo Same problem as frontend in versionOL(). See TODO point there and todo above.
3435
                if (!$incomingRecordIsAMoveVersion && $unsetMovePointers) {
3436
                    $row = false;
3437
                    return;
3438
                }
3439
                // When a moved record is found the "PID" value contains the newly moved location
3440
                // Whereas the _ORIG_pid field contains the PID of the live version
3441
                $wsAlt['_ORIG_pid'] = $row['pid'];
3442
            }
3443
            // Swap UID
3444
            if (!$versionState->equals(VersionState::NEW_PLACEHOLDER)) {
3445
                $wsAlt['_ORIG_uid'] = $wsAlt['uid'];
3446
                $wsAlt['uid'] = $row['uid'];
3447
            }
3448
            // Backend css class:
3449
            $wsAlt['_CSSCLASS'] = 'ver-element';
3450
            // Changing input record to the workspace version alternative:
3451
            $row = $wsAlt;
3452
        }
3453
    }
3454
3455
    /**
3456
     * Select the workspace version of a record, if exists
3457
     *
3458
     * @param int $workspace Workspace ID
3459
     * @param string $table Table name to select from
3460
     * @param int $uid Record uid for which to find workspace version.
3461
     * @param string $fields Field list to select
3462
     * @return array|bool If found, return record, otherwise false
3463
     */
3464
    public static function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields = '*')
3465
    {
3466
        if (ExtensionManagementUtility::isLoaded('workspaces')) {
3467
            if ($workspace !== 0 && self::isTableWorkspaceEnabled($table)) {
3468
3469
                // Select workspace version of record:
3470
                $queryBuilder = static::getQueryBuilderForTable($table);
3471
                $queryBuilder->getRestrictions()
3472
                    ->removeAll()
3473
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
3474
3475
                // build fields to select
3476
                $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields));
3477
3478
                $row = $queryBuilder
3479
                    ->from($table)
3480
                    ->where(
3481
                        $queryBuilder->expr()->eq(
3482
                            't3ver_wsid',
3483
                            $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
3484
                        ),
3485
                        $queryBuilder->expr()->orX(
3486
                            // t3ver_state=1 does not contain a t3ver_oid, and returns itself
3487
                            $queryBuilder->expr()->andX(
3488
                                $queryBuilder->expr()->eq(
3489
                                    'uid',
3490
                                    $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
3491
                                ),
3492
                                $queryBuilder->expr()->eq(
3493
                                    't3ver_state',
3494
                                    $queryBuilder->createNamedParameter(VersionState::NEW_PLACEHOLDER, \PDO::PARAM_INT)
3495
                                )
3496
                            ),
3497
                            $queryBuilder->expr()->eq(
3498
                                't3ver_oid',
3499
                                $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
3500
                            )
3501
                        )
3502
                    )
3503
                    ->execute()
3504
                    ->fetch();
3505
3506
                return $row;
3507
            }
3508
        }
3509
        return false;
3510
    }
3511
3512
    /**
3513
     * Returns live version of record
3514
     *
3515
     * @param string $table Table name
3516
     * @param int $uid Record UID of draft, offline version
3517
     * @param string $fields Field list, default is *
3518
     * @return array|null If found, the record, otherwise NULL
3519
     */
3520
    public static function getLiveVersionOfRecord($table, $uid, $fields = '*')
3521
    {
3522
        $liveVersionId = self::getLiveVersionIdOfRecord($table, $uid);
3523
        if ($liveVersionId !== null) {
3524
            return self::getRecord($table, $liveVersionId, $fields);
3525
        }
3526
        return null;
3527
    }
3528
3529
    /**
3530
     * Gets the id of the live version of a record.
3531
     *
3532
     * @param string $table Name of the table
3533
     * @param int $uid Uid of the offline/draft record
3534
     * @return int|null The id of the live version of the record (or NULL if nothing was found)
3535
     * @internal should only be used from within TYPO3 Core
3536
     */
3537
    public static function getLiveVersionIdOfRecord($table, $uid)
3538
    {
3539
        if (!ExtensionManagementUtility::isLoaded('workspaces')) {
3540
            return null;
3541
        }
3542
        $liveVersionId = null;
3543
        if (self::isTableWorkspaceEnabled($table)) {
3544
            $currentRecord = self::getRecord($table, $uid, 'pid,t3ver_oid,t3ver_state');
3545
            if (is_array($currentRecord)) {
3546
                if ((int)$currentRecord['t3ver_oid'] > 0) {
3547
                    $liveVersionId = $currentRecord['t3ver_oid'];
3548
                } elseif ((int)($currentRecord['t3ver_state']) === VersionState::NEW_PLACEHOLDER) {
3549
                    // New versions do not have a live counterpart
3550
                    $liveVersionId = (int)$uid;
3551
                }
3552
            }
3553
        }
3554
        return $liveVersionId;
3555
    }
3556
3557
    /**
3558
     * Performs mapping of new uids to new versions UID in case of import inside a workspace.
3559
     *
3560
     * @param string $table Table name
3561
     * @param int $uid Record uid (of live record placeholder)
3562
     * @return int Uid of offline version if any, otherwise live uid.
3563
     * @internal should only be used from within TYPO3 Core
3564
     */
3565
    public static function wsMapId($table, $uid)
3566
    {
3567
        $wsRec = null;
3568
        if (static::getBackendUserAuthentication() instanceof BackendUserAuthentication) {
3569
            $wsRec = self::getWorkspaceVersionOfRecord(
3570
                static::getBackendUserAuthentication()->workspace,
3571
                $table,
3572
                $uid,
3573
                'uid'
3574
            );
3575
        }
3576
        return is_array($wsRec) ? $wsRec['uid'] : $uid;
3577
    }
3578
3579
    /*******************************************
3580
     *
3581
     * Miscellaneous
3582
     *
3583
     *******************************************/
3584
3585
    /**
3586
     * Creates ADMCMD parameters for the "viewpage" extension / frontend
3587
     *
3588
     * @param array $pageInfo Page record
3589
     * @param \TYPO3\CMS\Core\Context\Context $context
3590
     * @return string Query-parameters
3591
     * @internal
3592
     */
3593
    public static function ADMCMD_previewCmds($pageInfo, Context $context)
3594
    {
3595
        $simUser = '';
3596
        $simTime = '';
3597
        if (($pageInfo['fe_group'] ?? 0) > 0) {
3598
            $simUser = '&ADMCMD_simUser=' . $pageInfo['fe_group'];
3599
        } elseif ((int)($pageInfo['fe_group'] ?? 0) === -2) {
3600
            // -2 means "show at any login". We simulate first available fe_group.
3601
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
3602
                ->getQueryBuilderForTable('fe_groups');
3603
            $queryBuilder->getRestrictions()
3604
                ->removeAll()
3605
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
3606
                ->add(GeneralUtility::makeInstance(HiddenRestriction::class));
3607
3608
            $activeFeGroupRow = $queryBuilder->select('uid')
3609
                ->from('fe_groups')
3610
                ->execute()
3611
                ->fetch();
3612
3613
            if (!empty($activeFeGroupRow)) {
3614
                $simUser = '&ADMCMD_simUser=' . $activeFeGroupRow['uid'];
3615
            }
3616
        }
3617
        $startTime = (int)($pageInfo['starttime'] ?? 0);
3618
        $endTime = (int)($pageInfo['endtime'] ?? 0);
3619
        if ($startTime > $GLOBALS['EXEC_TIME']) {
3620
            // simulate access time to ensure PageRepository will find the page and in turn PageRouter will generate
3621
            // an URL for it
3622
            $dateAspect = GeneralUtility::makeInstance(DateTimeAspect::class, new \DateTimeImmutable('@' . $startTime));
3623
            $context->setAspect('date', $dateAspect);
3624
            $simTime = '&ADMCMD_simTime=' . $startTime;
3625
        }
3626
        if ($endTime < $GLOBALS['EXEC_TIME'] && $endTime !== 0) {
3627
            // Set access time to page's endtime subtracted one second to ensure PageRepository will find the page and
3628
            // in turn PageRouter will generate an URL for it
3629
            $dateAspect = GeneralUtility::makeInstance(
3630
                DateTimeAspect::class,
3631
                new \DateTimeImmutable('@' . ($endTime - 1))
3632
            );
3633
            $context->setAspect('date', $dateAspect);
3634
            $simTime = '&ADMCMD_simTime=' . ($endTime - 1);
3635
        }
3636
        return $simUser . $simTime;
3637
    }
3638
3639
    /**
3640
     * Determines whether a table is enabled for workspaces.
3641
     *
3642
     * @param string $table Name of the table to be checked
3643
     * @return bool
3644
     */
3645
    public static function isTableWorkspaceEnabled($table)
3646
    {
3647
        return !empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS']);
3648
    }
3649
3650
    /**
3651
     * Gets the TCA configuration of a field.
3652
     *
3653
     * @param string $table Name of the table
3654
     * @param string $field Name of the field
3655
     * @return array
3656
     */
3657
    public static function getTcaFieldConfiguration($table, $field)
3658
    {
3659
        $configuration = [];
3660
        if (isset($GLOBALS['TCA'][$table]['columns'][$field]['config'])) {
3661
            $configuration = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
3662
        }
3663
        return $configuration;
3664
    }
3665
3666
    /**
3667
     * Whether to ignore restrictions on a web-mount of a table.
3668
     * The regular behaviour is that records to be accessed need to be
3669
     * in a valid user's web-mount.
3670
     *
3671
     * @param string $table Name of the table
3672
     * @return bool
3673
     */
3674
    public static function isWebMountRestrictionIgnored($table)
3675
    {
3676
        return !empty($GLOBALS['TCA'][$table]['ctrl']['security']['ignoreWebMountRestriction']);
3677
    }
3678
3679
    /**
3680
     * Whether to ignore restrictions on root-level records.
3681
     * The regular behaviour is that records on the root-level (page-id 0)
3682
     * only can be accessed by admin users.
3683
     *
3684
     * @param string $table Name of the table
3685
     * @return bool
3686
     */
3687
    public static function isRootLevelRestrictionIgnored($table)
3688
    {
3689
        return !empty($GLOBALS['TCA'][$table]['ctrl']['security']['ignoreRootLevelRestriction']);
3690
    }
3691
3692
    /**
3693
     * @param string $table
3694
     * @return Connection
3695
     */
3696
    protected static function getConnectionForTable($table)
3697
    {
3698
        return GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
3699
    }
3700
3701
    /**
3702
     * @param string $table
3703
     * @return QueryBuilder
3704
     */
3705
    protected static function getQueryBuilderForTable($table)
3706
    {
3707
        return GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
3708
    }
3709
3710
    /**
3711
     * @return LoggerInterface
3712
     */
3713
    protected static function getLogger()
3714
    {
3715
        return GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);
3716
    }
3717
3718
    /**
3719
     * @return LanguageService
3720
     */
3721
    protected static function getLanguageService()
3722
    {
3723
        return $GLOBALS['LANG'];
3724
    }
3725
3726
    /**
3727
     * @return BackendUserAuthentication|null
3728
     */
3729
    protected static function getBackendUserAuthentication()
3730
    {
3731
        return $GLOBALS['BE_USER'] ?? null;
3732
    }
3733
}
3734