Completed
Push — master ( 5c0aff...3e860e )
by
unknown
19:38
created

BackendUtility::thumbCode()   B

Complexity

Conditions 11
Paths 4

Size

Total Lines 80
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 48
c 1
b 0
f 0
nc 4
nop 10
dl 0
loc 80
rs 7.3166

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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\Log\LoggerInterface;
19
use TYPO3\CMS\Backend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
20
use TYPO3\CMS\Backend\Controller\File\ThumbnailController;
21
use TYPO3\CMS\Backend\Routing\UriBuilder;
22
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
23
use TYPO3\CMS\Core\Cache\CacheManager;
24
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
25
use TYPO3\CMS\Core\Configuration\Loader\PageTsConfigLoader;
26
use TYPO3\CMS\Core\Configuration\Parser\PageTsConfigParser;
27
use TYPO3\CMS\Core\Context\Context;
28
use TYPO3\CMS\Core\Context\DateTimeAspect;
29
use TYPO3\CMS\Core\Core\Environment;
30
use TYPO3\CMS\Core\Database\Connection;
31
use TYPO3\CMS\Core\Database\ConnectionPool;
32
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
33
use TYPO3\CMS\Core\Database\Query\QueryHelper;
34
use TYPO3\CMS\Core\Database\Query\Restriction\BackendWorkspaceRestriction;
35
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
36
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
37
use TYPO3\CMS\Core\Database\RelationHandler;
38
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
39
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
40
use TYPO3\CMS\Core\Imaging\Icon;
41
use TYPO3\CMS\Core\Imaging\IconFactory;
42
use TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection;
43
use TYPO3\CMS\Core\Localization\LanguageService;
44
use TYPO3\CMS\Core\Log\LogManager;
45
use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;
46
use TYPO3\CMS\Core\Resource\ProcessedFile;
47
use TYPO3\CMS\Core\Resource\ResourceFactory;
48
use TYPO3\CMS\Core\Routing\InvalidRouteArgumentsException;
49
use TYPO3\CMS\Core\Routing\RouterInterface;
50
use TYPO3\CMS\Core\Routing\UnableToLinkToPageException;
51
use TYPO3\CMS\Core\Site\SiteFinder;
52
use TYPO3\CMS\Core\Type\Bitmask\Permission;
53
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
54
use TYPO3\CMS\Core\Utility\ArrayUtility;
55
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
56
use TYPO3\CMS\Core\Utility\GeneralUtility;
57
use TYPO3\CMS\Core\Utility\HttpUtility;
58
use TYPO3\CMS\Core\Utility\MathUtility;
59
use TYPO3\CMS\Core\Utility\PathUtility;
60
use TYPO3\CMS\Core\Versioning\VersionState;
61
62
/**
63
 * Standard functions available for the TYPO3 backend.
64
 * You are encouraged to use this class in your own applications (Backend Modules)
65
 * Don't instantiate - call functions with "\TYPO3\CMS\Backend\Utility\BackendUtility::" prefixed the function name.
66
 *
67
 * Call ALL methods without making an object!
68
 * Eg. to get a page-record 51 do this: '\TYPO3\CMS\Backend\Utility\BackendUtility::getRecord('pages',51)'
69
 */
70
class BackendUtility
71
{
72
    /*******************************************
73
     *
74
     * SQL-related, selecting records, searching
75
     *
76
     *******************************************/
77
    /**
78
     * Gets record with uid = $uid from $table
79
     * You can set $field to a list of fields (default is '*')
80
     * Additional WHERE clauses can be added by $where (fx. ' AND some_field = 1')
81
     * Will automatically check if records has been deleted and if so, not return anything.
82
     * $table must be found in $GLOBALS['TCA']
83
     *
84
     * @param string $table Table name present in $GLOBALS['TCA']
85
     * @param int $uid UID of record
86
     * @param string $fields List of fields to select
87
     * @param string $where Additional WHERE clause, eg. ' AND some_field = 0'
88
     * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
89
     * @return array|null Returns the row if found, otherwise NULL
90
     */
91
    public static function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = true)
92
    {
93
        // Ensure we have a valid uid (not 0 and not NEWxxxx) and a valid TCA
94
        if ((int)$uid && !empty($GLOBALS['TCA'][$table])) {
95
            $queryBuilder = static::getQueryBuilderForTable($table);
96
97
            // do not use enabled fields here
98
            $queryBuilder->getRestrictions()->removeAll();
99
100
            // should the delete clause be used
101
            if ($useDeleteClause) {
102
                $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
103
            }
104
105
            // set table and where clause
106
            $queryBuilder
107
                ->select(...GeneralUtility::trimExplode(',', $fields, true))
108
                ->from($table)
109
                ->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter((int)$uid, \PDO::PARAM_INT)));
110
111
            // add custom where clause
112
            if ($where) {
113
                $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($where));
114
            }
115
116
            $row = $queryBuilder->execute()->fetch();
117
            if ($row) {
118
                return $row;
119
            }
120
        }
121
        return null;
122
    }
123
124
    /**
125
     * Like getRecord(), but overlays workspace version if any.
126
     *
127
     * @param string $table Table name present in $GLOBALS['TCA']
128
     * @param int $uid UID of record
129
     * @param string $fields List of fields to select
130
     * @param string $where Additional WHERE clause, eg. ' AND some_field = 0'
131
     * @param bool $useDeleteClause Use the deleteClause to check if a record is deleted (default TRUE)
132
     * @param bool $unsetMovePointers If TRUE the function does not return a "pointer" row for moved records in a workspace
133
     * @return array Returns the row if found, otherwise nothing
134
     */
135
    public static function getRecordWSOL(
136
        $table,
137
        $uid,
138
        $fields = '*',
139
        $where = '',
140
        $useDeleteClause = true,
141
        $unsetMovePointers = false
142
    ) {
143
        if ($fields !== '*') {
144
            $internalFields = GeneralUtility::uniqueList($fields . ',uid,pid');
145
            $row = self::getRecord($table, $uid, $internalFields, $where, $useDeleteClause);
146
            self::workspaceOL($table, $row, -99, $unsetMovePointers);
147
            if (is_array($row)) {
148
                foreach ($row as $key => $_) {
149
                    if (!GeneralUtility::inList($fields, $key) && $key[0] !== '_') {
150
                        unset($row[$key]);
151
                    }
152
                }
153
            }
154
        } else {
155
            $row = self::getRecord($table, $uid, $fields, $where, $useDeleteClause);
156
            self::workspaceOL($table, $row, -99, $unsetMovePointers);
157
        }
158
        return $row;
159
    }
160
161
    /**
162
     * Purges computed properties starting with underscore character ('_').
163
     *
164
     * @param array $record
165
     * @return array
166
     * @internal should only be used from within TYPO3 Core
167
     */
168
    public static function purgeComputedPropertiesFromRecord(array $record): array
169
    {
170
        return array_filter(
171
            $record,
172
            function (string $propertyName): bool {
173
                return $propertyName[0] !== '_';
174
            },
175
            ARRAY_FILTER_USE_KEY
176
        );
177
    }
178
179
    /**
180
     * Purges computed property names starting with underscore character ('_').
181
     *
182
     * @param array $propertyNames
183
     * @return array
184
     * @internal should only be used from within TYPO3 Core
185
     */
186
    public static function purgeComputedPropertyNames(array $propertyNames): array
187
    {
188
        return array_filter(
189
            $propertyNames,
190
            function (string $propertyName): bool {
191
                return $propertyName[0] !== '_';
192
            }
193
        );
194
    }
195
196
    /**
197
     * Makes a backwards explode on the $str and returns an array with ($table, $uid).
198
     * Example: tt_content_45 => ['tt_content', 45]
199
     *
200
     * @param string $str [tablename]_[uid] string to explode
201
     * @return array
202
     * @internal should only be used from within TYPO3 Core
203
     */
204
    public static function splitTable_Uid($str)
205
    {
206
        [$uid, $table] = explode('_', strrev($str), 2);
207
        return [strrev($table), strrev($uid)];
208
    }
209
210
    /**
211
     * Backend implementation of enableFields()
212
     * Notice that "fe_groups" is not selected for - only disabled, starttime and endtime.
213
     * Notice that deleted-fields are NOT filtered - you must ALSO call deleteClause in addition.
214
     * $GLOBALS["SIM_ACCESS_TIME"] is used for date.
215
     *
216
     * @param string $table The table from which to return enableFields WHERE clause. Table name must have a 'ctrl' section in $GLOBALS['TCA'].
217
     * @param bool $inv Means that the query will select all records NOT VISIBLE records (inverted selection)
218
     * @return string WHERE clause part
219
     * @internal should only be used from within TYPO3 Core, but DefaultRestrictionHandler is recommended as alternative
220
     */
221
    public static function BEenableFields($table, $inv = false)
222
    {
223
        $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
224
        $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
225
            ->getConnectionForTable($table)
226
            ->getExpressionBuilder();
227
        $query = $expressionBuilder->andX();
228
        $invQuery = $expressionBuilder->orX();
229
230
        if (is_array($ctrl)) {
231
            if (is_array($ctrl['enablecolumns'])) {
232
                if ($ctrl['enablecolumns']['disabled'] ?? false) {
233
                    $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
234
                    $query->add($expressionBuilder->eq($field, 0));
235
                    $invQuery->add($expressionBuilder->neq($field, 0));
236
                }
237
                if ($ctrl['enablecolumns']['starttime'] ?? false) {
238
                    $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
239
                    $query->add($expressionBuilder->lte($field, (int)$GLOBALS['SIM_ACCESS_TIME']));
240
                    $invQuery->add(
241
                        $expressionBuilder->andX(
242
                            $expressionBuilder->neq($field, 0),
243
                            $expressionBuilder->gt($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
244
                        )
245
                    );
246
                }
247
                if ($ctrl['enablecolumns']['endtime'] ?? false) {
248
                    $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
249
                    $query->add(
250
                        $expressionBuilder->orX(
251
                            $expressionBuilder->eq($field, 0),
252
                            $expressionBuilder->gt($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
253
                        )
254
                    );
255
                    $invQuery->add(
256
                        $expressionBuilder->andX(
257
                            $expressionBuilder->neq($field, 0),
258
                            $expressionBuilder->lte($field, (int)$GLOBALS['SIM_ACCESS_TIME'])
259
                        )
260
                    );
261
                }
262
            }
263
        }
264
265
        if ($query->count() === 0) {
266
            return '';
267
        }
268
269
        return ' AND ' . ($inv ? $invQuery : $query);
270
    }
271
272
    /**
273
     * Fetches the localization for a given record.
274
     *
275
     * @param string $table Table name present in $GLOBALS['TCA']
276
     * @param int $uid The uid of the record
277
     * @param int $language The uid of the language record in sys_language
278
     * @param string $andWhereClause Optional additional WHERE clause (default: '')
279
     * @return mixed Multidimensional array with selected records, empty array if none exists and FALSE if table is not localizable
280
     */
281
    public static function getRecordLocalization($table, $uid, $language, $andWhereClause = '')
282
    {
283
        $recordLocalization = false;
284
285
        if (self::isTableLocalizable($table)) {
286
            $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
287
288
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
289
                ->getQueryBuilderForTable($table);
290
            $queryBuilder->getRestrictions()
291
                ->removeAll()
292
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
293
                ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
294
295
            $queryBuilder->select('*')
296
                ->from($table)
297
                ->where(
298
                    $queryBuilder->expr()->eq(
299
                        $tcaCtrl['translationSource'] ?? $tcaCtrl['transOrigPointerField'],
300
                        $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
301
                    ),
302
                    $queryBuilder->expr()->eq(
303
                        $tcaCtrl['languageField'],
304
                        $queryBuilder->createNamedParameter((int)$language, \PDO::PARAM_INT)
305
                    )
306
                )
307
                ->setMaxResults(1);
308
309
            if ($andWhereClause) {
310
                $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($andWhereClause));
311
            }
312
313
            $recordLocalization = $queryBuilder->execute()->fetchAll();
314
        }
315
316
        return $recordLocalization;
317
    }
318
319
    /*******************************************
320
     *
321
     * Page tree, TCA related
322
     *
323
     *******************************************/
324
    /**
325
     * Returns what is called the 'RootLine'. That is an array with information about the page records from a page id
326
     * ($uid) and back to the root.
327
     * By default deleted pages are filtered.
328
     * This RootLine will follow the tree all the way to the root. This is opposite to another kind of root line known
329
     * from the frontend where the rootline stops when a root-template is found.
330
     *
331
     * @param int $uid Page id for which to create the root line.
332
     * @param string $clause Clause can be used to select other criteria. It would typically be where-clauses that
333
     *          stops the process if we meet a page, the user has no reading access to.
334
     * @param bool $workspaceOL If TRUE, version overlay is applied. This must be requested specifically because it is
335
     *          usually only wanted when the rootline is used for visual output while for permission checking you want the raw thing!
336
     * @param string[] $additionalFields Additional Fields to select for rootline records
337
     * @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
338
     */
339
    public static function BEgetRootLine($uid, $clause = '', $workspaceOL = false, array $additionalFields = [])
340
    {
341
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
342
        $beGetRootLineCache = $runtimeCache->get('backendUtilityBeGetRootLine') ?: [];
343
        $output = [];
344
        $pid = $uid;
345
        $ident = $pid . '-' . $clause . '-' . $workspaceOL . ($additionalFields ? '-' . md5(implode(',', $additionalFields)) : '');
346
        if (is_array($beGetRootLineCache[$ident] ?? false)) {
347
            $output = $beGetRootLineCache[$ident];
348
        } else {
349
            $loopCheck = 100;
350
            $theRowArray = [];
351
            while ($uid != 0 && $loopCheck) {
352
                $loopCheck--;
353
                $row = self::getPageForRootline($uid, $clause, $workspaceOL, $additionalFields);
354
                if (is_array($row)) {
355
                    $uid = $row['pid'];
356
                    $theRowArray[] = $row;
357
                } else {
358
                    break;
359
                }
360
            }
361
            $fields = [
362
                'uid',
363
                'pid',
364
                'title',
365
                'doktype',
366
                'slug',
367
                'tsconfig_includes',
368
                'TSconfig',
369
                'is_siteroot',
370
                't3ver_oid',
371
                't3ver_wsid',
372
                't3ver_state',
373
                't3ver_stage',
374
                'backend_layout_next_level',
375
                'hidden',
376
                'starttime',
377
                'endtime',
378
                'fe_group',
379
                'nav_hide',
380
                'content_from_pid',
381
                'module',
382
                'extendToSubpages'
383
            ];
384
            $fields = array_merge($fields, $additionalFields);
385
            $rootPage = array_fill_keys($fields, null);
386
            if ($uid == 0) {
387
                $rootPage['uid'] = 0;
388
                $theRowArray[] = $rootPage;
389
            }
390
            $c = count($theRowArray);
391
            foreach ($theRowArray as $val) {
392
                $c--;
393
                $output[$c] = array_intersect_key($val, $rootPage);
394
                if (isset($val['_ORIG_pid'])) {
395
                    $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
396
                }
397
            }
398
            $beGetRootLineCache[$ident] = $output;
399
            $runtimeCache->set('backendUtilityBeGetRootLine', $beGetRootLineCache);
400
        }
401
        return $output;
402
    }
403
404
    /**
405
     * Gets the cached page record for the rootline
406
     *
407
     * @param int $uid Page id for which to create the root line.
408
     * @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.
409
     * @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!
410
     * @param string[] $additionalFields AdditionalFields to fetch from the root line
411
     * @return array Cached page record for the rootline
412
     * @see BEgetRootLine
413
     */
414
    protected static function getPageForRootline($uid, $clause, $workspaceOL, array $additionalFields = [])
415
    {
416
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
417
        $pageForRootlineCache = $runtimeCache->get('backendUtilityPageForRootLine') ?: [];
418
        $statementCacheIdent = md5($clause . ($additionalFields ? '-' . implode(',', $additionalFields) : ''));
419
        $ident = $uid . '-' . $workspaceOL . '-' . $statementCacheIdent;
420
        if (is_array($pageForRootlineCache[$ident] ?? false)) {
421
            $row = $pageForRootlineCache[$ident];
422
        } else {
423
            $statement = $runtimeCache->get('getPageForRootlineStatement-' . $statementCacheIdent);
424
            if (!$statement) {
425
                $queryBuilder = static::getQueryBuilderForTable('pages');
426
                $queryBuilder->getRestrictions()
427
                             ->removeAll()
428
                             ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
429
430
                $queryBuilder
431
                    ->select(
432
                        'pid',
433
                        'uid',
434
                        'title',
435
                        'doktype',
436
                        'slug',
437
                        'tsconfig_includes',
438
                        'TSconfig',
439
                        'is_siteroot',
440
                        't3ver_oid',
441
                        't3ver_wsid',
442
                        't3ver_state',
443
                        't3ver_stage',
444
                        'backend_layout_next_level',
445
                        'hidden',
446
                        'starttime',
447
                        'endtime',
448
                        'fe_group',
449
                        'nav_hide',
450
                        'content_from_pid',
451
                        'module',
452
                        'extendToSubpages',
453
                        ...$additionalFields
454
                    )
455
                    ->from('pages')
456
                    ->where(
457
                        $queryBuilder->expr()->eq('uid', $queryBuilder->createPositionalParameter($uid, \PDO::PARAM_INT)),
458
                        QueryHelper::stripLogicalOperatorPrefix($clause)
459
                    );
460
                $statement = $queryBuilder->execute();
461
                $runtimeCache->set('getPageForRootlineStatement-' . $statementCacheIdent, $statement);
462
            } else {
463
                $statement->bindValue(1, (int)$uid);
464
                $statement->execute();
465
            }
466
            $row = $statement->fetch();
467
            $statement->closeCursor();
468
469
            if ($row) {
470
                $newLocation = false;
471
                if ($workspaceOL) {
472
                    self::workspaceOL('pages', $row);
473
                    if (is_array($row) && (int)$row['t3ver_state'] === VersionState::MOVE_POINTER) {
474
                        $newLocation = self::getMovePlaceholder('pages', $row['uid'], 'pid');
475
                    }
476
                }
477
                if (is_array($row)) {
478
                    if ($newLocation !== false) {
479
                        $row['pid'] = $newLocation['pid'];
480
                    } else {
481
                        self::fixVersioningPid('pages', $row);
482
                    }
483
                    $pageForRootlineCache[$ident] = $row;
484
                    $runtimeCache->set('backendUtilityPageForRootLine', $pageForRootlineCache);
485
                }
486
            }
487
        }
488
        return $row;
489
    }
490
491
    /**
492
     * Opens the page tree to the specified page id
493
     *
494
     * @param int $pid Page id.
495
     * @param bool $clearExpansion If set, then other open branches are closed.
496
     * @internal should only be used from within TYPO3 Core
497
     */
498
    public static function openPageTree($pid, $clearExpansion)
499
    {
500
        $beUser = static::getBackendUserAuthentication();
501
        // Get current expansion data:
502
        if ($clearExpansion) {
503
            $expandedPages = [];
504
        } else {
505
            $expandedPages = json_decode($beUser->uc['browseTrees']['browsePages'], true);
506
        }
507
        // Get rootline:
508
        $rL = self::BEgetRootLine($pid);
509
        // First, find out what mount index to use (if more than one DB mount exists):
510
        $mountIndex = 0;
511
        $mountKeys = array_flip($beUser->returnWebmounts());
512
        foreach ($rL as $rLDat) {
513
            if (isset($mountKeys[$rLDat['uid']])) {
514
                $mountIndex = $mountKeys[$rLDat['uid']];
515
                break;
516
            }
517
        }
518
        // Traverse rootline and open paths:
519
        foreach ($rL as $rLDat) {
520
            $expandedPages[$mountIndex][$rLDat['uid']] = 1;
521
        }
522
        // Write back:
523
        $beUser->uc['browseTrees']['browsePages'] = json_encode($expandedPages);
524
        $beUser->writeUC();
525
    }
526
527
    /**
528
     * Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"
529
     * Each part of the path will be limited to $titleLimit characters
530
     * Deleted pages are filtered out.
531
     *
532
     * @param int $uid Page uid for which to create record path
533
     * @param string $clause Clause is additional where clauses, eg.
534
     * @param int $titleLimit Title limit
535
     * @param int $fullTitleLimit Title limit of Full title (typ. set to 1000 or so)
536
     * @return mixed Path of record (string) OR array with short/long title if $fullTitleLimit is set.
537
     */
538
    public static function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0)
539
    {
540
        if (!$titleLimit) {
541
            $titleLimit = 1000;
542
        }
543
        $output = $fullOutput = '/';
544
        $clause = trim($clause);
545
        if ($clause !== '' && strpos($clause, 'AND') !== 0) {
546
            $clause = 'AND ' . $clause;
547
        }
548
        $data = self::BEgetRootLine($uid, $clause, true);
549
        foreach ($data as $record) {
550
            if ($record['uid'] === 0) {
551
                continue;
552
            }
553
            $output = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $titleLimit) . $output;
554
            if ($fullTitleLimit) {
555
                $fullOutput = '/' . GeneralUtility::fixed_lgd_cs(strip_tags($record['title']), $fullTitleLimit) . $fullOutput;
556
            }
557
        }
558
        if ($fullTitleLimit) {
559
            return [$output, $fullOutput];
560
        }
561
        return $output;
562
    }
563
564
    /**
565
     * Determines whether a table is localizable and has the languageField and transOrigPointerField set in $GLOBALS['TCA'].
566
     *
567
     * @param string $table The table to check
568
     * @return bool Whether a table is localizable
569
     */
570
    public static function isTableLocalizable($table)
571
    {
572
        $isLocalizable = false;
573
        if (isset($GLOBALS['TCA'][$table]['ctrl']) && is_array($GLOBALS['TCA'][$table]['ctrl'])) {
574
            $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
575
            $isLocalizable = isset($tcaCtrl['languageField']) && $tcaCtrl['languageField'] && isset($tcaCtrl['transOrigPointerField']) && $tcaCtrl['transOrigPointerField'];
576
        }
577
        return $isLocalizable;
578
    }
579
580
    /**
581
     * 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.
582
     * If $id is zero a pseudo root-page with "_thePath" set is returned IF the current BE_USER is admin.
583
     * In any case ->isInWebMount must return TRUE for the user (regardless of $perms_clause)
584
     *
585
     * @param int $id Page uid for which to check read-access
586
     * @param string $perms_clause This is typically a value generated with static::getBackendUserAuthentication()->getPagePermsClause(1);
587
     * @return array|bool Returns page record if OK, otherwise FALSE.
588
     */
589
    public static function readPageAccess($id, $perms_clause)
590
    {
591
        if ((string)$id !== '') {
592
            $id = (int)$id;
593
            if (!$id) {
594
                if (static::getBackendUserAuthentication()->isAdmin()) {
595
                    return ['_thePath' => '/'];
596
                }
597
            } else {
598
                $pageinfo = self::getRecord('pages', $id, '*', $perms_clause);
599
                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...
600
                    self::workspaceOL('pages', $pageinfo);
601
                    if (is_array($pageinfo)) {
602
                        self::fixVersioningPid('pages', $pageinfo);
603
                        [$pageinfo['_thePath'], $pageinfo['_thePathFull']] = self::getRecordPath((int)$pageinfo['uid'], $perms_clause, 15, 1000);
604
                        return $pageinfo;
605
                    }
606
                }
607
            }
608
        }
609
        return false;
610
    }
611
612
    /**
613
     * Returns the "type" value of $rec from $table which can be used to look up the correct "types" rendering section in $GLOBALS['TCA']
614
     * If no "type" field is configured in the "ctrl"-section of the $GLOBALS['TCA'] for the table, zero is used.
615
     * 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)
616
     *
617
     * Note: This method is very similar to the type determination of FormDataProvider/DatabaseRecordTypeValue,
618
     * however, it has two differences:
619
     * 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).
620
     * 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"
621
     * and "group" field values are stored, which makes different processing of the "foreign pointer field" type field variant necessary.
622
     *
623
     * @param string $table Table name present in TCA
624
     * @param array $row Record from $table
625
     * @throws \RuntimeException
626
     * @return string Field value
627
     */
628
    public static function getTCAtypeValue($table, $row)
629
    {
630
        $typeNum = 0;
631
        if ($GLOBALS['TCA'][$table]) {
632
            $field = $GLOBALS['TCA'][$table]['ctrl']['type'];
633
            if (strpos($field, ':') !== false) {
634
                [$pointerField, $foreignTableTypeField] = explode(':', $field);
635
                // Get field value from database if field is not in the $row array
636
                if (!isset($row[$pointerField])) {
637
                    $localRow = self::getRecord($table, $row['uid'], $pointerField);
638
                    $foreignUid = $localRow[$pointerField];
639
                } else {
640
                    $foreignUid = $row[$pointerField];
641
                }
642
                if ($foreignUid) {
643
                    $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$pointerField]['config'];
644
                    $relationType = $fieldConfig['type'];
645
                    if ($relationType === 'select') {
646
                        $foreignTable = $fieldConfig['foreign_table'];
647
                    } elseif ($relationType === 'group') {
648
                        $allowedTables = explode(',', $fieldConfig['allowed']);
649
                        $foreignTable = $allowedTables[0];
650
                    } else {
651
                        throw new \RuntimeException(
652
                            'TCA foreign field pointer fields are only allowed to be used with group or select field types.',
653
                            1325862240
654
                        );
655
                    }
656
                    $foreignRow = self::getRecord($foreignTable, $foreignUid, $foreignTableTypeField);
657
                    if ($foreignRow[$foreignTableTypeField]) {
658
                        $typeNum = $foreignRow[$foreignTableTypeField];
659
                    }
660
                }
661
            } else {
662
                $typeNum = $row[$field];
663
            }
664
            // If that value is an empty string, set it to "0" (zero)
665
            if (empty($typeNum)) {
666
                $typeNum = 0;
667
            }
668
        }
669
        // If current typeNum doesn't exist, set it to 0 (or to 1 for historical reasons, if 0 doesn't exist)
670
        if (!isset($GLOBALS['TCA'][$table]['types'][$typeNum]) || !$GLOBALS['TCA'][$table]['types'][$typeNum]) {
671
            $typeNum = isset($GLOBALS['TCA'][$table]['types']['0']) ? 0 : 1;
672
        }
673
        // Force to string. Necessary for eg '-1' to be recognized as a type value.
674
        $typeNum = (string)$typeNum;
675
        return $typeNum;
676
    }
677
678
    /*******************************************
679
     *
680
     * TypoScript related
681
     *
682
     *******************************************/
683
    /**
684
     * Returns the Page TSconfig for page with id, $id
685
     *
686
     * @param int $id Page uid for which to create Page TSconfig
687
     * @return array Page TSconfig
688
     * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
689
     */
690
    public static function getPagesTSconfig($id)
691
    {
692
        $id = (int)$id;
693
694
        $cache = self::getRuntimeCache();
695
        $pagesTsConfigIdToHash = $cache->get('pagesTsConfigIdToHash' . $id);
696
        if ($pagesTsConfigIdToHash !== false) {
697
            return $cache->get('pagesTsConfigHashToContent' . $pagesTsConfigIdToHash);
698
        }
699
700
        $rootLine = self::BEgetRootLine($id, '', true);
701
        // Order correctly
702
        ksort($rootLine);
703
704
        try {
705
            $site = GeneralUtility::makeInstance(SiteFinder::class)->getSiteByPageId($id);
706
        } catch (SiteNotFoundException $exception) {
707
            $site = null;
708
        }
709
710
        // Load PageTS from all pages of the rootLine
711
        $pageTs = GeneralUtility::makeInstance(PageTsConfigLoader::class)->load($rootLine);
712
713
        // Parse the PageTS into an array, also applying conditions
714
        $parser = GeneralUtility::makeInstance(
715
            PageTsConfigParser::class,
716
            GeneralUtility::makeInstance(TypoScriptParser::class),
717
            GeneralUtility::makeInstance(CacheManager::class)->getCache('hash')
718
        );
719
        $matcher = GeneralUtility::makeInstance(ConditionMatcher::class, null, $id, $rootLine);
720
        $tsConfig = $parser->parse($pageTs, $matcher, $site);
721
        $cacheHash = md5(json_encode($tsConfig));
722
723
        // Get User TSconfig overlay, if no backend user is logged-in, this needs to be checked as well
724
        if (static::getBackendUserAuthentication()) {
725
            $userTSconfig = static::getBackendUserAuthentication()->getTSConfig() ?? [];
726
        } else {
727
            $userTSconfig = [];
728
        }
729
730
        if (is_array($userTSconfig['page.'] ?? null)) {
731
            // Override page TSconfig with user TSconfig
732
            ArrayUtility::mergeRecursiveWithOverrule($tsConfig, $userTSconfig['page.']);
733
            $cacheHash .= '_user' . static::getBackendUserAuthentication()->user['uid'];
734
        }
735
736
        // Many pages end up with the same ts config. To reduce memory usage, the cache
737
        // entries are a linked list: One or more pids point to content hashes which then
738
        // contain the cached content.
739
        $cache->set('pagesTsConfigHashToContent' . $cacheHash, $tsConfig, ['pagesTsConfig']);
740
        $cache->set('pagesTsConfigIdToHash' . $id, $cacheHash, ['pagesTsConfig']);
741
742
        return $tsConfig;
743
    }
744
745
    /*******************************************
746
     *
747
     * Users / Groups related
748
     *
749
     *******************************************/
750
    /**
751
     * Returns an array with be_users records of all user NOT DELETED sorted by their username
752
     * Keys in the array is the be_users uid
753
     *
754
     * @param string $fields Optional $fields list (default: username,usergroup,usergroup_cached_list,uid) can be used to set the selected fields
755
     * @param string $where Optional $where clause (fx. "AND username='pete'") can be used to limit query
756
     * @return array
757
     * @internal should only be used from within TYPO3 Core, use a direct SQL query instead to ensure proper DBAL where statements
758
     */
759
    public static function getUserNames($fields = 'username,usergroup,usergroup_cached_list,uid', $where = '')
760
    {
761
        return self::getRecordsSortedByTitle(
762
            GeneralUtility::trimExplode(',', $fields, true),
763
            'be_users',
764
            'username',
765
            'AND pid=0 ' . $where
766
        );
767
    }
768
769
    /**
770
     * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
771
     *
772
     * @param string $fields Field list
773
     * @param string $where WHERE clause
774
     * @return array
775
     * @internal should only be used from within TYPO3 Core, use a direct SQL query instead to ensure proper DBAL where statements
776
     */
777
    public static function getGroupNames($fields = 'title,uid', $where = '')
778
    {
779
        return self::getRecordsSortedByTitle(
780
            GeneralUtility::trimExplode(',', $fields, true),
781
            'be_groups',
782
            'title',
783
            'AND pid=0 ' . $where
784
        );
785
    }
786
787
    /**
788
     * Returns an array of all non-deleted records of a table sorted by a given title field.
789
     * The value of the title field will be replaced by the return value
790
     * of self::getRecordTitle() before the sorting is performed.
791
     *
792
     * @param array $fields Fields to select
793
     * @param string $table Table name
794
     * @param string $titleField Field that will contain the record title
795
     * @param string $where Additional where clause
796
     * @return array Array of sorted records
797
     */
798
    protected static function getRecordsSortedByTitle(array $fields, $table, $titleField, $where = '')
799
    {
800
        $fieldsIndex = array_flip($fields);
801
        // Make sure the titleField is amongst the fields when getting sorted
802
        $fieldsIndex[$titleField] = 1;
803
804
        $result = [];
805
806
        $queryBuilder = static::getQueryBuilderForTable($table);
807
        $queryBuilder->getRestrictions()
808
            ->removeAll()
809
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
810
811
        $res = $queryBuilder
812
            ->select('*')
813
            ->from($table)
814
            ->where(QueryHelper::stripLogicalOperatorPrefix($where))
815
            ->execute();
816
817
        while ($record = $res->fetch()) {
818
            // store the uid, because it might be unset if it's not among the requested $fields
819
            $recordId = $record['uid'];
820
            $record[$titleField] = self::getRecordTitle($table, $record);
821
822
            // include only the requested fields in the result
823
            $result[$recordId] = array_intersect_key($record, $fieldsIndex);
824
        }
825
826
        // sort records by $sortField. This is not done in the query because the title might have been overwritten by
827
        // self::getRecordTitle();
828
        return ArrayUtility::sortArraysByKey($result, $titleField);
829
    }
830
831
    /**
832
     * Returns the array $usernames with the names of all users NOT IN $groupArray changed to the uid (hides the usernames!).
833
     * If $excludeBlindedFlag is set, then these records are unset from the array $usernames
834
     * Takes $usernames (array made by \TYPO3\CMS\Backend\Utility\BackendUtility::getUserNames()) and a $groupArray (array with the groups a certain user is member of) as input
835
     *
836
     * @param array $usernames User names
837
     * @param array $groupArray Group names
838
     * @param bool $excludeBlindedFlag If $excludeBlindedFlag is set, then these records are unset from the array $usernames
839
     * @return array User names, blinded
840
     * @internal
841
     */
842
    public static function blindUserNames($usernames, $groupArray, $excludeBlindedFlag = false)
843
    {
844
        if (is_array($usernames) && is_array($groupArray)) {
0 ignored issues
show
introduced by
The condition is_array($groupArray) is always true.
Loading history...
845
            foreach ($usernames as $uid => $row) {
846
                $userN = $uid;
847
                $set = 0;
848
                if ($row['uid'] != static::getBackendUserAuthentication()->user['uid']) {
849
                    foreach ($groupArray as $v) {
850
                        if ($v && GeneralUtility::inList($row['usergroup_cached_list'], $v)) {
851
                            $userN = $row['username'];
852
                            $set = 1;
853
                        }
854
                    }
855
                } else {
856
                    $userN = $row['username'];
857
                    $set = 1;
858
                }
859
                $usernames[$uid]['username'] = $userN;
860
                if ($excludeBlindedFlag && !$set) {
861
                    unset($usernames[$uid]);
862
                }
863
            }
864
        }
865
        return $usernames;
866
    }
867
868
    /**
869
     * Corresponds to blindUserNames but works for groups instead
870
     *
871
     * @param array $groups Group names
872
     * @param array $groupArray Group names (reference)
873
     * @param bool $excludeBlindedFlag If $excludeBlindedFlag is set, then these records are unset from the array $usernames
874
     * @return array
875
     * @internal
876
     */
877
    public static function blindGroupNames($groups, $groupArray, $excludeBlindedFlag = false)
878
    {
879
        if (is_array($groups) && is_array($groupArray)) {
0 ignored issues
show
introduced by
The condition is_array($groupArray) is always true.
Loading history...
880
            foreach ($groups as $uid => $row) {
881
                $groupN = $uid;
882
                $set = 0;
883
                if (in_array($uid, $groupArray, false)) {
884
                    $groupN = $row['title'];
885
                    $set = 1;
886
                }
887
                $groups[$uid]['title'] = $groupN;
888
                if ($excludeBlindedFlag && !$set) {
889
                    unset($groups[$uid]);
890
                }
891
            }
892
        }
893
        return $groups;
894
    }
895
896
    /*******************************************
897
     *
898
     * Output related
899
     *
900
     *******************************************/
901
    /**
902
     * Returns the difference in days between input $tstamp and $EXEC_TIME
903
     *
904
     * @param int $tstamp Time stamp, seconds
905
     * @return int
906
     */
907
    public static function daysUntil($tstamp)
908
    {
909
        $delta_t = $tstamp - $GLOBALS['EXEC_TIME'];
910
        return ceil($delta_t / (3600 * 24));
911
    }
912
913
    /**
914
     * Returns $tstamp formatted as "ddmmyy" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'])
915
     *
916
     * @param int $tstamp Time stamp, seconds
917
     * @return string Formatted time
918
     */
919
    public static function date($tstamp)
920
    {
921
        return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int)$tstamp);
922
    }
923
924
    /**
925
     * Returns $tstamp formatted as "ddmmyy hhmm" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] AND $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'])
926
     *
927
     * @param int $value Time stamp, seconds
928
     * @return string Formatted time
929
     */
930
    public static function datetime($value)
931
    {
932
        return date(
933
            $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'],
934
            $value
935
        );
936
    }
937
938
    /**
939
     * Returns $value (in seconds) formatted as hh:mm:ss
940
     * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
941
     *
942
     * @param int $value Time stamp, seconds
943
     * @param bool $withSeconds Output hh:mm:ss. If FALSE: hh:mm
944
     * @return string Formatted time
945
     */
946
    public static function time($value, $withSeconds = true)
947
    {
948
        return gmdate('H:i' . ($withSeconds ? ':s' : ''), (int)$value);
949
    }
950
951
    /**
952
     * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
953
     *
954
     * @param int $seconds Seconds could be the difference of a certain timestamp and time()
955
     * @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")
956
     * @return string Formatted time
957
     */
958
    public static function calcAge($seconds, $labels = 'min|hrs|days|yrs|min|hour|day|year')
959
    {
960
        $labelArr = GeneralUtility::trimExplode('|', $labels, true);
961
        $absSeconds = abs($seconds);
962
        $sign = $seconds < 0 ? -1 : 1;
963
        if ($absSeconds < 3600) {
964
            $val = round($absSeconds / 60);
965
            $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[4] : $labelArr[0]);
966
        } elseif ($absSeconds < 24 * 3600) {
967
            $val = round($absSeconds / 3600);
968
            $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[5] : $labelArr[1]);
969
        } elseif ($absSeconds < 365 * 24 * 3600) {
970
            $val = round($absSeconds / (24 * 3600));
971
            $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[6] : $labelArr[2]);
972
        } else {
973
            $val = round($absSeconds / (365 * 24 * 3600));
974
            $seconds = $sign * $val . ' ' . ($val == 1 ? $labelArr[7] : $labelArr[3]);
975
        }
976
        return $seconds;
977
    }
978
979
    /**
980
     * Returns a formatted timestamp if $tstamp is set.
981
     * The date/datetime will be followed by the age in parenthesis.
982
     *
983
     * @param int $tstamp Time stamp, seconds
984
     * @param int $prefix 1/-1 depending on polarity of age.
985
     * @param string $date $date=="date" will yield "dd:mm:yy" formatting, otherwise "dd:mm:yy hh:mm
986
     * @return string
987
     */
988
    public static function dateTimeAge($tstamp, $prefix = 1, $date = '')
989
    {
990
        if (!$tstamp) {
991
            return '';
992
        }
993
        $label = static::getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears');
994
        $age = ' (' . self::calcAge($prefix * ($GLOBALS['EXEC_TIME'] - $tstamp), $label) . ')';
995
        return ($date === 'date' ? self::date($tstamp) : self::datetime($tstamp)) . $age;
996
    }
997
998
    /**
999
     * Resolves file references for a given record.
1000
     *
1001
     * @param string $tableName Name of the table of the record
1002
     * @param string $fieldName Name of the field of the record
1003
     * @param array $element Record data
1004
     * @param int|null $workspaceId Workspace to fetch data for
1005
     * @return \TYPO3\CMS\Core\Resource\FileReference[]|null
1006
     */
1007
    public static function resolveFileReferences($tableName, $fieldName, $element, $workspaceId = null)
1008
    {
1009
        if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'])) {
1010
            return null;
1011
        }
1012
        $configuration = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
1013
        if (empty($configuration['type']) || $configuration['type'] !== 'inline'
1014
            || empty($configuration['foreign_table']) || $configuration['foreign_table'] !== 'sys_file_reference'
1015
        ) {
1016
            return null;
1017
        }
1018
1019
        $fileReferences = [];
1020
        /** @var RelationHandler $relationHandler */
1021
        $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
1022
        if ($workspaceId !== null) {
1023
            $relationHandler->setWorkspaceId($workspaceId);
1024
        }
1025
        $relationHandler->start(
1026
            $element[$fieldName],
1027
            $configuration['foreign_table'],
1028
            $configuration['MM'] ?? '',
1029
            $element['uid'],
1030
            $tableName,
1031
            $configuration
1032
        );
1033
        $relationHandler->processDeletePlaceholder();
1034
        $referenceUids = $relationHandler->tableArray[$configuration['foreign_table']];
1035
1036
        foreach ($referenceUids as $referenceUid) {
1037
            try {
1038
                $fileReference = GeneralUtility::makeInstance(ResourceFactory::class)->getFileReferenceObject(
1039
                    $referenceUid,
1040
                    [],
1041
                    $workspaceId === 0
1042
                );
1043
                $fileReferences[$fileReference->getUid()] = $fileReference;
1044
            } catch (FileDoesNotExistException $e) {
1045
                /**
1046
                 * We just catch the exception here
1047
                 * Reasoning: There is nothing an editor or even admin could do
1048
                 */
1049
            } catch (\InvalidArgumentException $e) {
1050
                /**
1051
                 * The storage does not exist anymore
1052
                 * Log the exception message for admins as they maybe can restore the storage
1053
                 */
1054
                self::getLogger()->error($e->getMessage(), ['table' => $tableName, 'fieldName' => $fieldName, 'referenceUid' => $referenceUid, 'exception' => $e]);
1055
            }
1056
        }
1057
1058
        return $fileReferences;
1059
    }
1060
1061
    /**
1062
     * Returns a linked image-tag for thumbnail(s)/fileicons/truetype-font-previews from a database row with sys_file_references
1063
     * All $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] extension are made to thumbnails + ttf file (renders font-example)
1064
     * Thumbnails are linked to ShowItemController (/thumbnails route)
1065
     *
1066
     * @param array $row Row is the database row from the table, $table.
1067
     * @param string $table Table name for $row (present in TCA)
1068
     * @param string $field Field is pointing to the connecting field of sys_file_references
1069
     * @param string $backPath Back path prefix for image tag src="" field
1070
     * @param string $thumbScript UNUSED since FAL
1071
     * @param string $uploaddir UNUSED since FAL
1072
     * @param int $abs UNUSED
1073
     * @param string $tparams Optional: $tparams is additional attributes for the image tags
1074
     * @param int|string $size Optional: $size is [w]x[h] of the thumbnail. 64 is default.
1075
     * @param bool $linkInfoPopup Whether to wrap with a link opening the info popup
1076
     * @return string Thumbnail image tag.
1077
     */
1078
    public static function thumbCode(
1079
        $row,
1080
        $table,
1081
        $field,
1082
        $backPath = '',
1083
        $thumbScript = '',
1084
        $uploaddir = null,
1085
        $abs = 0,
1086
        $tparams = '',
1087
        $size = '',
1088
        $linkInfoPopup = true
1089
    ) {
1090
        // Check and parse the size parameter
1091
        $size = trim($size);
1092
        $sizeParts = [64, 64];
1093
        if ($size) {
1094
            $sizeParts = explode('x', $size . 'x' . $size);
1095
        }
1096
        $thumbData = '';
1097
        $fileReferences = static::resolveFileReferences($table, $field, $row);
1098
        // FAL references
1099
        $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
1100
        if ($fileReferences !== null) {
1101
            foreach ($fileReferences as $fileReferenceObject) {
1102
                // Do not show previews of hidden references
1103
                if ($fileReferenceObject->getProperty('hidden')) {
1104
                    continue;
1105
                }
1106
                $fileObject = $fileReferenceObject->getOriginalFile();
1107
1108
                if ($fileObject->isMissing()) {
1109
                    $thumbData .= '<span class="label label-danger">'
1110
                        . htmlspecialchars(
1111
                            static::getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:warning.file_missing')
1112
                        )
1113
                        . '</span>&nbsp;' . htmlspecialchars($fileObject->getName()) . '<br />';
1114
                    continue;
1115
                }
1116
1117
                // Preview web image or media elements
1118
                if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails']
1119
                    && GeneralUtility::inList(
1120
                        $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'],
1121
                        $fileReferenceObject->getExtension()
1122
                    )
1123
                ) {
1124
                    $cropVariantCollection = CropVariantCollection::create((string)$fileReferenceObject->getProperty('crop'));
1125
                    $cropArea = $cropVariantCollection->getCropArea();
1126
                    $imageUrl = self::getThumbnailUrl($fileObject->getUid(), [
1127
                        'width' => $sizeParts[0],
1128
                        'height' => $sizeParts[1] . 'c',
1129
                        'crop' => $cropArea->isEmpty() ? null : $cropArea->makeAbsoluteBasedOnFile($fileReferenceObject),
1130
                        '_context' => $cropArea->isEmpty() ? ProcessedFile::CONTEXT_IMAGEPREVIEW : ProcessedFile::CONTEXT_IMAGECROPSCALEMASK
1131
                    ]);
1132
                    $attributes = [
1133
                        'src' => $imageUrl,
1134
                        'width' => (int)$sizeParts[0],
1135
                        'height' => (int)$sizeParts[1],
1136
                        'alt' => $fileReferenceObject->getName(),
1137
                    ];
1138
                    $imgTag = '<img ' . GeneralUtility::implodeAttributes($attributes, true) . $tparams . '/>';
1139
                } else {
1140
                    // Icon
1141
                    $imgTag = '<span title="' . htmlspecialchars($fileObject->getName()) . '">'
1142
                        . $iconFactory->getIconForResource($fileObject, Icon::SIZE_SMALL)->render()
1143
                        . '</span>';
1144
                }
1145
                if ($linkInfoPopup) {
1146
                    // relies on module 'TYPO3/CMS/Backend/ActionDispatcher'
1147
                    $attributes = GeneralUtility::implodeAttributes([
1148
                        'data-dispatch-action' => 'TYPO3.InfoWindow.showItem',
1149
                        'data-dispatch-args-list' => '_FILE,' . (int)$fileObject->getUid(),
1150
                    ], true);
1151
                    $thumbData .= '<a href="#" ' . $attributes . '>' . $imgTag . '</a> ';
1152
                } else {
1153
                    $thumbData .= $imgTag;
1154
                }
1155
            }
1156
        }
1157
        return $thumbData;
1158
    }
1159
1160
    /**
1161
     * @param int $fileId
1162
     * @param array $configuration
1163
     * @return string
1164
     * @throws \TYPO3\CMS\Backend\Routing\Exception\RouteNotFoundException
1165
     */
1166
    public static function getThumbnailUrl(int $fileId, array $configuration): string
1167
    {
1168
        $parameters = json_encode([
1169
            'fileId' => $fileId,
1170
            'configuration' => $configuration
1171
        ]);
1172
        $uriParameters = [
1173
            'parameters' => $parameters,
1174
            'hmac' => GeneralUtility::hmac(
1175
                $parameters,
1176
                ThumbnailController::class
1177
            ),
1178
        ];
1179
        return (string)GeneralUtility::makeInstance(UriBuilder::class)
1180
            ->buildUriFromRoute('thumbnails', $uriParameters);
1181
    }
1182
1183
    /**
1184
     * Returns title-attribute information for a page-record informing about id, doktype, hidden, starttime, endtime, fe_group etc.
1185
     *
1186
     * @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)
1187
     * @param string $perms_clause This is used to get the record path of the shortcut page, if any (and doktype==4)
1188
     * @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
1189
     * @return string
1190
     */
1191
    public static function titleAttribForPages($row, $perms_clause = '', $includeAttrib = true)
1192
    {
1193
        $lang = static::getLanguageService();
1194
        $parts = [];
1195
        $parts[] = 'id=' . $row['uid'];
1196
        if ($row['uid'] === 0) {
1197
            $out = htmlspecialchars($parts[0]);
1198
            return $includeAttrib ? 'title="' . $out . '"' : $out;
1199
        }
1200
        switch (VersionState::cast($row['t3ver_state'])) {
1201
            case new VersionState(VersionState::NEW_PLACEHOLDER):
1202
                $parts[] = 'PLH WSID#' . $row['t3ver_wsid'];
1203
                break;
1204
            case new VersionState(VersionState::DELETE_PLACEHOLDER):
1205
                $parts[] = 'Deleted element!';
1206
                break;
1207
            case new VersionState(VersionState::MOVE_PLACEHOLDER):
1208
                $parts[] = 'OLD LOCATION (Move Placeholder) WSID#' . $row['t3ver_wsid'];
1209
                break;
1210
            case new VersionState(VersionState::MOVE_POINTER):
1211
                $parts[] = 'NEW LOCATION (Move-to Pointer) WSID#' . $row['t3ver_wsid'];
1212
                break;
1213
            case new VersionState(VersionState::NEW_PLACEHOLDER_VERSION):
1214
                $parts[] = 'New element!';
1215
                break;
1216
        }
1217
        if ($row['doktype'] == PageRepository::DOKTYPE_LINK) {
1218
            $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['url']['label']) . ' ' . $row['url'];
1219
        } elseif ($row['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1220
            if ($perms_clause) {
1221
                $label = self::getRecordPath((int)$row['shortcut'], $perms_clause, 20);
1222
            } else {
1223
                $row['shortcut'] = (int)$row['shortcut'];
1224
                $lRec = self::getRecordWSOL('pages', $row['shortcut'], 'title');
1225
                $label = $lRec['title'] . ' (id=' . $row['shortcut'] . ')';
1226
            }
1227
            if ($row['shortcut_mode'] != PageRepository::SHORTCUT_MODE_NONE) {
1228
                $label .= ', ' . $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut_mode']['label']) . ' '
1229
                    . $lang->sL(self::getLabelFromItemlist('pages', 'shortcut_mode', $row['shortcut_mode']));
1230
            }
1231
            $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

1231
            $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['shortcut']['label']) . ' ' . /** @scrutinizer ignore-type */ $label;
Loading history...
1232
        } elseif ($row['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT) {
1233
            if ((int)$row['mount_pid'] > 0) {
1234
                if ($perms_clause) {
1235
                    $label = self::getRecordPath((int)$row['mount_pid'], $perms_clause, 20);
1236
                } else {
1237
                    $lRec = self::getRecordWSOL('pages', (int)$row['mount_pid'], 'title');
1238
                    $label = $lRec['title'] . ' (id=' . $row['mount_pid'] . ')';
1239
                }
1240
                $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid']['label']) . ' ' . $label;
1241
                if ($row['mount_pid_ol']) {
1242
                    $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['mount_pid_ol']['label']);
1243
                }
1244
            } else {
1245
                $parts[] = $lang->sL('LLL:EXT:frontend/Resources/Private/Language/locallang_tca.xlf:no_mount_pid');
1246
            }
1247
        }
1248
        if ($row['nav_hide']) {
1249
            $parts[] = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_tca.xlf:pages.nav_hide');
1250
        }
1251
        if ($row['hidden']) {
1252
            $parts[] = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.hidden');
1253
        }
1254
        if ($row['starttime']) {
1255
            $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['starttime']['label'])
1256
                . ' ' . self::dateTimeAge($row['starttime'], -1, 'date');
1257
        }
1258
        if ($row['endtime']) {
1259
            $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['endtime']['label']) . ' '
1260
                . self::dateTimeAge($row['endtime'], -1, 'date');
1261
        }
1262
        if ($row['fe_group']) {
1263
            $fe_groups = [];
1264
            foreach (GeneralUtility::intExplode(',', $row['fe_group']) as $fe_group) {
1265
                if ($fe_group < 0) {
1266
                    $fe_groups[] = $lang->sL(self::getLabelFromItemlist('pages', 'fe_group', $fe_group));
1267
                } else {
1268
                    $lRec = self::getRecordWSOL('fe_groups', $fe_group, 'title');
1269
                    $fe_groups[] = $lRec['title'];
1270
                }
1271
            }
1272
            $label = implode(', ', $fe_groups);
1273
            $parts[] = $lang->sL($GLOBALS['TCA']['pages']['columns']['fe_group']['label']) . ' ' . $label;
1274
        }
1275
        $out = htmlspecialchars(implode(' - ', $parts));
1276
        return $includeAttrib ? 'title="' . $out . '"' : $out;
1277
    }
1278
1279
    /**
1280
     * Returns the combined markup for Bootstraps tooltips
1281
     *
1282
     * @param array $row
1283
     * @param string $table
1284
     * @return string
1285
     */
1286
    public static function getRecordToolTip(array $row, $table = 'pages')
1287
    {
1288
        $toolTipText = self::getRecordIconAltText($row, $table);
1289
        $toolTipCode = 'data-toggle="tooltip" data-title=" '
1290
            . str_replace(' - ', '<br>', $toolTipText)
1291
            . '" data-html="true" data-placement="right"';
1292
        return $toolTipCode;
1293
    }
1294
1295
    /**
1296
     * Returns title-attribute information for ANY record (from a table defined in TCA of course)
1297
     * 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.
1298
     * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
1299
     *
1300
     * @param array $row Table row; $row is a row from the table, $table
1301
     * @param string $table Table name
1302
     * @return string
1303
     */
1304
    public static function getRecordIconAltText($row, $table = 'pages')
1305
    {
1306
        if ($table === 'pages') {
1307
            $out = self::titleAttribForPages($row, '', 0);
1308
        } else {
1309
            $out = !empty(trim($GLOBALS['TCA'][$table]['ctrl']['descriptionColumn'])) ? $row[$GLOBALS['TCA'][$table]['ctrl']['descriptionColumn']] . ' ' : '';
1310
            $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
1311
            // Uid is added
1312
            $out .= 'id=' . $row['uid'];
1313
            if (static::isTableWorkspaceEnabled($table)) {
1314
                switch (VersionState::cast($row['t3ver_state'])) {
1315
                    case new VersionState(VersionState::NEW_PLACEHOLDER):
1316
                        $out .= ' - PLH WSID#' . $row['t3ver_wsid'];
1317
                        break;
1318
                    case new VersionState(VersionState::DELETE_PLACEHOLDER):
1319
                        $out .= ' - Deleted element!';
1320
                        break;
1321
                    case new VersionState(VersionState::MOVE_PLACEHOLDER):
1322
                        $out .= ' - OLD LOCATION (Move Placeholder) WSID#' . $row['t3ver_wsid'];
1323
                        break;
1324
                    case new VersionState(VersionState::MOVE_POINTER):
1325
                        $out .= ' - NEW LOCATION (Move-to Pointer) WSID#' . $row['t3ver_wsid'];
1326
                        break;
1327
                    case new VersionState(VersionState::NEW_PLACEHOLDER_VERSION):
1328
                        $out .= ' - New element!';
1329
                        break;
1330
                }
1331
            }
1332
            // Hidden
1333
            $lang = static::getLanguageService();
1334
            if ($ctrl['disabled']) {
1335
                $out .= $row[$ctrl['disabled']] ? ' - ' . $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.hidden') : '';
1336
            }
1337
            if ($ctrl['starttime']) {
1338
                if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
1339
                    $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') . ')';
1340
                }
1341
            }
1342
            if ($row[$ctrl['endtime']]) {
1343
                $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') . ')';
1344
            }
1345
        }
1346
        return htmlspecialchars($out);
1347
    }
1348
1349
    /**
1350
     * Returns the label of the first found entry in an "items" array from $GLOBALS['TCA'] (tablename = $table/fieldname = $col) where the value is $key
1351
     *
1352
     * @param string $table Table name, present in $GLOBALS['TCA']
1353
     * @param string $col Field name, present in $GLOBALS['TCA']
1354
     * @param string $key items-array value to match
1355
     * @return string Label for item entry
1356
     */
1357
    public static function getLabelFromItemlist($table, $col, $key)
1358
    {
1359
        // Check, if there is an "items" array:
1360
        if (is_array($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'] ?? false)) {
1361
            // Traverse the items-array...
1362
            foreach ($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'] as $v) {
1363
                // ... and return the first found label where the value was equal to $key
1364
                if ((string)$v[1] === (string)$key) {
1365
                    return $v[0];
1366
                }
1367
            }
1368
        }
1369
        return '';
1370
    }
1371
1372
    /**
1373
     * Return the label of a field by additionally checking TsConfig values
1374
     *
1375
     * @param int $pageId Page id
1376
     * @param string $table Table name
1377
     * @param string $column Field Name
1378
     * @param string $key item value
1379
     * @return string Label for item entry
1380
     */
1381
    public static function getLabelFromItemListMerged($pageId, $table, $column, $key)
1382
    {
1383
        $pageTsConfig = static::getPagesTSconfig($pageId);
1384
        $label = '';
1385
        if (isset($pageTsConfig['TCEFORM.'])
1386
            && \is_array($pageTsConfig['TCEFORM.'])
1387
            && \is_array($pageTsConfig['TCEFORM.'][$table . '.'])
1388
            && \is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.'])
1389
        ) {
1390
            if (\is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'])
1391
                && isset($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'][$key])
1392
            ) {
1393
                $label = $pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'][$key];
1394
            } elseif (\is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'])
1395
                && isset($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'][$key])
1396
            ) {
1397
                $label = $pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['altLabels.'][$key];
1398
            }
1399
        }
1400
        if (empty($label)) {
1401
            $tcaValue = self::getLabelFromItemlist($table, $column, $key);
1402
            if (!empty($tcaValue)) {
1403
                $label = $tcaValue;
1404
            }
1405
        }
1406
        return $label;
1407
    }
1408
1409
    /**
1410
     * Splits the given key with commas and returns the list of all the localized items labels, separated by a comma.
1411
     * NOTE: this does not take itemsProcFunc into account
1412
     *
1413
     * @param string $table Table name, present in TCA
1414
     * @param string $column Field name
1415
     * @param string $keyList Key or comma-separated list of keys.
1416
     * @param array $columnTsConfig page TSConfig for $column (TCEMAIN.<table>.<column>)
1417
     * @return string Comma-separated list of localized labels
1418
     */
1419
    public static function getLabelsFromItemsList($table, $column, $keyList, array $columnTsConfig = [])
1420
    {
1421
        // Check if there is an "items" array
1422
        if (
1423
            !isset($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])
1424
            || !is_array($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])
1425
            || $keyList === ''
1426
        ) {
1427
            return '';
1428
        }
1429
1430
        $keys = GeneralUtility::trimExplode(',', $keyList, true);
1431
        $labels = [];
1432
        // Loop on all selected values
1433
        foreach ($keys as $key) {
1434
            $label = null;
1435
            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...
1436
                // Check if label has been defined or redefined via pageTsConfig
1437
                if (isset($columnTsConfig['addItems.'][$key])) {
1438
                    $label = $columnTsConfig['addItems.'][$key];
1439
                } elseif (isset($columnTsConfig['altLabels.'][$key])) {
1440
                    $label = $columnTsConfig['altLabels.'][$key];
1441
                }
1442
            }
1443
            if ($label === null) {
1444
                // Otherwise lookup the label in TCA items list
1445
                foreach ($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'] as $itemConfiguration) {
1446
                    [$currentLabel, $currentKey] = $itemConfiguration;
1447
                    if ((string)$key === (string)$currentKey) {
1448
                        $label = $currentLabel;
1449
                        break;
1450
                    }
1451
                }
1452
            }
1453
            if ($label !== null) {
1454
                $labels[] = static::getLanguageService()->sL($label);
1455
            }
1456
        }
1457
        return implode(', ', $labels);
1458
    }
1459
1460
    /**
1461
     * Returns the label-value for fieldname $col in table, $table
1462
     * 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>'
1463
     *
1464
     * @param string $table Table name, present in $GLOBALS['TCA']
1465
     * @param string $col Field name
1466
     * @return string or NULL if $col is not found in the TCA table
1467
     */
1468
    public static function getItemLabel($table, $col)
1469
    {
1470
        // Check if column exists
1471
        if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
1472
            return $GLOBALS['TCA'][$table]['columns'][$col]['label'];
1473
        }
1474
1475
        return null;
1476
    }
1477
1478
    /**
1479
     * Returns the "title"-value in record, $row, from table, $table
1480
     * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
1481
     *
1482
     * @param string $table Table name, present in TCA
1483
     * @param array $row Row from table
1484
     * @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
1485
     * @param bool $forceResult If set, the function always returns an output. If no value is found for the title, '[No title]' is returned (localized).
1486
     * @return string
1487
     */
1488
    public static function getRecordTitle($table, $row, $prep = false, $forceResult = true)
1489
    {
1490
        $params = [];
1491
        $recordTitle = '';
1492
        if (isset($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table])) {
1493
            // If configured, call userFunc
1494
            if (!empty($GLOBALS['TCA'][$table]['ctrl']['label_userFunc'])) {
1495
                $params['table'] = $table;
1496
                $params['row'] = $row;
1497
                $params['title'] = '';
1498
                $params['options'] = $GLOBALS['TCA'][$table]['ctrl']['label_userFunc_options'] ?? [];
1499
1500
                // Create NULL-reference
1501
                $null = null;
1502
                GeneralUtility::callUserFunction($GLOBALS['TCA'][$table]['ctrl']['label_userFunc'], $params, $null);
1503
                $recordTitle = $params['title'];
1504
            } else {
1505
                // No userFunc: Build label
1506
                $recordTitle = self::getProcessedValue(
1507
                    $table,
1508
                    $GLOBALS['TCA'][$table]['ctrl']['label'],
1509
                    $row[$GLOBALS['TCA'][$table]['ctrl']['label']],
1510
                    0,
1511
                    0,
1512
                    false,
1513
                    $row['uid'],
1514
                    $forceResult
1515
                );
1516
                if (!empty($GLOBALS['TCA'][$table]['ctrl']['label_alt'])
1517
                    && (!empty($GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) || (string)$recordTitle === '')
1518
                ) {
1519
                    $altFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], true);
1520
                    $tA = [];
1521
                    if (!empty($recordTitle)) {
1522
                        $tA[] = $recordTitle;
1523
                    }
1524
                    foreach ($altFields as $fN) {
1525
                        $recordTitle = trim(strip_tags($row[$fN]));
1526
                        if ((string)$recordTitle !== '') {
1527
                            $recordTitle = self::getProcessedValue($table, $fN, $recordTitle, 0, 0, false, $row['uid']);
1528
                            if (!$GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
1529
                                break;
1530
                            }
1531
                            $tA[] = $recordTitle;
1532
                        }
1533
                    }
1534
                    if ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
1535
                        $recordTitle = implode(', ', $tA);
1536
                    }
1537
                }
1538
            }
1539
            // If the current result is empty, set it to '[No title]' (localized) and prepare for output if requested
1540
            if ($prep || $forceResult) {
1541
                if ($prep) {
1542
                    $recordTitle = self::getRecordTitlePrep($recordTitle);
1543
                }
1544
                if (trim($recordTitle) === '') {
1545
                    $recordTitle = self::getNoRecordTitle($prep);
1546
                }
1547
            }
1548
        }
1549
1550
        return $recordTitle;
1551
    }
1552
1553
    /**
1554
     * Crops a title string to a limited length and if it really was cropped, wrap it in a <span title="...">|</span>,
1555
     * which offers a tooltip with the original title when moving mouse over it.
1556
     *
1557
     * @param string $title The title string to be cropped
1558
     * @param int $titleLength Crop title after this length - if not set, BE_USER->uc['titleLen'] is used
1559
     * @return string The processed title string, wrapped in <span title="...">|</span> if cropped
1560
     */
1561
    public static function getRecordTitlePrep($title, $titleLength = 0)
1562
    {
1563
        // If $titleLength is not a valid positive integer, use BE_USER->uc['titleLen']:
1564
        if (!$titleLength || !MathUtility::canBeInterpretedAsInteger($titleLength) || $titleLength < 0) {
1565
            $titleLength = static::getBackendUserAuthentication()->uc['titleLen'];
1566
        }
1567
        $titleOrig = htmlspecialchars($title);
1568
        $title = htmlspecialchars(GeneralUtility::fixed_lgd_cs($title, $titleLength));
1569
        // If title was cropped, offer a tooltip:
1570
        if ($titleOrig != $title) {
1571
            $title = '<span title="' . $titleOrig . '">' . $title . '</span>';
1572
        }
1573
        return $title;
1574
    }
1575
1576
    /**
1577
     * Get a localized [No title] string, wrapped in <em>|</em> if $prep is TRUE.
1578
     *
1579
     * @param bool $prep Wrap result in <em>|</em>
1580
     * @return string Localized [No title] string
1581
     */
1582
    public static function getNoRecordTitle($prep = false)
1583
    {
1584
        $noTitle = '[' .
1585
            htmlspecialchars(static::getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.no_title'))
1586
            . ']';
1587
        if ($prep) {
1588
            $noTitle = '<em>' . $noTitle . '</em>';
1589
        }
1590
        return $noTitle;
1591
    }
1592
1593
    /**
1594
     * Returns a human readable output of a value from a record
1595
     * 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.
1596
     * $table/$col is tablename and fieldname
1597
     * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
1598
     *
1599
     * @param string $table Table name, present in TCA
1600
     * @param string $col Field name, present in TCA
1601
     * @param string $value The value of that field from a selected record
1602
     * @param int $fixed_lgd_chars The max amount of characters the value may occupy
1603
     * @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")
1604
     * @param bool $noRecordLookup If set, no records will be looked up, UIDs are just shown.
1605
     * @param int $uid Uid of the current record
1606
     * @param bool $forceResult If BackendUtility::getRecordTitle is used to process the value, this parameter is forwarded.
1607
     * @param int $pid Optional page uid is used to evaluate page TSConfig for the given field
1608
     * @throws \InvalidArgumentException
1609
     * @return string|null
1610
     */
1611
    public static function getProcessedValue(
1612
        $table,
1613
        $col,
1614
        $value,
1615
        $fixed_lgd_chars = 0,
1616
        $defaultPassthrough = false,
1617
        $noRecordLookup = false,
1618
        $uid = 0,
1619
        $forceResult = true,
1620
        $pid = 0
1621
    ) {
1622
        if ($col === 'uid') {
1623
            // uid is not in TCA-array
1624
            return $value;
1625
        }
1626
        // Check if table and field is configured
1627
        if (!isset($GLOBALS['TCA'][$table]['columns'][$col]) || !is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
1628
            return null;
1629
        }
1630
        // Depending on the fields configuration, make a meaningful output value.
1631
        $theColConf = $GLOBALS['TCA'][$table]['columns'][$col]['config'] ?? [];
1632
        /*****************
1633
         *HOOK: pre-processing the human readable output from a record
1634
         ****************/
1635
        $referenceObject = new \stdClass();
1636
        $referenceObject->table = $table;
1637
        $referenceObject->fieldName = $col;
1638
        $referenceObject->uid = $uid;
1639
        $referenceObject->value = &$value;
1640
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] ?? [] as $_funcRef) {
1641
            GeneralUtility::callUserFunction($_funcRef, $theColConf, $referenceObject);
1642
        }
1643
1644
        $l = '';
1645
        $lang = static::getLanguageService();
1646
        switch ((string)($theColConf['type'] ?? '')) {
1647
            case 'radio':
1648
                $l = self::getLabelFromItemlist($table, $col, $value);
1649
                $l = $lang->sL($l);
1650
                break;
1651
            case 'inline':
1652
            case 'select':
1653
                if (!empty($theColConf['MM'])) {
1654
                    if ($uid) {
1655
                        // Display the title of MM related records in lists
1656
                        if ($noRecordLookup) {
1657
                            $MMfields = [];
1658
                            $MMfields[] = $theColConf['foreign_table'] . '.uid';
1659
                        } else {
1660
                            $MMfields = [$theColConf['foreign_table'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']];
1661
                            if (isset($GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt'])) {
1662
                                foreach (GeneralUtility::trimExplode(
1663
                                    ',',
1664
                                    $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt'],
1665
                                    true
1666
                                ) as $f) {
1667
                                    $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
1668
                                }
1669
                            }
1670
                        }
1671
                        /** @var RelationHandler $dbGroup */
1672
                        $dbGroup = GeneralUtility::makeInstance(RelationHandler::class);
1673
                        $dbGroup->start(
1674
                            $value,
1675
                            $theColConf['foreign_table'],
1676
                            $theColConf['MM'],
1677
                            $uid,
1678
                            $table,
1679
                            $theColConf
1680
                        );
1681
                        $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
1682
                        if (is_array($selectUids) && !empty($selectUids)) {
1683
                            $queryBuilder = static::getQueryBuilderForTable($theColConf['foreign_table']);
1684
                            $queryBuilder->getRestrictions()
1685
                                ->removeAll()
1686
                                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1687
1688
                            $result = $queryBuilder
1689
                                ->select('uid', ...$MMfields)
1690
                                ->from($theColConf['foreign_table'])
1691
                                ->where(
1692
                                    $queryBuilder->expr()->in(
1693
                                        'uid',
1694
                                        $queryBuilder->createNamedParameter($selectUids, Connection::PARAM_INT_ARRAY)
1695
                                    )
1696
                                )
1697
                                ->execute();
1698
1699
                            $mmlA = [];
1700
                            while ($MMrow = $result->fetch()) {
1701
                                // Keep sorting of $selectUids
1702
                                $selectedUid = array_search($MMrow['uid'], $selectUids);
1703
                                $mmlA[$selectedUid] = $MMrow['uid'];
1704
                                if (!$noRecordLookup) {
1705
                                    $mmlA[$selectedUid] = static::getRecordTitle(
1706
                                        $theColConf['foreign_table'],
1707
                                        $MMrow,
1708
                                        false,
1709
                                        $forceResult
1710
                                    );
1711
                                }
1712
                            }
1713
1714
                            if (!empty($mmlA)) {
1715
                                ksort($mmlA);
1716
                                $l = implode('; ', $mmlA);
1717
                            } else {
1718
                                $l = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:notAvailableAbbreviation');
1719
                            }
1720
                        } else {
1721
                            $l = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:notAvailableAbbreviation');
1722
                        }
1723
                    } else {
1724
                        $l = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:notAvailableAbbreviation');
1725
                    }
1726
                } else {
1727
                    $columnTsConfig = [];
1728
                    if ($pid) {
1729
                        $pageTsConfig = self::getPagesTSconfig($pid);
1730
                        if (isset($pageTsConfig['TCEFORM.'][$table . '.'][$col . '.']) && is_array($pageTsConfig['TCEFORM.'][$table . '.'][$col . '.'])) {
1731
                            $columnTsConfig = $pageTsConfig['TCEFORM.'][$table . '.'][$col . '.'];
1732
                        }
1733
                    }
1734
                    $l = self::getLabelsFromItemsList($table, $col, $value, $columnTsConfig);
1735
                    if (!empty($theColConf['foreign_table']) && !$l && !empty($GLOBALS['TCA'][$theColConf['foreign_table']])) {
1736
                        if ($noRecordLookup) {
1737
                            $l = $value;
1738
                        } else {
1739
                            $rParts = [];
1740
                            if ($uid && isset($theColConf['foreign_field']) && $theColConf['foreign_field'] !== '') {
1741
                                $queryBuilder = static::getQueryBuilderForTable($theColConf['foreign_table']);
1742
                                $queryBuilder->getRestrictions()
1743
                                    ->removeAll()
1744
                                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
1745
                                    ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
1746
                                $constraints = [
1747
                                    $queryBuilder->expr()->eq(
1748
                                        $theColConf['foreign_field'],
1749
                                        $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
1750
                                    )
1751
                                ];
1752
1753
                                if (!empty($theColConf['foreign_table_field'])) {
1754
                                    $constraints[] = $queryBuilder->expr()->eq(
1755
                                        $theColConf['foreign_table_field'],
1756
                                        $queryBuilder->createNamedParameter($table, \PDO::PARAM_STR)
1757
                                    );
1758
                                }
1759
1760
                                // Add additional where clause if foreign_match_fields are defined
1761
                                $foreignMatchFields = [];
1762
                                if (is_array($theColConf['foreign_match_fields'])) {
1763
                                    $foreignMatchFields = $theColConf['foreign_match_fields'];
1764
                                }
1765
1766
                                foreach ($foreignMatchFields as $matchField => $matchValue) {
1767
                                    $constraints[] = $queryBuilder->expr()->eq(
1768
                                        $matchField,
1769
                                        $queryBuilder->createNamedParameter($matchValue)
1770
                                    );
1771
                                }
1772
1773
                                $result = $queryBuilder
1774
                                    ->select('*')
1775
                                    ->from($theColConf['foreign_table'])
1776
                                    ->where(...$constraints)
1777
                                    ->execute();
1778
1779
                                while ($record = $result->fetch()) {
1780
                                    $rParts[] = $record['uid'];
1781
                                }
1782
                            }
1783
                            if (empty($rParts)) {
1784
                                $rParts = GeneralUtility::trimExplode(',', $value, true);
1785
                            }
1786
                            $lA = [];
1787
                            foreach ($rParts as $rVal) {
1788
                                $rVal = (int)$rVal;
1789
                                $r = self::getRecordWSOL($theColConf['foreign_table'], $rVal);
1790
                                if (is_array($r)) {
1791
                                    $lA[] = $lang->sL($theColConf['foreign_table_prefix'])
1792
                                        . self::getRecordTitle($theColConf['foreign_table'], $r, false, $forceResult);
1793
                                } else {
1794
                                    $lA[] = $rVal ? '[' . $rVal . '!]' : '';
1795
                                }
1796
                            }
1797
                            $l = implode(', ', $lA);
1798
                        }
1799
                    }
1800
                    if (empty($l) && !empty($value)) {
1801
                        // Use plain database value when label is empty
1802
                        $l = $value;
1803
                    }
1804
                }
1805
                break;
1806
            case 'group':
1807
                // resolve the titles for DB records
1808
                if (isset($theColConf['internal_type']) && $theColConf['internal_type'] === 'db') {
1809
                    if (isset($theColConf['MM']) && $theColConf['MM']) {
1810
                        if ($uid) {
1811
                            // Display the title of MM related records in lists
1812
                            if ($noRecordLookup) {
1813
                                $MMfields = [];
1814
                                $MMfields[] = $theColConf['foreign_table'] . '.uid';
1815
                            } else {
1816
                                $MMfields = [$theColConf['foreign_table'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']];
1817
                                $altLabelFields = explode(
1818
                                    ',',
1819
                                    $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt']
1820
                                );
1821
                                foreach ($altLabelFields as $f) {
1822
                                    $f = trim($f);
1823
                                    if ($f !== '') {
1824
                                        $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
1825
                                    }
1826
                                }
1827
                            }
1828
                            /** @var RelationHandler $dbGroup */
1829
                            $dbGroup = GeneralUtility::makeInstance(RelationHandler::class);
1830
                            $dbGroup->start(
1831
                                $value,
1832
                                $theColConf['foreign_table'],
1833
                                $theColConf['MM'],
1834
                                $uid,
1835
                                $table,
1836
                                $theColConf
1837
                            );
1838
                            $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
1839
                            if (!empty($selectUids) && is_array($selectUids)) {
1840
                                $queryBuilder = static::getQueryBuilderForTable($theColConf['foreign_table']);
1841
                                $queryBuilder->getRestrictions()
1842
                                    ->removeAll()
1843
                                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1844
1845
                                $result = $queryBuilder
1846
                                    ->select('uid', ...$MMfields)
1847
                                    ->from($theColConf['foreign_table'])
1848
                                    ->where(
1849
                                        $queryBuilder->expr()->in(
1850
                                            'uid',
1851
                                            $queryBuilder->createNamedParameter(
1852
                                                $selectUids,
1853
                                                Connection::PARAM_INT_ARRAY
1854
                                            )
1855
                                        )
1856
                                    )
1857
                                    ->execute();
1858
1859
                                $mmlA = [];
1860
                                while ($MMrow = $result->fetch()) {
1861
                                    // Keep sorting of $selectUids
1862
                                    $selectedUid = array_search($MMrow['uid'], $selectUids);
1863
                                    $mmlA[$selectedUid] = $MMrow['uid'];
1864
                                    if (!$noRecordLookup) {
1865
                                        $mmlA[$selectedUid] = static::getRecordTitle(
1866
                                            $theColConf['foreign_table'],
1867
                                            $MMrow,
1868
                                            false,
1869
                                            $forceResult
1870
                                        );
1871
                                    }
1872
                                }
1873
1874
                                if (!empty($mmlA)) {
1875
                                    ksort($mmlA);
1876
                                    $l = implode('; ', $mmlA);
1877
                                } else {
1878
                                    $l = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:notAvailableAbbreviation');
1879
                                }
1880
                            } else {
1881
                                $l = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:notAvailableAbbreviation');
1882
                            }
1883
                        } else {
1884
                            $l = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:notAvailableAbbreviation');
1885
                        }
1886
                    } else {
1887
                        $finalValues = [];
1888
                        $relationTableName = $theColConf['allowed'];
1889
                        $explodedValues = GeneralUtility::trimExplode(',', $value, true);
1890
1891
                        foreach ($explodedValues as $explodedValue) {
1892
                            if (MathUtility::canBeInterpretedAsInteger($explodedValue)) {
1893
                                $relationTableNameForField = $relationTableName;
1894
                            } else {
1895
                                [$relationTableNameForField, $explodedValue] = self::splitTable_Uid($explodedValue);
1896
                            }
1897
1898
                            $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

1898
                            $relationRecord = static::getRecordWSOL($relationTableNameForField, /** @scrutinizer ignore-type */ $explodedValue);
Loading history...
1899
                            $finalValues[] = static::getRecordTitle($relationTableNameForField, $relationRecord);
1900
                        }
1901
                        $l = implode(', ', $finalValues);
1902
                    }
1903
                } else {
1904
                    $l = implode(', ', GeneralUtility::trimExplode(',', $value, true));
1905
                }
1906
                break;
1907
            case 'check':
1908
                if (!is_array($theColConf['items'])) {
1909
                    $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');
1910
                } elseif (count($theColConf['items']) === 1) {
1911
                    reset($theColConf['items']);
1912
                    $invertStateDisplay = current($theColConf['items'])['invertStateDisplay'] ?? false;
1913
                    if ($invertStateDisplay) {
1914
                        $value = !$value;
1915
                    }
1916
                    $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');
1917
                } else {
1918
                    $lA = [];
1919
                    foreach ($theColConf['items'] as $key => $val) {
1920
                        if ($value & 2 ** $key) {
1921
                            $lA[] = $lang->sL($val[0]);
1922
                        }
1923
                    }
1924
                    $l = implode(', ', $lA);
1925
                }
1926
                break;
1927
            case 'input':
1928
                // Hide value 0 for dates, but show it for everything else
1929
                // todo: phpstan states that $value always exists and is not nullable. At the moment, this is a false
1930
                //       positive as null can be passed into this method via $value. As soon as more strict types are
1931
                //       used, this isset check must be replaced with a more appropriate check.
1932
                if (isset($value)) {
1933
                    $dateTimeFormats = QueryHelper::getDateTimeFormats();
1934
1935
                    if (GeneralUtility::inList($theColConf['eval'] ?? '', 'date')) {
1936
                        // Handle native date field
1937
                        if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'date') {
1938
                            $value = $value === $dateTimeFormats['date']['empty'] ? 0 : (int)strtotime($value);
1939
                        } else {
1940
                            $value = (int)$value;
1941
                        }
1942
                        if (!empty($value)) {
1943
                            $ageSuffix = '';
1944
                            $dateColumnConfiguration = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
1945
                            $ageDisplayKey = 'disableAgeDisplay';
1946
1947
                            // generate age suffix as long as not explicitly suppressed
1948
                            if (!isset($dateColumnConfiguration[$ageDisplayKey])
1949
                                // non typesafe comparison on intention
1950
                                || $dateColumnConfiguration[$ageDisplayKey] == false
1951
                            ) {
1952
                                $ageSuffix = ' (' . ($GLOBALS['EXEC_TIME'] - $value > 0 ? '-' : '')
1953
                                    . self::calcAge(
1954
                                        abs($GLOBALS['EXEC_TIME'] - $value),
0 ignored issues
show
Bug introduced by
It seems like abs($GLOBALS['EXEC_TIME'] - $value) can also be of type double; however, parameter $seconds of TYPO3\CMS\Backend\Utilit...ckendUtility::calcAge() 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

1954
                                        /** @scrutinizer ignore-type */ abs($GLOBALS['EXEC_TIME'] - $value),
Loading history...
1955
                                        $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears')
1956
                                    )
1957
                                    . ')';
1958
                            }
1959
1960
                            $l = self::date($value) . $ageSuffix;
1961
                        }
1962
                    } elseif (GeneralUtility::inList($theColConf['eval'] ?? '', 'time')) {
1963
                        // Handle native time field
1964
                        if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'time') {
1965
                            $value = $value === $dateTimeFormats['time']['empty'] ? 0 : (int)strtotime('1970-01-01 ' . $value);
1966
                        } else {
1967
                            $value = (int)$value;
1968
                        }
1969
                        if (!empty($value)) {
1970
                            $l = gmdate('H:i', (int)$value);
1971
                        }
1972
                    } elseif (GeneralUtility::inList($theColConf['eval'] ?? '', 'timesec')) {
1973
                        // Handle native time field
1974
                        if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'time') {
1975
                            $value = $value === $dateTimeFormats['time']['empty'] ? 0 : (int)strtotime('1970-01-01 ' . $value);
1976
                        } else {
1977
                            $value = (int)$value;
1978
                        }
1979
                        if (!empty($value)) {
1980
                            $l = gmdate('H:i:s', (int)$value);
1981
                        }
1982
                    } elseif (GeneralUtility::inList($theColConf['eval'] ?? '', 'datetime')) {
1983
                        // Handle native datetime field
1984
                        if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'datetime') {
1985
                            $value = $value === $dateTimeFormats['datetime']['empty'] ? 0 : (int)strtotime($value);
1986
                        } else {
1987
                            $value = (int)$value;
1988
                        }
1989
                        if (!empty($value)) {
1990
                            $l = self::datetime($value);
1991
                        }
1992
                    } else {
1993
                        $l = $value;
1994
                    }
1995
                }
1996
                break;
1997
            case 'flex':
1998
                $l = strip_tags($value);
1999
                break;
2000
            default:
2001
                if ($defaultPassthrough) {
2002
                    $l = $value;
2003
                } elseif (isset($theColConf['MM'])) {
2004
                    $l = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_common.xlf:notAvailableAbbreviation');
2005
                } elseif ($value) {
2006
                    $l = GeneralUtility::fixed_lgd_cs(strip_tags($value), 200);
2007
                }
2008
        }
2009
        // If this field is a password field, then hide the password by changing it to a random number of asterisk (*)
2010
        if (!empty($theColConf['eval']) && stripos($theColConf['eval'], 'password') !== false) {
2011
            $l = '';
2012
            $randomNumber = random_int(5, 12);
2013
            for ($i = 0; $i < $randomNumber; $i++) {
2014
                $l .= '*';
2015
            }
2016
        }
2017
        /*****************
2018
         *HOOK: post-processing the human readable output from a record
2019
         ****************/
2020
        $null = null;
2021
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] ?? [] as $_funcRef) {
2022
            $params = [
2023
                'value' => $l,
2024
                'colConf' => $theColConf
2025
            ];
2026
            $l = GeneralUtility::callUserFunction($_funcRef, $params, $null);
2027
        }
2028
        if ($fixed_lgd_chars) {
2029
            return GeneralUtility::fixed_lgd_cs($l, $fixed_lgd_chars);
2030
        }
2031
        return $l;
2032
    }
2033
2034
    /**
2035
     * 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.
2036
     *
2037
     * @param string $table Table name, present in TCA
2038
     * @param string $fN Field name
2039
     * @param string $fV Field value
2040
     * @param int $fixed_lgd_chars The max amount of characters the value may occupy
2041
     * @param int $uid Uid of the current record
2042
     * @param bool $forceResult If BackendUtility::getRecordTitle is used to process the value, this parameter is forwarded.
2043
     * @param int $pid Optional page uid is used to evaluate page TSConfig for the given field
2044
     * @return string
2045
     * @see getProcessedValue()
2046
     */
2047
    public static function getProcessedValueExtra(
2048
        $table,
2049
        $fN,
2050
        $fV,
2051
        $fixed_lgd_chars = 0,
2052
        $uid = 0,
2053
        $forceResult = true,
2054
        $pid = 0
2055
    ) {
2056
        $fVnew = self::getProcessedValue($table, $fN, $fV, $fixed_lgd_chars, 1, 0, $uid, $forceResult, $pid);
2057
        if (!isset($fVnew)) {
2058
            if (is_array($GLOBALS['TCA'][$table])) {
2059
                if ($fN == $GLOBALS['TCA'][$table]['ctrl']['tstamp'] || $fN == $GLOBALS['TCA'][$table]['ctrl']['crdate']) {
2060
                    $fVnew = self::datetime($fV);
0 ignored issues
show
Bug introduced by
$fV of type string is incompatible with the type integer expected by parameter $value of TYPO3\CMS\Backend\Utilit...kendUtility::datetime(). ( Ignorable by Annotation )

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

2060
                    $fVnew = self::datetime(/** @scrutinizer ignore-type */ $fV);
Loading history...
2061
                } elseif ($fN === 'pid') {
2062
                    // Fetches the path with no regard to the users permissions to select pages.
2063
                    $fVnew = self::getRecordPath($fV, '1=1', 20);
0 ignored issues
show
Bug introduced by
$fV of type string is incompatible with the type integer expected by parameter $uid of TYPO3\CMS\Backend\Utilit...tility::getRecordPath(). ( Ignorable by Annotation )

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

2063
                    $fVnew = self::getRecordPath(/** @scrutinizer ignore-type */ $fV, '1=1', 20);
Loading history...
2064
                } else {
2065
                    $fVnew = $fV;
2066
                }
2067
            }
2068
        }
2069
        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...
2070
    }
2071
2072
    /**
2073
     * Returns fields for a table, $table, which would typically be interesting to select
2074
     * This includes uid, the fields defined for title, icon-field.
2075
     * 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)
2076
     *
2077
     * @param string $table Table name, present in $GLOBALS['TCA']
2078
     * @param string $prefix Table prefix
2079
     * @param array $fields Preset fields (must include prefix if that is used)
2080
     * @return string List of fields.
2081
     * @internal should only be used from within TYPO3 Core
2082
     */
2083
    public static function getCommonSelectFields($table, $prefix = '', $fields = [])
2084
    {
2085
        $fields[] = $prefix . 'uid';
2086
        if (isset($GLOBALS['TCA'][$table]['ctrl']['label']) && $GLOBALS['TCA'][$table]['ctrl']['label'] != '') {
2087
            $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['label'];
2088
        }
2089
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['label_alt'])) {
2090
            $secondFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], true);
2091
            foreach ($secondFields as $fieldN) {
2092
                $fields[] = $prefix . $fieldN;
2093
            }
2094
        }
2095
        if (static::isTableWorkspaceEnabled($table)) {
2096
            $fields[] = $prefix . 't3ver_state';
2097
            $fields[] = $prefix . 't3ver_wsid';
2098
        }
2099
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['selicon_field'])) {
2100
            $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['selicon_field'];
2101
        }
2102
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['typeicon_column'])) {
2103
            $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['typeicon_column'];
2104
        }
2105
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'])) {
2106
            $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'];
2107
        }
2108
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime'])) {
2109
            $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime'];
2110
        }
2111
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime'])) {
2112
            $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime'];
2113
        }
2114
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group'])) {
2115
            $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group'];
2116
        }
2117
        return implode(',', array_unique($fields));
2118
    }
2119
2120
    /*******************************************
2121
     *
2122
     * Backend Modules API functions
2123
     *
2124
     *******************************************/
2125
2126
    /**
2127
     * Returns CSH help text (description), if configured for, as an array (title, description)
2128
     *
2129
     * @param string $table Table name
2130
     * @param string $field Field name
2131
     * @return array With keys 'description' (raw, as available in locallang), 'title' (optional), 'moreInfo'
2132
     * @internal should only be used from within TYPO3 Core
2133
     */
2134
    public static function helpTextArray($table, $field)
2135
    {
2136
        if (!isset($GLOBALS['TCA_DESCR'][$table]['columns'])) {
2137
            static::getLanguageService()->loadSingleTableDescription($table);
2138
        }
2139
        $output = [
2140
            'description' => null,
2141
            'title' => null,
2142
            'moreInfo' => false
2143
        ];
2144
        if (isset($GLOBALS['TCA_DESCR'][$table]['columns'][$field]) && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field])) {
2145
            $data = $GLOBALS['TCA_DESCR'][$table]['columns'][$field];
2146
            // Add alternative title, if defined
2147
            if ($data['alttitle']) {
2148
                $output['title'] = $data['alttitle'];
2149
            }
2150
            // If we have more information to show and access to the cshmanual
2151
            if (($data['image_descr'] || $data['seeAlso'] || $data['details'] || $data['syntax'])
2152
                && static::getBackendUserAuthentication()->check('modules', 'help_CshmanualCshmanual')
2153
            ) {
2154
                $output['moreInfo'] = true;
2155
            }
2156
            // Add description
2157
            if ($data['description']) {
2158
                $output['description'] = $data['description'];
2159
            }
2160
        }
2161
        return $output;
2162
    }
2163
2164
    /**
2165
     * Returns CSH help text
2166
     *
2167
     * @param string $table Table name
2168
     * @param string $field Field name
2169
     * @return string HTML content for help text
2170
     * @see cshItem()
2171
     * @internal should only be used from within TYPO3 Core
2172
     */
2173
    public static function helpText($table, $field)
2174
    {
2175
        $helpTextArray = self::helpTextArray($table, $field);
2176
        $output = '';
2177
        $arrow = '';
2178
        // Put header before the rest of the text
2179
        if ($helpTextArray['title'] !== null) {
2180
            $output .= '<h2>' . $helpTextArray['title'] . '</h2>';
2181
        }
2182
        // Add see also arrow if we have more info
2183
        if ($helpTextArray['moreInfo']) {
2184
            /** @var IconFactory $iconFactory */
2185
            $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
2186
            $arrow = $iconFactory->getIcon('actions-view-go-forward', Icon::SIZE_SMALL)->render();
2187
        }
2188
        // Wrap description and arrow in p tag
2189
        if ($helpTextArray['description'] !== null || $arrow) {
2190
            $output .= '<p class="help-short">' . nl2br(htmlspecialchars($helpTextArray['description'])) . $arrow . '</p>';
2191
        }
2192
        return $output;
2193
    }
2194
2195
    /**
2196
     * API function that wraps the text / html in help text, so if a user hovers over it
2197
     * the help text will show up
2198
     *
2199
     * @param string $table The table name for which the help should be shown
2200
     * @param string $field The field name for which the help should be shown
2201
     * @param string $text The text which should be wrapped with the help text
2202
     * @param array $overloadHelpText Array with text to overload help text
2203
     * @return string the HTML code ready to render
2204
     * @internal should only be used from within TYPO3 Core
2205
     */
2206
    public static function wrapInHelp($table, $field, $text = '', array $overloadHelpText = [])
2207
    {
2208
        // Initialize some variables
2209
        $helpText = '';
2210
        $abbrClassAdd = '';
2211
        $hasHelpTextOverload = !empty($overloadHelpText);
2212
        // Get the help text that should be shown on hover
2213
        if (!$hasHelpTextOverload) {
2214
            $helpText = self::helpText($table, $field);
2215
        }
2216
        // If there's a help text or some overload information, proceed with preparing an output
2217
        if (!empty($helpText) || $hasHelpTextOverload) {
2218
            // If no text was given, just use the regular help icon
2219
            if ($text == '') {
2220
                $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
2221
                $text = $iconFactory->getIcon('actions-system-help-open', Icon::SIZE_SMALL)->render();
2222
                $abbrClassAdd = ' help-teaser-icon';
2223
            }
2224
            $text = '<abbr class="help-teaser' . $abbrClassAdd . '">' . $text . '</abbr>';
2225
            $wrappedText = '<span class="help-link" href="#" data-table="' . $table . '" data-field="' . $field . '"';
2226
            // The overload array may provide a title and a description
2227
            // If either one is defined, add them to the "data" attributes
2228
            if ($hasHelpTextOverload) {
2229
                if (isset($overloadHelpText['title'])) {
2230
                    $wrappedText .= ' data-title="' . htmlspecialchars($overloadHelpText['title']) . '"';
2231
                }
2232
                if (isset($overloadHelpText['description'])) {
2233
                    $wrappedText .= ' data-description="' . htmlspecialchars($overloadHelpText['description']) . '"';
2234
                }
2235
            }
2236
            $wrappedText .= '>' . $text . '</span>';
2237
            return $wrappedText;
2238
        }
2239
        return $text;
2240
    }
2241
2242
    /**
2243
     * API for getting CSH icons/text for use in backend modules.
2244
     * TCA_DESCR will be loaded if it isn't already
2245
     *
2246
     * @param string $table Table name ('_MOD_'+module name)
2247
     * @param string $field Field name (CSH locallang main key)
2248
     * @param string $_ (unused)
2249
     * @param string $wrap Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
2250
     * @return string HTML content for help text
2251
     */
2252
    public static function cshItem($table, $field, $_ = '', $wrap = '')
2253
    {
2254
        static::getLanguageService()->loadSingleTableDescription($table);
2255
        if (is_array($GLOBALS['TCA_DESCR'][$table])
2256
            && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field])
2257
        ) {
2258
            // Creating short description
2259
            $output = self::wrapInHelp($table, $field);
2260
            if ($output && $wrap) {
2261
                $wrParts = explode('|', $wrap);
2262
                $output = $wrParts[0] . $output . $wrParts[1];
2263
            }
2264
            return $output;
2265
        }
2266
        return '';
2267
    }
2268
2269
    /**
2270
     * Returns a JavaScript string for viewing the page id, $id
2271
     * It will re-use any window already open.
2272
     *
2273
     * @param int $pageUid Page UID
2274
     * @param string $backPath Must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2275
     * @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)
2276
     * @param string $anchorSection Optional anchor to the URL
2277
     * @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!
2278
     * @param string $additionalGetVars Additional GET variables.
2279
     * @param bool $switchFocus If TRUE, then the preview window will gain the focus.
2280
     * @return string
2281
     */
2282
    public static function viewOnClick(
2283
        $pageUid,
2284
        $backPath = '',
2285
        $rootLine = null,
2286
        $anchorSection = '',
2287
        $alternativeUrl = '',
2288
        $additionalGetVars = '',
2289
        $switchFocus = true
2290
    ) {
2291
        try {
2292
            $previewUrl = self::getPreviewUrl(
2293
                $pageUid,
2294
                $backPath,
2295
                $rootLine,
2296
                $anchorSection,
2297
                $alternativeUrl,
2298
                $additionalGetVars,
2299
                $switchFocus
2300
            );
2301
        } catch (UnableToLinkToPageException $e) {
2302
            return '';
2303
        }
2304
2305
        $onclickCode = 'var previewWin = window.open(' . GeneralUtility::quoteJSvalue($previewUrl) . ',\'newTYPO3frontendWindow\');'
2306
            . ($switchFocus ? 'previewWin.focus();' : '') . LF
2307
            . 'if (previewWin.location.href === ' . GeneralUtility::quoteJSvalue($previewUrl) . ') { previewWin.location.reload(); };';
2308
2309
        return $onclickCode;
2310
    }
2311
2312
    /**
2313
     * Returns the preview url
2314
     *
2315
     * It will detect the correct domain name if needed and provide the link with the right back path.
2316
     *
2317
     * @param int $pageUid Page UID
2318
     * @param string $backPath Must point back to TYPO3_mainDir (where the site is assumed to be one level above)
2319
     * @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)
2320
     * @param string $anchorSection Optional anchor to the URL
2321
     * @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!
2322
     * @param string $additionalGetVars Additional GET variables.
2323
     * @param bool $switchFocus If TRUE, then the preview window will gain the focus.
2324
     * @return string
2325
     */
2326
    public static function getPreviewUrl(
2327
        $pageUid,
2328
        $backPath = '',
2329
        $rootLine = null,
2330
        $anchorSection = '',
2331
        $alternativeUrl = '',
2332
        $additionalGetVars = '',
2333
        &$switchFocus = true
2334
    ): string {
2335
        $viewScript = '/index.php?id=';
2336
        if ($alternativeUrl) {
2337
            $viewScript = $alternativeUrl;
2338
        }
2339
2340
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] ?? [] as $className) {
2341
            $hookObj = GeneralUtility::makeInstance($className);
2342
            if (method_exists($hookObj, 'preProcess')) {
2343
                $hookObj->preProcess(
2344
                    $pageUid,
2345
                    $backPath,
2346
                    $rootLine,
2347
                    $anchorSection,
2348
                    $viewScript,
2349
                    $additionalGetVars,
2350
                    $switchFocus
2351
                );
2352
            }
2353
        }
2354
2355
        // If there is an alternative URL or the URL has been modified by a hook, use that one.
2356
        if ($alternativeUrl || $viewScript !== '/index.php?id=') {
2357
            $previewUrl = $viewScript;
2358
        } else {
2359
            $permissionClause = $GLOBALS['BE_USER']->getPagePermsClause(Permission::PAGE_SHOW);
2360
            $pageInfo = self::readPageAccess($pageUid, $permissionClause);
2361
            // prepare custom context for link generation (to allow for example time based previews)
2362
            $context = clone GeneralUtility::makeInstance(Context::class);
2363
            $additionalGetVars .= self::ADMCMD_previewCmds($pageInfo, $context);
2364
2365
            // Build the URL with a site as prefix, if configured
2366
            $siteFinder = GeneralUtility::makeInstance(SiteFinder::class);
2367
            // Check if the page (= its rootline) has a site attached, otherwise just keep the URL as is
2368
            $rootLine = $rootLine ?? BackendUtility::BEgetRootLine($pageUid);
2369
            try {
2370
                $site = $siteFinder->getSiteByPageId((int)$pageUid, $rootLine);
2371
            } catch (SiteNotFoundException $e) {
2372
                throw new UnableToLinkToPageException('The page ' . $pageUid . ' had no proper connection to a site, no link could be built.', 1559794919);
2373
            }
2374
            // Create a multi-dimensional array out of the additional get vars
2375
            $additionalQueryParams = [];
2376
            parse_str($additionalGetVars, $additionalQueryParams);
2377
            if (isset($additionalQueryParams['L'])) {
2378
                $additionalQueryParams['_language'] = $additionalQueryParams['_language'] ?? $additionalQueryParams['L'];
2379
                unset($additionalQueryParams['L']);
2380
            }
2381
            try {
2382
                $previewUrl = (string)$site->getRouter($context)->generateUri(
2383
                    $pageUid,
2384
                    $additionalQueryParams,
2385
                    $anchorSection,
2386
                    RouterInterface::ABSOLUTE_URL
2387
                );
2388
            } catch (\InvalidArgumentException | InvalidRouteArgumentsException $e) {
2389
                throw new UnableToLinkToPageException('The page ' . $pageUid . ' had no proper connection to a site, no link could be built.', 1559794914);
2390
            }
2391
        }
2392
2393
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] ?? [] as $className) {
2394
            $hookObj = GeneralUtility::makeInstance($className);
2395
            if (method_exists($hookObj, 'postProcess')) {
2396
                $previewUrl = $hookObj->postProcess(
2397
                    $previewUrl,
2398
                    $pageUid,
2399
                    $rootLine,
2400
                    $anchorSection,
2401
                    $viewScript,
2402
                    $additionalGetVars,
2403
                    $switchFocus
2404
                );
2405
            }
2406
        }
2407
2408
        return $previewUrl;
2409
    }
2410
2411
    /**
2412
     * Makes click menu link (context sensitive menu)
2413
     *
2414
     * Returns $str wrapped in a link which will activate the context sensitive
2415
     * menu for the record ($table/$uid) or file ($table = file)
2416
     * The link will load the top frame with the parameter "&item" which is the table, uid
2417
     * and context arguments imploded by "|": rawurlencode($table.'|'.$uid.'|'.$context)
2418
     *
2419
     * @param string $content String to be wrapped in link, typ. image tag.
2420
     * @param string $table Table name/File path. If the icon is for a database
2421
     * record, enter the tablename from $GLOBALS['TCA']. If a file then enter
2422
     * the absolute filepath
2423
     * @param int|string $uid If icon is for database record this is the UID for the
2424
     * record from $table or identifier for sys_file record
2425
     * @param string $context Set tree if menu is called from tree view
2426
     * @param string $_addParams NOT IN USE
2427
     * @param string $_enDisItems NOT IN USE
2428
     * @param bool $returnTagParameters If set, will return only the onclick
2429
     * JavaScript, not the whole link.
2430
     *
2431
     * @return string The link wrapped input string.
2432
     */
2433
    public static function wrapClickMenuOnIcon(
2434
        $content,
2435
        $table,
2436
        $uid = 0,
2437
        $context = '',
2438
        $_addParams = '',
2439
        $_enDisItems = '',
2440
        $returnTagParameters = false
2441
    ) {
2442
        $tagParameters = [
2443
            'class' => 't3js-contextmenutrigger',
2444
            'data-table' => $table,
2445
            'data-uid' => $uid,
2446
            'data-context' => $context
2447
        ];
2448
2449
        if ($returnTagParameters) {
2450
            return $tagParameters;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $tagParameters returns the type array<string,integer|string> which is incompatible with the documented return type string.
Loading history...
2451
        }
2452
        return '<a href="#" ' . GeneralUtility::implodeAttributes($tagParameters, true) . '>' . $content . '</a>';
2453
    }
2454
2455
    /**
2456
     * Returns a URL with a command to TYPO3 Datahandler
2457
     *
2458
     * @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
2459
     * @param string $redirectUrl Redirect URL, default is to use GeneralUtility::getIndpEnv('REQUEST_URI')
2460
     * @return string
2461
     */
2462
    public static function getLinkToDataHandlerAction($parameters, $redirectUrl = '')
2463
    {
2464
        $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
2465
        $url = (string)$uriBuilder->buildUriFromRoute('tce_db') . $parameters . '&redirect=';
2466
        $url .= rawurlencode($redirectUrl ?: GeneralUtility::getIndpEnv('REQUEST_URI'));
2467
        return $url;
2468
    }
2469
2470
    /**
2471
     * Returns a selector box "function menu" for a module
2472
     * See Inside TYPO3 for details about how to use / make Function menus
2473
     *
2474
     * @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=...
2475
     * @param string $elementName The form elements name, probably something like "SET[...]
2476
     * @param string $currentValue The value to be selected currently.
2477
     * @param array $menuItems An array with the menu items for the selector box
2478
     * @param string $script The script to send the &id to, if empty it's automatically found
2479
     * @param string $addParams Additional parameters to pass to the script.
2480
     * @return string HTML code for selector box
2481
     */
2482
    public static function getFuncMenu(
2483
        $mainParams,
2484
        $elementName,
2485
        $currentValue,
2486
        $menuItems,
2487
        $script = '',
2488
        $addParams = ''
2489
    ) {
2490
        if (!is_array($menuItems) || count($menuItems) <= 1) {
0 ignored issues
show
introduced by
The condition is_array($menuItems) is always true.
Loading history...
2491
            return '';
2492
        }
2493
        $scriptUrl = self::buildScriptUrl($mainParams, $addParams, $script);
2494
        $options = [];
2495
        foreach ($menuItems as $value => $label) {
2496
            $options[] = '<option value="'
2497
                . htmlspecialchars($value) . '"'
2498
                . ((string)$currentValue === (string)$value ? ' selected="selected"' : '') . '>'
2499
                . htmlspecialchars($label, ENT_COMPAT, 'UTF-8', false) . '</option>';
2500
        }
2501
        $dataMenuIdentifier = str_replace(['SET[', ']'], '', $elementName);
2502
        $dataMenuIdentifier = GeneralUtility::camelCaseToLowerCaseUnderscored($dataMenuIdentifier);
2503
        $dataMenuIdentifier = str_replace('_', '-', $dataMenuIdentifier);
2504
        if (!empty($options)) {
2505
            // relies on module 'TYPO3/CMS/Backend/ActionDispatcher'
2506
            $attributes = GeneralUtility::implodeAttributes([
2507
                'name' => $elementName,
2508
                'class' => 'form-control',
2509
                'data-menu-identifier' => $dataMenuIdentifier,
2510
                'data-global-event' => 'change',
2511
                'data-action-navigate' => '$data=~s/$value/',
2512
                'data-navigate-value' => $scriptUrl . '&' . $elementName . '=${value}',
2513
            ], true);
2514
            return sprintf(
2515
                '<select %s>%s</select>',
2516
                $attributes,
2517
                implode('', $options)
2518
            );
2519
        }
2520
        return '';
2521
    }
2522
2523
    /**
2524
     * Returns a selector box to switch the view
2525
     * Based on BackendUtility::getFuncMenu() but done as new function because it has another purpose.
2526
     * Mingling with getFuncMenu would harm the docHeader Menu.
2527
     *
2528
     * @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=...
2529
     * @param string $elementName The form elements name, probably something like "SET[...]
2530
     * @param string $currentValue The value to be selected currently.
2531
     * @param array $menuItems An array with the menu items for the selector box
2532
     * @param string $script The script to send the &id to, if empty it's automatically found
2533
     * @param string $addParams Additional parameters to pass to the script.
2534
     * @return string HTML code for selector box
2535
     */
2536
    public static function getDropdownMenu(
2537
        $mainParams,
2538
        $elementName,
2539
        $currentValue,
2540
        $menuItems,
2541
        $script = '',
2542
        $addParams = ''
2543
    ) {
2544
        if (!is_array($menuItems) || count($menuItems) <= 1) {
0 ignored issues
show
introduced by
The condition is_array($menuItems) is always true.
Loading history...
2545
            return '';
2546
        }
2547
        $scriptUrl = self::buildScriptUrl($mainParams, $addParams, $script);
2548
        $options = [];
2549
        foreach ($menuItems as $value => $label) {
2550
            $options[] = '<option value="'
2551
                . htmlspecialchars($value) . '"'
2552
                . ((string)$currentValue === (string)$value ? ' selected="selected"' : '') . '>'
2553
                . htmlspecialchars($label, ENT_COMPAT, 'UTF-8', false) . '</option>';
2554
        }
2555
        $dataMenuIdentifier = str_replace(['SET[', ']'], '', $elementName);
2556
        $dataMenuIdentifier = GeneralUtility::camelCaseToLowerCaseUnderscored($dataMenuIdentifier);
2557
        $dataMenuIdentifier = str_replace('_', '-', $dataMenuIdentifier);
2558
        if (!empty($options)) {
2559
            // relies on module 'TYPO3/CMS/Backend/ActionDispatcher'
2560
            $attributes = GeneralUtility::implodeAttributes([
2561
                'name' => $elementName,
2562
                'data-menu-identifier' => $dataMenuIdentifier,
2563
                'data-global-event' => 'change',
2564
                'data-action-navigate' => '$data=~s/$value/',
2565
                'data-navigate-value' => $scriptUrl . '&' . $elementName . '=${value}',
2566
            ], true);
2567
            return '
2568
			<div class="form-group">
2569
				<!-- Function Menu of module -->
2570
				<select class="form-control input-sm" ' . $attributes . '>
2571
					' . implode(LF, $options) . '
2572
				</select>
2573
			</div>
2574
						';
2575
        }
2576
        return '';
2577
    }
2578
2579
    /**
2580
     * Checkbox function menu.
2581
     * Works like ->getFuncMenu() but takes no $menuItem array since this is a simple checkbox.
2582
     *
2583
     * @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=...
2584
     * @param string $elementName The form elements name, probably something like "SET[...]
2585
     * @param string $currentValue The value to be selected currently.
2586
     * @param string $script The script to send the &id to, if empty it's automatically found
2587
     * @param string $addParams Additional parameters to pass to the script.
2588
     * @param string $tagParams Additional attributes for the checkbox input tag
2589
     * @return string HTML code for checkbox
2590
     * @see getFuncMenu()
2591
     */
2592
    public static function getFuncCheck(
2593
        $mainParams,
2594
        $elementName,
2595
        $currentValue,
2596
        $script = '',
2597
        $addParams = '',
2598
        $tagParams = ''
2599
    ) {
2600
        // relies on module 'TYPO3/CMS/Backend/ActionDispatcher'
2601
        $scriptUrl = self::buildScriptUrl($mainParams, $addParams, $script);
2602
        $attributes = GeneralUtility::implodeAttributes([
2603
            'type' => 'checkbox',
2604
            'class' => 'checkbox',
2605
            'name' => $elementName,
2606
            'value' => 1,
2607
            'data-global-event' => 'change',
2608
            'data-action-navigate' => '$data=~s/$value/',
2609
            'data-navigate-value' => sprintf('%s&%s=${value}', $scriptUrl, $elementName),
2610
        ], true);
2611
        return
2612
            '<input ' . $attributes .
2613
            ($currentValue ? ' checked="checked"' : '') .
2614
            ($tagParams ? ' ' . $tagParams : '') .
2615
            ' />';
2616
    }
2617
2618
    /**
2619
     * Input field function menu
2620
     * Works like ->getFuncMenu() / ->getFuncCheck() but displays an input field instead which updates the script "onchange"
2621
     *
2622
     * @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=...
2623
     * @param string $elementName The form elements name, probably something like "SET[...]
2624
     * @param string $currentValue The value to be selected currently.
2625
     * @param int $size Relative size of input field, max is 48
2626
     * @param string $script The script to send the &id to, if empty it's automatically found
2627
     * @param string $addParams Additional parameters to pass to the script.
2628
     * @return string HTML code for input text field.
2629
     * @see getFuncMenu()
2630
     */
2631
    public static function getFuncInput(
2632
        $mainParams,
2633
        $elementName,
2634
        $currentValue,
2635
        $size = 10,
2636
        $script = '',
2637
        $addParams = ''
2638
    ) {
2639
        $scriptUrl = self::buildScriptUrl($mainParams, $addParams, $script);
2640
        $onChange = 'window.location.href = ' . GeneralUtility::quoteJSvalue($scriptUrl . '&' . $elementName . '=') . '+escape(this.value);';
2641
        return '<input type="text" class="form-control" name="' . $elementName . '" value="' . htmlspecialchars($currentValue) . '" onchange="' . htmlspecialchars($onChange) . '" />';
2642
    }
2643
2644
    /**
2645
     * Builds the URL to the current script with given arguments
2646
     *
2647
     * @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=...
2648
     * @param string $addParams Additional parameters to pass to the script.
2649
     * @param string $script The script to send the &id to, if empty it's automatically found
2650
     * @return string The complete script URL
2651
     */
2652
    protected static function buildScriptUrl($mainParams, $addParams, $script = '')
2653
    {
2654
        if (!is_array($mainParams)) {
2655
            $mainParams = ['id' => $mainParams];
2656
        }
2657
        if (!$script) {
2658
            $script = PathUtility::basename(Environment::getCurrentScript());
2659
        }
2660
2661
        if ($routePath = GeneralUtility::_GP('route')) {
2662
            $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
2663
            $scriptUrl = (string)$uriBuilder->buildUriFromRoutePath($routePath, $mainParams);
2664
            $scriptUrl .= $addParams;
2665
        } else {
2666
            $scriptUrl = $script . HttpUtility::buildQueryString($mainParams, '?') . $addParams;
2667
        }
2668
2669
        return $scriptUrl;
2670
    }
2671
2672
    /**
2673
     * Call to update the page tree frame (or something else..?) after
2674
     * use 'updatePageTree' as a first parameter will set the page tree to be updated.
2675
     *
2676
     * @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.
2677
     * @param mixed $params Additional information for the update signal, used to only refresh a branch of the tree
2678
     * @see BackendUtility::getUpdateSignalCode()
2679
     */
2680
    public static function setUpdateSignal($set = '', $params = '')
2681
    {
2682
        $beUser = static::getBackendUserAuthentication();
2683
        $modData = $beUser->getModuleData(
2684
            \TYPO3\CMS\Backend\Utility\BackendUtility::class . '::getUpdateSignal',
2685
            'ses'
2686
        );
2687
        if ($set) {
2688
            $modData[$set] = [
2689
                'set' => $set,
2690
                'parameter' => $params
2691
            ];
2692
        } else {
2693
            // clear the module data
2694
            $modData = [];
2695
        }
2696
        $beUser->pushModuleData(\TYPO3\CMS\Backend\Utility\BackendUtility::class . '::getUpdateSignal', $modData);
2697
    }
2698
2699
    /**
2700
     * Call to update the page tree frame (or something else..?) if this is set by the function
2701
     * setUpdateSignal(). It will return some JavaScript that does the update
2702
     *
2703
     * @return string HTML javascript code
2704
     * @see BackendUtility::setUpdateSignal()
2705
     */
2706
    public static function getUpdateSignalCode()
2707
    {
2708
        $signals = [];
2709
        $modData = static::getBackendUserAuthentication()->getModuleData(
2710
            \TYPO3\CMS\Backend\Utility\BackendUtility::class . '::getUpdateSignal',
2711
            'ses'
2712
        );
2713
        if (empty($modData)) {
2714
            return '';
2715
        }
2716
        // Hook: Allows to let TYPO3 execute your JS code
2717
        $updateSignals = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['updateSignalHook'] ?? [];
2718
        // Loop through all setUpdateSignals and get the JS code
2719
        foreach ($modData as $set => $val) {
2720
            if (isset($updateSignals[$set])) {
2721
                $params = ['set' => $set, 'parameter' => $val['parameter'], 'JScode' => ''];
2722
                $ref = null;
2723
                GeneralUtility::callUserFunction($updateSignals[$set], $params, $ref);
2724
                $signals[] = $params['JScode'];
2725
            } else {
2726
                switch ($set) {
2727
                    case 'updatePageTree':
2728
                        $signals[] = '
2729
								if (top && top.TYPO3.Backend && top.TYPO3.Backend.NavigationContainer.PageTree) {
2730
									top.TYPO3.Backend.NavigationContainer.PageTree.refreshTree();
2731
								}
2732
							';
2733
                        break;
2734
                    case 'updateFolderTree':
2735
                        $signals[] = '
2736
								if (top && top.nav_frame && top.nav_frame.location) {
2737
									top.nav_frame.location.reload(true);
2738
								}';
2739
                        break;
2740
                    case 'updateModuleMenu':
2741
                        $signals[] = '
2742
								if (top && top.TYPO3.ModuleMenu && top.TYPO3.ModuleMenu.App) {
2743
									top.TYPO3.ModuleMenu.App.refreshMenu();
2744
								}';
2745
                        break;
2746
                    case 'updateTopbar':
2747
                        $signals[] = '
2748
								if (top && top.TYPO3.Backend && top.TYPO3.Backend.Topbar) {
2749
									top.TYPO3.Backend.Topbar.refresh();
2750
								}';
2751
                        break;
2752
                }
2753
            }
2754
        }
2755
        $content = implode(LF, $signals);
2756
        // For backwards compatibility, should be replaced
2757
        self::setUpdateSignal();
2758
        return $content;
2759
    }
2760
2761
    /**
2762
     * Returns an array which is most backend modules becomes MOD_SETTINGS containing values from function menus etc. determining the function of the module.
2763
     * This is kind of session variable management framework for the backend users.
2764
     * 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
2765
     * Ultimately, see Inside TYPO3 for how to use this function in relation to your modules.
2766
     *
2767
     * @param array $MOD_MENU MOD_MENU is an array that defines the options in menus.
2768
     * @param array $CHANGED_SETTINGS CHANGED_SETTINGS represents the array used when passing values to the script from the menus.
2769
     * @param string $modName modName is the name of this module. Used to get the correct module data.
2770
     * @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.
2771
     * @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.
2772
     * @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)
2773
     * @throws \RuntimeException
2774
     * @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
2775
     */
2776
    public static function getModuleData(
2777
        $MOD_MENU,
2778
        $CHANGED_SETTINGS,
2779
        $modName,
2780
        $type = '',
2781
        $dontValidateList = '',
2782
        $setDefaultList = ''
2783
    ) {
2784
        if ($modName && is_string($modName)) {
2785
            // Getting stored user-data from this module:
2786
            $beUser = static::getBackendUserAuthentication();
2787
            $settings = $beUser->getModuleData($modName, $type);
2788
            $changed = 0;
2789
            if (!is_array($settings)) {
2790
                $changed = 1;
2791
                $settings = [];
2792
            }
2793
            if (is_array($MOD_MENU)) {
0 ignored issues
show
introduced by
The condition is_array($MOD_MENU) is always true.
Loading history...
2794
                foreach ($MOD_MENU as $key => $var) {
2795
                    // If a global var is set before entering here. eg if submitted, then it's substituting the current value the array.
2796
                    if (is_array($CHANGED_SETTINGS) && isset($CHANGED_SETTINGS[$key])) {
2797
                        if (is_array($CHANGED_SETTINGS[$key])) {
2798
                            $serializedSettings = serialize($CHANGED_SETTINGS[$key]);
2799
                            if ((string)$settings[$key] !== $serializedSettings) {
2800
                                $settings[$key] = $serializedSettings;
2801
                                $changed = 1;
2802
                            }
2803
                        } else {
2804
                            if ((string)$settings[$key] !== (string)$CHANGED_SETTINGS[$key]) {
2805
                                $settings[$key] = $CHANGED_SETTINGS[$key];
2806
                                $changed = 1;
2807
                            }
2808
                        }
2809
                    }
2810
                    // If the $var is an array, which denotes the existence of a menu, we check if the value is permitted
2811
                    if (is_array($var) && (!$dontValidateList || !GeneralUtility::inList($dontValidateList, $key))) {
2812
                        // If the setting is an array or not present in the menu-array, MOD_MENU, then the default value is inserted.
2813
                        if (is_array($settings[$key]) || !isset($MOD_MENU[$key][$settings[$key]])) {
2814
                            $settings[$key] = (string)key($var);
2815
                            $changed = 1;
2816
                        }
2817
                    }
2818
                    // Sets default values (only strings/checkboxes, not menus)
2819
                    if ($setDefaultList && !is_array($var)) {
2820
                        if (GeneralUtility::inList($setDefaultList, $key) && !isset($settings[$key])) {
2821
                            $settings[$key] = (string)$var;
2822
                        }
2823
                    }
2824
                }
2825
            } else {
2826
                throw new \RuntimeException('No menu', 1568119229);
2827
            }
2828
            if ($changed) {
2829
                $beUser->pushModuleData($modName, $settings);
2830
            }
2831
            return $settings;
2832
        }
2833
        throw new \RuntimeException('Wrong module name "' . $modName . '"', 1568119221);
2834
    }
2835
2836
    /*******************************************
2837
     *
2838
     * Core
2839
     *
2840
     *******************************************/
2841
    /**
2842
     * Unlock or Lock a record from $table with $uid
2843
     * If $table and $uid is not set, then all locking for the current BE_USER is removed!
2844
     *
2845
     * @param string $table Table name
2846
     * @param int $uid Record uid
2847
     * @param int $pid Record pid
2848
     * @internal
2849
     */
2850
    public static function lockRecords($table = '', $uid = 0, $pid = 0)
2851
    {
2852
        $beUser = static::getBackendUserAuthentication();
2853
        if (isset($beUser->user['uid'])) {
2854
            $userId = (int)$beUser->user['uid'];
2855
            if ($table && $uid) {
2856
                $fieldsValues = [
2857
                    'userid' => $userId,
2858
                    'feuserid' => 0,
2859
                    'tstamp' => $GLOBALS['EXEC_TIME'],
2860
                    'record_table' => $table,
2861
                    'record_uid' => $uid,
2862
                    'username' => $beUser->user['username'],
2863
                    'record_pid' => $pid
2864
                ];
2865
                GeneralUtility::makeInstance(ConnectionPool::class)
2866
                    ->getConnectionForTable('sys_lockedrecords')
2867
                    ->insert(
2868
                        'sys_lockedrecords',
2869
                        $fieldsValues
2870
                    );
2871
            } else {
2872
                GeneralUtility::makeInstance(ConnectionPool::class)
2873
                    ->getConnectionForTable('sys_lockedrecords')
2874
                    ->delete(
2875
                        'sys_lockedrecords',
2876
                        ['userid' => (int)$userId]
2877
                    );
2878
            }
2879
        }
2880
    }
2881
2882
    /**
2883
     * Returns information about whether the record from table, $table, with uid, $uid is currently locked
2884
     * (edited by another user - which should issue a warning).
2885
     * Notice: Locking is not strictly carried out since locking is abandoned when other backend scripts
2886
     * are activated - which means that a user CAN have a record "open" without having it locked.
2887
     * So this just serves as a warning that counts well in 90% of the cases, which should be sufficient.
2888
     *
2889
     * @param string $table Table name
2890
     * @param int $uid Record uid
2891
     * @return array|bool
2892
     * @internal
2893
     */
2894
    public static function isRecordLocked($table, $uid)
2895
    {
2896
        $runtimeCache = self::getRuntimeCache();
2897
        $cacheId = 'backend-recordLocked';
2898
        $recordLockedCache = $runtimeCache->get($cacheId);
2899
        if ($recordLockedCache !== false) {
2900
            $lockedRecords = $recordLockedCache;
2901
        } else {
2902
            $lockedRecords = [];
2903
2904
            $queryBuilder = static::getQueryBuilderForTable('sys_lockedrecords');
2905
            $result = $queryBuilder
2906
                ->select('*')
2907
                ->from('sys_lockedrecords')
2908
                ->where(
2909
                    $queryBuilder->expr()->neq(
2910
                        'sys_lockedrecords.userid',
2911
                        $queryBuilder->createNamedParameter(
2912
                            static::getBackendUserAuthentication()->user['uid'],
2913
                            \PDO::PARAM_INT
2914
                        )
2915
                    ),
2916
                    $queryBuilder->expr()->gt(
2917
                        'sys_lockedrecords.tstamp',
2918
                        $queryBuilder->createNamedParameter(
2919
                            $GLOBALS['EXEC_TIME'] - 2 * 3600,
2920
                            \PDO::PARAM_INT
2921
                        )
2922
                    )
2923
                )
2924
                ->execute();
2925
2926
            $lang = static::getLanguageService();
2927
            while ($row = $result->fetch()) {
2928
                // Get the type of the user that locked this record:
2929
                if ($row['userid']) {
2930
                    $userTypeLabel = 'beUser';
2931
                } elseif ($row['feuserid']) {
2932
                    $userTypeLabel = 'feUser';
2933
                } else {
2934
                    $userTypeLabel = 'user';
2935
                }
2936
                $userType = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.' . $userTypeLabel);
2937
                // Get the username (if available):
2938
                if ($row['username']) {
2939
                    $userName = $row['username'];
2940
                } else {
2941
                    $userName = $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.unknownUser');
2942
                }
2943
                $lockedRecords[$row['record_table'] . ':' . $row['record_uid']] = $row;
2944
                $lockedRecords[$row['record_table'] . ':' . $row['record_uid']]['msg'] = sprintf(
2945
                    $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.lockedRecordUser'),
2946
                    $userType,
2947
                    $userName,
2948
                    self::calcAge(
2949
                        $GLOBALS['EXEC_TIME'] - $row['tstamp'],
2950
                        $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears')
2951
                    )
2952
                );
2953
                if ($row['record_pid'] && !isset($lockedRecords[$row['record_table'] . ':' . $row['record_pid']])) {
2954
                    $lockedRecords['pages:' . $row['record_pid']]['msg'] = sprintf(
2955
                        $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.lockedRecordUser_content'),
2956
                        $userType,
2957
                        $userName,
2958
                        self::calcAge(
2959
                            $GLOBALS['EXEC_TIME'] - $row['tstamp'],
2960
                            $lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears')
2961
                        )
2962
                    );
2963
                }
2964
            }
2965
            $runtimeCache->set($cacheId, $lockedRecords);
2966
        }
2967
2968
        return $lockedRecords[$table . ':' . $uid] ?? false;
2969
    }
2970
2971
    /**
2972
     * Returns TSConfig for the TCEFORM object in Page TSconfig.
2973
     * Used in TCEFORMs
2974
     *
2975
     * @param string $table Table name present in TCA
2976
     * @param array $row Row from table
2977
     * @return array
2978
     */
2979
    public static function getTCEFORM_TSconfig($table, $row)
2980
    {
2981
        self::fixVersioningPid($table, $row);
2982
        $res = [];
2983
        // Get main config for the table
2984
        [$TScID, $cPid] = self::getTSCpid($table, $row['uid'], $row['pid']);
2985
        if ($TScID >= 0) {
2986
            $tsConfig = static::getPagesTSconfig($TScID)['TCEFORM.'][$table . '.'] ?? [];
2987
            $typeVal = self::getTCAtypeValue($table, $row);
2988
            foreach ($tsConfig as $key => $val) {
2989
                if (is_array($val)) {
2990
                    $fieldN = substr($key, 0, -1);
2991
                    $res[$fieldN] = $val;
2992
                    unset($res[$fieldN]['types.']);
2993
                    if ((string)$typeVal !== '' && is_array($val['types.'][$typeVal . '.'])) {
2994
                        ArrayUtility::mergeRecursiveWithOverrule($res[$fieldN], $val['types.'][$typeVal . '.']);
2995
                    }
2996
                }
2997
            }
2998
        }
2999
        $res['_CURRENT_PID'] = $cPid;
3000
        $res['_THIS_UID'] = $row['uid'];
3001
        // So the row will be passed to foreign_table_where_query()
3002
        $res['_THIS_ROW'] = $row;
3003
        return $res;
3004
    }
3005
3006
    /**
3007
     * Find the real PID of the record (with $uid from $table).
3008
     * 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).
3009
     * NOTICE: Make sure that the input PID is never negative because the record was an offline version!
3010
     * Therefore, you should always use BackendUtility::fixVersioningPid($table,$row); on the data you input before calling this function!
3011
     *
3012
     * @param string $table Table name
3013
     * @param int $uid Record uid
3014
     * @param int $pid Record pid, could be negative then pointing to a record from same table whose pid to find and return
3015
     * @return int
3016
     * @internal
3017
     * @see \TYPO3\CMS\Core\DataHandling\DataHandler::copyRecord()
3018
     * @see \TYPO3\CMS\Backend\Utility\BackendUtility::getTSCpid()
3019
     */
3020
    public static function getTSconfig_pidValue($table, $uid, $pid)
3021
    {
3022
        // If pid is an integer this takes precedence in our lookup.
3023
        if (MathUtility::canBeInterpretedAsInteger($pid)) {
3024
            $thePidValue = (int)$pid;
3025
            // If ref to another record, look that record up.
3026
            if ($thePidValue < 0) {
3027
                $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

3027
                $pidRec = self::getRecord($table, /** @scrutinizer ignore-type */ abs($thePidValue), 'pid');
Loading history...
3028
                $thePidValue = is_array($pidRec) ? $pidRec['pid'] : -2;
3029
            }
3030
        } else {
3031
            // Try to fetch the record pid from uid. If the uid is 'NEW...' then this will of course return nothing
3032
            $rr = self::getRecord($table, $uid);
3033
            $thePidValue = null;
3034
            if (is_array($rr)) {
3035
                // First check if the pid is -1 which means it is a workspaced element. Get the "real" record:
3036
                if ($rr['pid'] == '-1') {
3037
                    $rr = self::getRecord($table, $rr['t3ver_oid'], 'pid');
3038
                    if (is_array($rr)) {
3039
                        $thePidValue = $rr['pid'];
3040
                    }
3041
                } else {
3042
                    // Returning the "pid" of the record
3043
                    $thePidValue = $rr['pid'];
3044
                }
3045
            }
3046
            if (!$thePidValue) {
3047
                // Returns -1 if the record with this pid was not found.
3048
                $thePidValue = -1;
3049
            }
3050
        }
3051
        return $thePidValue;
3052
    }
3053
3054
    /**
3055
     * Return the real pid of a record and caches the result.
3056
     * The non-cached method needs database queries to do the job, so this method
3057
     * can be used if code sometimes calls the same record multiple times to save
3058
     * some queries. This should not be done if the calling code may change the
3059
     * same record meanwhile.
3060
     *
3061
     * @param string $table Tablename
3062
     * @param string $uid UID value
3063
     * @param string $pid PID value
3064
     * @return array Array of two integers; first is the real PID of a record, second is the PID value for TSconfig.
3065
     */
3066
    public static function getTSCpidCached($table, $uid, $pid)
3067
    {
3068
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
3069
        $firstLevelCache = $runtimeCache->get('backendUtilityTscPidCached') ?: [];
3070
        $key = $table . ':' . $uid . ':' . $pid;
3071
        if (!isset($firstLevelCache[$key])) {
3072
            $firstLevelCache[$key] = static::getTSCpid($table, $uid, $pid);
0 ignored issues
show
Bug introduced by
$pid of type string is incompatible with the type integer expected by parameter $pid of TYPO3\CMS\Backend\Utilit...endUtility::getTSCpid(). ( Ignorable by Annotation )

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

3072
            $firstLevelCache[$key] = static::getTSCpid($table, $uid, /** @scrutinizer ignore-type */ $pid);
Loading history...
Bug introduced by
$uid of type string is incompatible with the type integer expected by parameter $uid of TYPO3\CMS\Backend\Utilit...endUtility::getTSCpid(). ( Ignorable by Annotation )

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

3072
            $firstLevelCache[$key] = static::getTSCpid($table, /** @scrutinizer ignore-type */ $uid, $pid);
Loading history...
3073
            $runtimeCache->set('backendUtilityTscPidCached', $firstLevelCache);
3074
        }
3075
        return $firstLevelCache[$key];
3076
    }
3077
3078
    /**
3079
     * 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.
3080
     *
3081
     * @param string $table Table name
3082
     * @param int $uid Record uid
3083
     * @param int $pid Record pid
3084
     * @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,
3085
     * second value is the PID value for TSconfig (uid if table is pages, otherwise the pid)
3086
     * @internal
3087
     * @see \TYPO3\CMS\Core\DataHandling\DataHandler::setHistory()
3088
     * @see \TYPO3\CMS\Core\DataHandling\DataHandler::process_datamap()
3089
     */
3090
    public static function getTSCpid($table, $uid, $pid)
3091
    {
3092
        // If pid is negative (referring to another record) the pid of the other record is fetched and returned.
3093
        $cPid = self::getTSconfig_pidValue($table, $uid, $pid);
3094
        // $TScID is the id of $table = pages, else it's the pid of the record.
3095
        $TScID = $table === 'pages' && MathUtility::canBeInterpretedAsInteger($uid) ? $uid : $cPid;
3096
        return [$TScID, $cPid];
3097
    }
3098
3099
    /**
3100
     * Returns soft-reference parser for the softRef processing type
3101
     * Usage: $softRefObj = BackendUtility::softRefParserObj('[parser key]');
3102
     *
3103
     * @param string $spKey softRef parser key
3104
     * @return mixed If available, returns Soft link parser object, otherwise false.
3105
     * @internal should only be used from within TYPO3 Core
3106
     */
3107
    public static function softRefParserObj($spKey)
3108
    {
3109
        $className = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser'][$spKey] ?? false;
3110
        if ($className) {
3111
            return GeneralUtility::makeInstance($className);
3112
        }
3113
        return false;
3114
    }
3115
3116
    /**
3117
     * Gets an instance of the runtime cache.
3118
     *
3119
     * @return FrontendInterface
3120
     */
3121
    protected static function getRuntimeCache()
3122
    {
3123
        return GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
3124
    }
3125
3126
    /**
3127
     * Returns array of soft parser references
3128
     *
3129
     * @param string $parserList softRef parser list
3130
     * @return array|bool Array where the parser key is the key and the value is the parameter string, FALSE if no parsers were found
3131
     * @throws \InvalidArgumentException
3132
     * @internal should only be used from within TYPO3 Core
3133
     */
3134
    public static function explodeSoftRefParserList($parserList)
3135
    {
3136
        // Return immediately if list is blank:
3137
        if ((string)$parserList === '') {
3138
            return false;
3139
        }
3140
3141
        $runtimeCache = self::getRuntimeCache();
3142
        $cacheId = 'backend-softRefList-' . md5($parserList);
3143
        $parserListCache = $runtimeCache->get($cacheId);
3144
        if ($parserListCache !== false) {
3145
            return $parserListCache;
3146
        }
3147
3148
        // Otherwise parse the list:
3149
        $keyList = GeneralUtility::trimExplode(',', $parserList, true);
3150
        $output = [];
3151
        foreach ($keyList as $val) {
3152
            $reg = [];
3153
            if (preg_match('/^([[:alnum:]_-]+)\\[(.*)\\]$/', $val, $reg)) {
3154
                $output[$reg[1]] = GeneralUtility::trimExplode(';', $reg[2], true);
3155
            } else {
3156
                $output[$val] = '';
3157
            }
3158
        }
3159
        $runtimeCache->set($cacheId, $output);
3160
        return $output;
3161
    }
3162
3163
    /**
3164
     * Returns TRUE if $modName is set and is found as a main- or submodule in $TBE_MODULES array
3165
     *
3166
     * @param string $modName Module name
3167
     * @return bool
3168
     */
3169
    public static function isModuleSetInTBE_MODULES($modName)
3170
    {
3171
        $loaded = [];
3172
        foreach ($GLOBALS['TBE_MODULES'] as $mkey => $list) {
3173
            $loaded[$mkey] = 1;
3174
            if (!is_array($list) && trim($list)) {
3175
                $subList = GeneralUtility::trimExplode(',', $list, true);
3176
                foreach ($subList as $skey) {
3177
                    $loaded[$mkey . '_' . $skey] = 1;
3178
                }
3179
            }
3180
        }
3181
        return $modName && isset($loaded[$modName]);
3182
    }
3183
3184
    /**
3185
     * Counting references to a record/file
3186
     *
3187
     * @param string $table Table name (or "_FILE" if its a file)
3188
     * @param string $ref Reference: If table, then int-uid, if _FILE, then file reference (relative to Environment::getPublicPath())
3189
     * @param string $msg Message with %s, eg. "There were %s records pointing to this file!
3190
     * @param string|null $count Reference count
3191
     * @return string Output string (or int count value if no msg string specified)
3192
     */
3193
    public static function referenceCount($table, $ref, $msg = '', $count = null)
3194
    {
3195
        if ($count === null) {
3196
3197
            // Build base query
3198
            $queryBuilder = static::getQueryBuilderForTable('sys_refindex');
3199
            $queryBuilder
3200
                ->count('*')
3201
                ->from('sys_refindex')
3202
                ->where(
3203
                    $queryBuilder->expr()->eq('ref_table', $queryBuilder->createNamedParameter($table, \PDO::PARAM_STR)),
3204
                    $queryBuilder->expr()->eq('deleted', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
3205
                );
3206
3207
            // Look up the path:
3208
            if ($table === '_FILE') {
3209
                if (!GeneralUtility::isFirstPartOfStr($ref, Environment::getPublicPath())) {
3210
                    return '';
3211
                }
3212
3213
                $ref = PathUtility::stripPathSitePrefix($ref);
3214
                $queryBuilder->andWhere(
3215
                    $queryBuilder->expr()->eq('ref_string', $queryBuilder->createNamedParameter($ref, \PDO::PARAM_STR))
3216
                );
3217
            } else {
3218
                $queryBuilder->andWhere(
3219
                    $queryBuilder->expr()->eq('ref_uid', $queryBuilder->createNamedParameter($ref, \PDO::PARAM_INT))
3220
                );
3221
                if ($table === 'sys_file') {
3222
                    $queryBuilder->andWhere($queryBuilder->expr()->neq('tablename', $queryBuilder->quote('sys_file_metadata')));
3223
                }
3224
            }
3225
3226
            $count = $queryBuilder->execute()->fetchColumn(0);
3227
        }
3228
3229
        if ($count) {
3230
            return $msg ? sprintf($msg, $count) : $count;
3231
        }
3232
        return $msg ? '' : 0;
3233
    }
3234
3235
    /**
3236
     * Counting translations of records
3237
     *
3238
     * @param string $table Table name
3239
     * @param string $ref Reference: the record's uid
3240
     * @param string $msg Message with %s, eg. "This record has %s translation(s) which will be deleted, too!
3241
     * @return string Output string (or int count value if no msg string specified)
3242
     */
3243
    public static function translationCount($table, $ref, $msg = '')
3244
    {
3245
        $count = null;
3246
        if ($GLOBALS['TCA'][$table]['ctrl']['languageField']
3247
            && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
3248
        ) {
3249
            $queryBuilder = static::getQueryBuilderForTable($table);
3250
            $queryBuilder->getRestrictions()
3251
                ->removeAll()
3252
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
3253
3254
            $count = (int)$queryBuilder
3255
                ->count('*')
3256
                ->from($table)
3257
                ->where(
3258
                    $queryBuilder->expr()->eq(
3259
                        $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'],
3260
                        $queryBuilder->createNamedParameter($ref, \PDO::PARAM_INT)
3261
                    ),
3262
                    $queryBuilder->expr()->neq(
3263
                        $GLOBALS['TCA'][$table]['ctrl']['languageField'],
3264
                        $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
3265
                    )
3266
                )
3267
                ->execute()
3268
                ->fetchColumn(0);
3269
        }
3270
3271
        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...
3272
            return sprintf($msg, $count);
3273
        }
3274
3275
        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...
3276
            return $msg ? sprintf($msg, $count) : $count;
3277
        }
3278
        return $msg ? '' : 0;
3279
    }
3280
3281
    /*******************************************
3282
     *
3283
     * Workspaces / Versioning
3284
     *
3285
     *******************************************/
3286
    /**
3287
     * Select all versions of a record, ordered by latest created version (uid DESC)
3288
     *
3289
     * @param string $table Table name to select from
3290
     * @param int $uid Record uid for which to find versions.
3291
     * @param string $fields Field list to select
3292
     * @param int|null $workspace Search in workspace ID and Live WS, if 0 search only in LiveWS, if NULL search in all WS.
3293
     * @param bool $includeDeletedRecords If set, deleted-flagged versions are included! (Only for clean-up script!)
3294
     * @param array $row The current record
3295
     * @return array|null Array of versions of table/uid
3296
     * @internal should only be used from within TYPO3 Core
3297
     */
3298
    public static function selectVersionsOfRecord(
3299
        $table,
3300
        $uid,
3301
        $fields = '*',
3302
        $workspace = 0,
3303
        $includeDeletedRecords = false,
3304
        $row = null
3305
    ) {
3306
        $outputRows = [];
3307
        if (static::isTableWorkspaceEnabled($table)) {
3308
            if (is_array($row) && !$includeDeletedRecords) {
3309
                $row['_CURRENT_VERSION'] = true;
3310
                $outputRows[] = $row;
3311
            } else {
3312
                // Select UID version:
3313
                $row = self::getRecord($table, $uid, $fields, '', !$includeDeletedRecords);
3314
                // Add rows to output array:
3315
                if ($row) {
3316
                    $row['_CURRENT_VERSION'] = true;
3317
                    $outputRows[] = $row;
3318
                }
3319
            }
3320
3321
            $queryBuilder = static::getQueryBuilderForTable($table);
3322
            $queryBuilder->getRestrictions()->removeAll();
3323
3324
            // build fields to select
3325
            $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields));
3326
3327
            $queryBuilder
3328
                ->from($table)
3329
                ->where(
3330
                    $queryBuilder->expr()->neq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)),
3331
                    $queryBuilder->expr()->eq('t3ver_oid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT))
3332
                )
3333
                ->orderBy('uid', 'DESC');
3334
3335
            if (!$includeDeletedRecords) {
3336
                $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
3337
            }
3338
3339
            if ($workspace === 0) {
3340
                // Only in Live WS
3341
                $queryBuilder->andWhere(
3342
                    $queryBuilder->expr()->eq(
3343
                        't3ver_wsid',
3344
                        $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
3345
                    )
3346
                );
3347
            } elseif ($workspace !== null) {
3348
                // In Live WS and Workspace with given ID
3349
                $queryBuilder->andWhere(
3350
                    $queryBuilder->expr()->in(
3351
                        't3ver_wsid',
3352
                        $queryBuilder->createNamedParameter([0, (int)$workspace], Connection::PARAM_INT_ARRAY)
3353
                    )
3354
                );
3355
            }
3356
3357
            $rows = $queryBuilder->execute()->fetchAll();
3358
3359
            // Add rows to output array:
3360
            if (is_array($rows)) {
0 ignored issues
show
introduced by
The condition is_array($rows) is always true.
Loading history...
3361
                $outputRows = array_merge($outputRows, $rows);
3362
            }
3363
            return $outputRows;
3364
        }
3365
        return null;
3366
    }
3367
3368
    /**
3369
     * Find page-tree PID for versionized record
3370
     * Will look if the "pid" value of the input record is -1 and if the table supports versioning - if so,
3371
     * it will translate the -1 PID into the PID of the original record
3372
     * Used whenever you are tracking something back, like making the root line.
3373
     * Will only translate if the workspace of the input record matches that of the current user (unless flag set)
3374
     * Principle; Record offline! => Find online?
3375
     *
3376
     * If the record had its pid corrected to the online versions pid, then "_ORIG_pid" is set
3377
     * to the original pid value (-1 of course). The field "_ORIG_pid" is used by various other functions
3378
     * to detect if a record was in fact in a versionized branch.
3379
     *
3380
     * @param string $table Table name
3381
     * @param array $rr Record array passed by reference. As minimum, "pid" and "uid" fields must exist! "t3ver_oid" and "t3ver_wsid" is nice and will save you a DB query.
3382
     * @param bool $ignoreWorkspaceMatch Ignore workspace match
3383
     * @see PageRepository::fixVersioningPid()
3384
     * @internal should only be used from within TYPO3 Core
3385
     */
3386
    public static function fixVersioningPid($table, &$rr, $ignoreWorkspaceMatch = false)
3387
    {
3388
        if (!ExtensionManagementUtility::isLoaded('workspaces')) {
3389
            return;
3390
        }
3391
        if (!static::isTableWorkspaceEnabled($table)) {
3392
            return;
3393
        }
3394
        // Check that the input record is an offline version from a table that supports versioning:
3395
        if (is_array($rr)) {
0 ignored issues
show
introduced by
The condition is_array($rr) is always true.
Loading history...
3396
            // Check values for t3ver_oid and t3ver_wsid:
3397
            if (isset($rr['t3ver_oid']) && isset($rr['t3ver_wsid'])) {
3398
                // If "t3ver_oid" is already a field, just set this:
3399
                $oid = $rr['t3ver_oid'];
3400
                $wsid = $rr['t3ver_wsid'];
3401
            } else {
3402
                $oid = 0;
3403
                $wsid = 0;
3404
                // Otherwise we have to expect "uid" to be in the record and look up based on this:
3405
                $newPidRec = self::getRecord($table, $rr['uid'], 't3ver_oid,t3ver_wsid');
3406
                if (is_array($newPidRec)) {
3407
                    $oid = $newPidRec['t3ver_oid'];
3408
                    $wsid = $newPidRec['t3ver_wsid'];
3409
                }
3410
            }
3411
            // If ID of current online version is found, look up the PID value of that:
3412
            if ($oid
3413
                && ($ignoreWorkspaceMatch || (static::getBackendUserAuthentication() instanceof BackendUserAuthentication && (int)$wsid === (int)static::getBackendUserAuthentication()->workspace))
3414
            ) {
3415
                $oidRec = self::getRecord($table, $oid, 'pid');
3416
                if (is_array($oidRec)) {
3417
                    $rr['_ORIG_pid'] = $rr['pid'];
3418
                    $rr['pid'] = $oidRec['pid'];
3419
                }
3420
                // Use target PID in case of move pointer
3421
                if (
3422
                    !isset($rr['t3ver_state'])
3423
                    || VersionState::cast($rr['t3ver_state'])->equals(VersionState::MOVE_POINTER)
3424
                ) {
3425
                    $movePlaceholder = self::getMovePlaceholder($table, $oid, 'pid');
3426
                    if ($movePlaceholder) {
3427
                        $rr['_ORIG_pid'] = $rr['pid'];
3428
                        $rr['pid'] = $movePlaceholder['pid'];
3429
                    }
3430
                }
3431
            }
3432
        }
3433
    }
3434
3435
    /**
3436
     * Workspace Preview Overlay
3437
     * Generally ALWAYS used when records are selected based on uid or pid.
3438
     * If records are selected on other fields than uid or pid (eg. "email = ....")
3439
     * then usage might produce undesired results and that should be evaluated on individual basis.
3440
     * Principle; Record online! => Find offline?
3441
     * Recently, this function has been modified so it MAY set $row to FALSE.
3442
     * This happens if a version overlay with the move-id pointer is found in which case we would like a backend preview.
3443
     * In other words, you should check if the input record is still an array afterwards when using this function.
3444
     *
3445
     * @param string $table Table name
3446
     * @param array $row Record array passed by reference. As minimum, the "uid" and  "pid" fields must exist! Fake fields cannot exist since the fields in the array is used as field names in the SQL look up. It would be nice to have fields like "t3ver_state" and "t3ver_mode_id" as well to avoid a new lookup inside movePlhOL().
3447
     * @param int $wsid Workspace ID, if not specified will use static::getBackendUserAuthentication()->workspace
3448
     * @param bool $unsetMovePointers If TRUE the function does not return a "pointer" row for moved records in a workspace
3449
     * @see fixVersioningPid()
3450
     */
3451
    public static function workspaceOL($table, &$row, $wsid = -99, $unsetMovePointers = false)
3452
    {
3453
        if (!ExtensionManagementUtility::isLoaded('workspaces')) {
3454
            return;
3455
        }
3456
        // If this is FALSE the placeholder is shown raw in the backend.
3457
        // I don't know if this move can be useful for users to toggle. Technically it can help debugging.
3458
        $previewMovePlaceholders = true;
3459
        // Initialize workspace ID
3460
        if ($wsid == -99 && static::getBackendUserAuthentication() instanceof BackendUserAuthentication) {
3461
            $wsid = static::getBackendUserAuthentication()->workspace;
3462
        }
3463
        // Check if workspace is different from zero and record is set:
3464
        if ($wsid !== 0 && is_array($row)) {
3465
            // Check if input record is a move-placeholder and if so, find the pointed-to live record:
3466
            $movePldSwap = null;
3467
            $orig_uid = 0;
3468
            $orig_pid = 0;
3469
            if ($previewMovePlaceholders) {
0 ignored issues
show
introduced by
The condition $previewMovePlaceholders is always true.
Loading history...
3470
                $orig_uid = $row['uid'];
3471
                $orig_pid = $row['pid'];
3472
                $movePldSwap = self::movePlhOL($table, $row);
3473
            }
3474
            $wsAlt = self::getWorkspaceVersionOfRecord(
3475
                $wsid,
3476
                $table,
3477
                $row['uid'],
3478
                implode(',', static::purgeComputedPropertyNames(array_keys($row)))
3479
            );
3480
            // If version was found, swap the default record with that one.
3481
            if (is_array($wsAlt)) {
3482
                // Check if this is in move-state:
3483
                if ($previewMovePlaceholders && !$movePldSwap && static::isTableWorkspaceEnabled($table) && $unsetMovePointers) {
3484
                    // Only for WS ver 2... (moving)
3485
                    // If t3ver_state is not found, then find it... (but we like best if it is here...)
3486
                    if (!isset($wsAlt['t3ver_state'])) {
3487
                        $stateRec = self::getRecord($table, $wsAlt['uid'], 't3ver_state');
3488
                        $versionState = VersionState::cast($stateRec['t3ver_state']);
3489
                    } else {
3490
                        $versionState = VersionState::cast($wsAlt['t3ver_state']);
3491
                    }
3492
                    if ($versionState->equals(VersionState::MOVE_POINTER)) {
3493
                        // @todo Same problem as frontend in versionOL(). See TODO point there.
3494
                        $row = false;
3495
                        return;
3496
                    }
3497
                }
3498
                // Always correct PID from -1 to what it should be
3499
                if (isset($wsAlt['pid'])) {
3500
                    // Keep the old (-1) - indicates it was a version.
3501
                    $wsAlt['_ORIG_pid'] = $wsAlt['pid'];
3502
                    // Set in the online versions PID.
3503
                    $wsAlt['pid'] = $row['pid'];
3504
                }
3505
                // For versions of single elements or page+content, swap UID and PID
3506
                $wsAlt['_ORIG_uid'] = $wsAlt['uid'];
3507
                $wsAlt['uid'] = $row['uid'];
3508
                // Backend css class:
3509
                $wsAlt['_CSSCLASS'] = 'ver-element';
3510
                // Changing input record to the workspace version alternative:
3511
                $row = $wsAlt;
3512
            }
3513
            // If the original record was a move placeholder, the uid and pid of that is preserved here:
3514
            if ($movePldSwap) {
3515
                $row['_MOVE_PLH'] = true;
3516
                $row['_MOVE_PLH_uid'] = $orig_uid;
3517
                $row['_MOVE_PLH_pid'] = $orig_pid;
3518
                // For display; To make the icon right for the placeholder vs. the original
3519
                $row['t3ver_state'] = (string)new VersionState(VersionState::MOVE_PLACEHOLDER);
3520
            }
3521
        }
3522
    }
3523
3524
    /**
3525
     * Checks if record is a move-placeholder (t3ver_state==VersionState::MOVE_PLACEHOLDER) and if so
3526
     * it will set $row to be the pointed-to live record (and return TRUE)
3527
     *
3528
     * @param string $table Table name
3529
     * @param array $row Row (passed by reference) - must be online record!
3530
     * @return bool TRUE if overlay is made.
3531
     * @see PageRepository::movePlhOl()
3532
     * @internal should only be used from within TYPO3 Core
3533
     */
3534
    public static function movePlhOL($table, &$row)
3535
    {
3536
        if (static::isTableWorkspaceEnabled($table)) {
3537
            // If t3ver_move_id or t3ver_state is not found, then find it... (but we like best if it is here...)
3538
            if (!isset($row['t3ver_move_id']) || !isset($row['t3ver_state'])) {
3539
                $moveIDRec = self::getRecord($table, $row['uid'], 't3ver_move_id, t3ver_state');
3540
                $moveID = $moveIDRec['t3ver_move_id'];
3541
                $versionState = VersionState::cast($moveIDRec['t3ver_state']);
3542
            } else {
3543
                $moveID = $row['t3ver_move_id'];
3544
                $versionState = VersionState::cast($row['t3ver_state']);
3545
            }
3546
            // Find pointed-to record.
3547
            if ($versionState->equals(VersionState::MOVE_PLACEHOLDER) && $moveID) {
3548
                if ($origRow = self::getRecord(
3549
                    $table,
3550
                    $moveID,
3551
                    implode(',', static::purgeComputedPropertyNames(array_keys($row)))
3552
                )) {
3553
                    $row = $origRow;
3554
                    return true;
3555
                }
3556
            }
3557
        }
3558
        return false;
3559
    }
3560
3561
    /**
3562
     * Select the workspace version of a record, if exists
3563
     *
3564
     * @param int $workspace Workspace ID
3565
     * @param string $table Table name to select from
3566
     * @param int $uid Record uid for which to find workspace version.
3567
     * @param string $fields Field list to select
3568
     * @return array|bool If found, return record, otherwise false
3569
     */
3570
    public static function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields = '*')
3571
    {
3572
        if (ExtensionManagementUtility::isLoaded('workspaces')) {
3573
            if ($workspace !== 0 && self::isTableWorkspaceEnabled($table)) {
3574
3575
                // Select workspace version of record:
3576
                $queryBuilder = static::getQueryBuilderForTable($table);
3577
                $queryBuilder->getRestrictions()
3578
                    ->removeAll()
3579
                    ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
3580
3581
                // build fields to select
3582
                $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields));
3583
3584
                $row = $queryBuilder
3585
                    ->from($table)
3586
                    ->where(
3587
                        $queryBuilder->expr()->eq(
3588
                            't3ver_oid',
3589
                            $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
3590
                        ),
3591
                        $queryBuilder->expr()->eq(
3592
                            't3ver_wsid',
3593
                            $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
3594
                        )
3595
                    )
3596
                    ->execute()
3597
                    ->fetch();
3598
3599
                return $row;
3600
            }
3601
        }
3602
        return false;
3603
    }
3604
3605
    /**
3606
     * Returns live version of record
3607
     *
3608
     * @param string $table Table name
3609
     * @param int $uid Record UID of draft, offline version
3610
     * @param string $fields Field list, default is *
3611
     * @return array|null If found, the record, otherwise NULL
3612
     */
3613
    public static function getLiveVersionOfRecord($table, $uid, $fields = '*')
3614
    {
3615
        $liveVersionId = self::getLiveVersionIdOfRecord($table, $uid);
3616
        if ($liveVersionId !== null) {
3617
            return self::getRecord($table, $liveVersionId, $fields);
3618
        }
3619
        return null;
3620
    }
3621
3622
    /**
3623
     * Gets the id of the live version of a record.
3624
     *
3625
     * @param string $table Name of the table
3626
     * @param int $uid Uid of the offline/draft record
3627
     * @return int|null The id of the live version of the record (or NULL if nothing was found)
3628
     * @internal should only be used from within TYPO3 Core
3629
     */
3630
    public static function getLiveVersionIdOfRecord($table, $uid)
3631
    {
3632
        if (!ExtensionManagementUtility::isLoaded('workspaces')) {
3633
            return null;
3634
        }
3635
        $liveVersionId = null;
3636
        if (self::isTableWorkspaceEnabled($table)) {
3637
            $currentRecord = self::getRecord($table, $uid, 'pid,t3ver_oid');
3638
            if (is_array($currentRecord) && (int)$currentRecord['t3ver_oid'] > 0) {
3639
                $liveVersionId = $currentRecord['t3ver_oid'];
3640
            }
3641
        }
3642
        return $liveVersionId;
3643
    }
3644
3645
    /**
3646
     * Performs mapping of new uids to new versions UID in case of import inside a workspace.
3647
     *
3648
     * @param string $table Table name
3649
     * @param int $uid Record uid (of live record placeholder)
3650
     * @return int Uid of offline version if any, otherwise live uid.
3651
     * @internal should only be used from within TYPO3 Core
3652
     */
3653
    public static function wsMapId($table, $uid)
3654
    {
3655
        $wsRec = null;
3656
        if (static::getBackendUserAuthentication() instanceof BackendUserAuthentication) {
0 ignored issues
show
introduced by
static::getBackendUserAuthentication() is always a sub-type of TYPO3\CMS\Core\Authentic...ckendUserAuthentication.
Loading history...
3657
            $wsRec = self::getWorkspaceVersionOfRecord(
3658
                static::getBackendUserAuthentication()->workspace,
3659
                $table,
3660
                $uid,
3661
                'uid'
3662
            );
3663
        }
3664
        return is_array($wsRec) ? $wsRec['uid'] : $uid;
3665
    }
3666
3667
    /**
3668
     * Returns move placeholder of online (live) version
3669
     *
3670
     * @param string $table Table name
3671
     * @param int $uid Record UID of online version
3672
     * @param string $fields Field list, default is *
3673
     * @param int|null $workspace The workspace to be used
3674
     * @return array|bool If found, the record, otherwise false
3675
     * @internal should only be used from within TYPO3 Core
3676
     */
3677
    public static function getMovePlaceholder($table, $uid, $fields = '*', $workspace = null)
3678
    {
3679
        if ($workspace === null && static::getBackendUserAuthentication() instanceof BackendUserAuthentication) {
3680
            $workspace = static::getBackendUserAuthentication()->workspace;
3681
        }
3682
        if ((int)$workspace !== 0 && static::isTableWorkspaceEnabled($table)) {
3683
            // Select workspace version of record:
3684
            $queryBuilder = static::getQueryBuilderForTable($table);
3685
            $queryBuilder->getRestrictions()
3686
                ->removeAll()
3687
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
3688
3689
            $row = $queryBuilder
3690
                ->select(...GeneralUtility::trimExplode(',', $fields, true))
3691
                ->from($table)
3692
                ->where(
3693
                    $queryBuilder->expr()->eq(
3694
                        't3ver_state',
3695
                        $queryBuilder->createNamedParameter(
3696
                            (string)new VersionState(VersionState::MOVE_PLACEHOLDER),
3697
                            \PDO::PARAM_INT
3698
                        )
3699
                    ),
3700
                    $queryBuilder->expr()->eq(
3701
                        't3ver_move_id',
3702
                        $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
3703
                    ),
3704
                    $queryBuilder->expr()->eq(
3705
                        't3ver_wsid',
3706
                        $queryBuilder->createNamedParameter($workspace, \PDO::PARAM_INT)
3707
                    )
3708
                )
3709
                ->execute()
3710
                ->fetch();
3711
3712
            return $row ?: false;
3713
        }
3714
        return false;
3715
    }
3716
3717
    /*******************************************
3718
     *
3719
     * Miscellaneous
3720
     *
3721
     *******************************************/
3722
3723
    /**
3724
     * Creates ADMCMD parameters for the "viewpage" extension / frontend
3725
     *
3726
     * @param array $pageInfo Page record
3727
     * @param \TYPO3\CMS\Core\Context\Context $context
3728
     * @return string Query-parameters
3729
     * @internal
3730
     */
3731
    public static function ADMCMD_previewCmds($pageInfo, Context $context)
3732
    {
3733
        $simUser = '';
3734
        $simTime = '';
3735
        if ($pageInfo['fe_group'] > 0) {
3736
            $simUser = '&ADMCMD_simUser=' . $pageInfo['fe_group'];
3737
        } elseif ((int)$pageInfo['fe_group'] === -2) {
3738
            // -2 means "show at any login". We simulate first available fe_group.
3739
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
3740
                ->getQueryBuilderForTable('fe_groups');
3741
            $queryBuilder->getRestrictions()
3742
                ->removeAll()
3743
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
3744
                ->add(GeneralUtility::makeInstance(HiddenRestriction::class));
3745
3746
            $activeFeGroupRow = $queryBuilder->select('uid')
3747
                ->from('fe_groups')
3748
                ->execute()
3749
                ->fetch();
3750
3751
            if (!empty($activeFeGroupRow)) {
3752
                $simUser = '&ADMCMD_simUser=' . $activeFeGroupRow['uid'];
3753
            }
3754
        }
3755
        $startTime = (int)$pageInfo['starttime'];
3756
        $endTime = (int)$pageInfo['endtime'];
3757
        if ($startTime > $GLOBALS['EXEC_TIME']) {
3758
            // simulate access time to ensure PageRepository will find the page and in turn PageRouter will generate
3759
            // an URL for it
3760
            $dateAspect = GeneralUtility::makeInstance(DateTimeAspect::class, new \DateTimeImmutable('@' . $startTime));
3761
            $context->setAspect('date', $dateAspect);
3762
            $simTime = '&ADMCMD_simTime=' . $startTime;
3763
        }
3764
        if ($endTime < $GLOBALS['EXEC_TIME'] && $endTime !== 0) {
3765
            // Set access time to page's endtime subtracted one second to ensure PageRepository will find the page and
3766
            // in turn PageRouter will generate an URL for it
3767
            $dateAspect = GeneralUtility::makeInstance(
3768
                DateTimeAspect::class,
3769
                new \DateTimeImmutable('@' . ($endTime - 1))
3770
            );
3771
            $context->setAspect('date', $dateAspect);
3772
            $simTime = '&ADMCMD_simTime=' . ($endTime - 1);
3773
        }
3774
        return $simUser . $simTime;
3775
    }
3776
3777
    /**
3778
     * Returns the name of the backend script relative to the TYPO3 main directory.
3779
     *
3780
     * @param string $interface Name of the backend interface  (backend, frontend) to look up the script name for. If no interface is given, the interface for the current backend user is used.
3781
     * @return string The name of the backend script relative to the TYPO3 main directory.
3782
     * @internal should only be used from within TYPO3 Core
3783
     */
3784
    public static function getBackendScript($interface = '')
3785
    {
3786
        if (!$interface) {
3787
            $interface = static::getBackendUserAuthentication()->uc['interfaceSetup'];
3788
        }
3789
        switch ($interface) {
3790
            case 'frontend':
3791
                $script = '../.';
3792
                break;
3793
            case 'backend':
3794
            default:
3795
                $script = (string)GeneralUtility::makeInstance(UriBuilder::class)->buildUriFromRoute('main');
3796
        }
3797
        return $script;
3798
    }
3799
3800
    /**
3801
     * Determines whether a table is enabled for workspaces.
3802
     *
3803
     * @param string $table Name of the table to be checked
3804
     * @return bool
3805
     */
3806
    public static function isTableWorkspaceEnabled($table)
3807
    {
3808
        return !empty($GLOBALS['TCA'][$table]['ctrl']['versioningWS']);
3809
    }
3810
3811
    /**
3812
     * Gets the TCA configuration of a field.
3813
     *
3814
     * @param string $table Name of the table
3815
     * @param string $field Name of the field
3816
     * @return array
3817
     */
3818
    public static function getTcaFieldConfiguration($table, $field)
3819
    {
3820
        $configuration = [];
3821
        if (isset($GLOBALS['TCA'][$table]['columns'][$field]['config'])) {
3822
            $configuration = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
3823
        }
3824
        return $configuration;
3825
    }
3826
3827
    /**
3828
     * Whether to ignore restrictions on a web-mount of a table.
3829
     * The regular behaviour is that records to be accessed need to be
3830
     * in a valid user's web-mount.
3831
     *
3832
     * @param string $table Name of the table
3833
     * @return bool
3834
     */
3835
    public static function isWebMountRestrictionIgnored($table)
3836
    {
3837
        return !empty($GLOBALS['TCA'][$table]['ctrl']['security']['ignoreWebMountRestriction']);
3838
    }
3839
3840
    /**
3841
     * Whether to ignore restrictions on root-level records.
3842
     * The regular behaviour is that records on the root-level (page-id 0)
3843
     * only can be accessed by admin users.
3844
     *
3845
     * @param string $table Name of the table
3846
     * @return bool
3847
     */
3848
    public static function isRootLevelRestrictionIgnored($table)
3849
    {
3850
        return !empty($GLOBALS['TCA'][$table]['ctrl']['security']['ignoreRootLevelRestriction']);
3851
    }
3852
3853
    /**
3854
     * @param string $table
3855
     * @return Connection
3856
     */
3857
    protected static function getConnectionForTable($table)
3858
    {
3859
        return GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
3860
    }
3861
3862
    /**
3863
     * @param string $table
3864
     * @return QueryBuilder
3865
     */
3866
    protected static function getQueryBuilderForTable($table)
3867
    {
3868
        return GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
3869
    }
3870
3871
    /**
3872
     * @return LoggerInterface
3873
     */
3874
    protected static function getLogger()
3875
    {
3876
        return GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);
3877
    }
3878
3879
    /**
3880
     * @return LanguageService
3881
     */
3882
    protected static function getLanguageService()
3883
    {
3884
        return $GLOBALS['LANG'];
3885
    }
3886
3887
    /**
3888
     * @return BackendUserAuthentication
3889
     */
3890
    protected static function getBackendUserAuthentication()
3891
    {
3892
        return $GLOBALS['BE_USER'] ?? null;
3893
    }
3894
}
3895