Completed
Push — master ( f8df32...b7eb89 )
by Timo
49s
created

Util::isDraftRecord()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 14
ccs 0
cts 4
cp 0
rs 8.8571
cc 5
eloc 7
nc 3
nop 2
crap 30
1
<?php
2
namespace ApacheSolrForTypo3\Solr;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2009-2015 Ingo Renner <[email protected]>
8
 *  All rights reserved
9
 *
10
 *  This script is part of the TYPO3 project. The TYPO3 project is
11
 *  free software; you can redistribute it and/or modify
12
 *  it under the terms of the GNU General Public License as published by
13
 *  the Free Software Foundation; either version 2 of the License, or
14
 *  (at your option) any later version.
15
 *
16
 *  The GNU General Public License can be found at
17
 *  http://www.gnu.org/copyleft/gpl.html.
18
 *
19
 *  This script is distributed in the hope that it will be useful,
20
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 *  GNU General Public License for more details.
23
 *
24
 *  This copyright notice MUST APPEAR in all copies of the script!
25
 ***************************************************************/
26
27
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\RecordMonitor\Helper\RootPageResolver;
28
use ApacheSolrForTypo3\Solr\Domain\Site\SiteHashService;
29
use ApacheSolrForTypo3\Solr\System\Cache\TwoLevelCache;
30
use ApacheSolrForTypo3\Solr\System\Configuration\ConfigurationManager;
31
use ApacheSolrForTypo3\Solr\System\Configuration\TypoScriptConfiguration;
32
use ApacheSolrForTypo3\Solr\System\Page\Rootline;
33
use TYPO3\CMS\Backend\Utility\BackendUtility;
34
use TYPO3\CMS\Core\TimeTracker\NullTimeTracker;
35
use TYPO3\CMS\Core\TypoScript\ExtendedTemplateService;
36
use TYPO3\CMS\Core\Utility\GeneralUtility;
37
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
38
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
39
use TYPO3\CMS\Frontend\Page\PageRepository;
40
41
/**
42
 * Utility class for tx_solr
43
 *
44
 * @author Ingo Renner <[email protected]>
45
 */
46
class Util
47
{
48
    const SOLR_ISO_DATETIME_FORMAT = 'Y-m-d\TH:i:s\Z';
49
50
    /**
51
     * Generates a document id for documents representing page records.
52
     *
53
     * @param int $uid The page's uid
54
     * @param int $typeNum The page's typeNum
55
     * @param int $language the language id, defaults to 0
56
     * @param string $accessGroups comma separated list of uids of groups that have access to that page
57
     * @param string $mountPointParameter The mount point parameter that is used to access the page.
58
     * @return string The document id for that page
59 42
     */
60
    public static function getPageDocumentId(
61
        $uid,
62
        $typeNum = 0,
63
        $language = 0,
64
        $accessGroups = '0,-1',
65
        $mountPointParameter = ''
66 42
    ) {
67
        $additionalParameters = $typeNum . '/' . $language . '/' . $accessGroups;
68 42
69
        if ((string)$mountPointParameter !== '') {
70
            $additionalParameters = $mountPointParameter . '/' . $additionalParameters;
71
        }
72 42
73 42
        $documentId = self::getDocumentId(
74
            'pages',
75
            $uid,
76
            $uid,
77
            $additionalParameters
78
        );
79 42
80
        return $documentId;
81
    }
82
83
    /**
84
     * Generates a document id in the form $siteHash/$type/$uid.
85
     *
86
     * @param string $table The records table name
87
     * @param int $pid The record's pid
88
     * @param int $uid The record's uid
89
     * @param string $additionalIdParameters Additional ID parameters
90
     * @return string A document id
91 53
     */
92
    public static function getDocumentId(
93
        $table,
94
        $pid,
95
        $uid,
96
        $additionalIdParameters = ''
97 53
    ) {
98
        $siteHash = Site::getSiteByPageId($pid)->getSiteHash();
99 53
100 53
        $documentId = $siteHash . '/' . $table . '/' . $uid;
101 42
        if (!empty($additionalIdParameters)) {
102
            $documentId .= '/' . $additionalIdParameters;
103
        }
104 53
105
        return $documentId;
106
    }
107
108
    /**
109
     * Converts a date from unix timestamp to ISO 8601 format.
110
     *
111
     * @param int $timestamp unix timestamp
112
     * @return string the date in ISO 8601 format
113 56
     */
114
    public static function timestampToIso($timestamp)
115 56
    {
116
        return date(self::SOLR_ISO_DATETIME_FORMAT, $timestamp);
117
    }
118
119
    /**
120
     * Converts a date from ISO 8601 format to unix timestamp.
121
     *
122
     * @param string $isoTime date in ISO 8601 format
123
     * @return int unix timestamp
124 18
     */
125
    public static function isoToTimestamp($isoTime)
126 18
    {
127
        $dateTime = \DateTime::createFromFormat(self::SOLR_ISO_DATETIME_FORMAT,
128 18
            $isoTime);
129
        return $dateTime ? (int)$dateTime->format('U') : 0;
130
    }
131
132
    /**
133
     * Converts a date from unix timestamp to ISO 8601 format in UTC timezone.
134
     *
135
     * @param int $timestamp unix timestamp
136
     * @return string the date in ISO 8601 format
137
     */
138
    public static function timestampToUtcIso($timestamp)
139
    {
140
        return gmdate(self::SOLR_ISO_DATETIME_FORMAT, $timestamp);
141
    }
142
143
    /**
144
     * Converts a date from ISO 8601 format in UTC timezone to unix timestamp.
145
     *
146
     * @param string $isoTime date in ISO 8601 format
147
     * @return int unix timestamp
148
     */
149
    public static function utcIsoToTimestamp($isoTime)
150
    {
151
        $utcTimeZone = new \DateTimeZone('UTC');
152
        $dateTime = \DateTime::createFromFormat(self::SOLR_ISO_DATETIME_FORMAT,
153
            $isoTime, $utcTimeZone);
154
        return $dateTime ? (int)$dateTime->format('U') : 0;
155
    }
156
157
    /**
158
     * Returns given word as CamelCased.
159
     *
160
     * Converts a word like "send_email" to "SendEmail". It
161
     * will remove non alphanumeric characters from the word, so
162
     * "who's online" will be converted to "WhoSOnline"
163
     *
164
     * @param string $word Word to convert to camel case
165
     * @return string UpperCamelCasedWord
166
     */
167
    public static function camelize($word)
168
    {
169
        return str_replace(' ', '',
170
            ucwords(preg_replace('![^A-Z^a-z^0-9]+!', ' ', $word)));
171
    }
172
173
    /**
174
     * Returns a given CamelCasedString as an lowercase string with underscores.
175
     * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
176
     *
177
     * @param string $string String to be converted to lowercase underscore
178
     * @return string     lowercase_and_underscored_string
179
     */
180
    public static function camelCaseToLowerCaseUnderscored($string)
181
    {
182
        return strtolower(preg_replace('/(?<=\w)([A-Z])/', '_\\1', $string));
183
    }
184
185
    /**
186
     * Returns a given string with underscores as UpperCamelCase.
187
     * Example: Converts blog_example to BlogExample
188
     *
189
     * @param string $string String to be converted to camel case
190
     * @return string     UpperCamelCasedWord
191 26
     */
192
    public static function underscoredToUpperCamelCase($string)
193 26
    {
194 26
        return str_replace(' ', '',
195
            ucwords(str_replace('_', ' ', strtolower($string))));
196
    }
197
198
    /**
199
     * Shortcut to retrieve the TypoScript configuration for EXT:solr
200
     * (plugin.tx_solr) from TSFE.
201
     *
202
     * @return TypoScriptConfiguration
203 148
     */
204
    public static function getSolrConfiguration()
205 148
    {
206
        $configurationManager = self::getConfigurationManager();
207 148
208
        return $configurationManager->getTypoScriptConfiguration();
209
    }
210
211
    /**
212
     * @return ConfigurationManager
213 184
     */
214
    private static function getConfigurationManager()
215
    {
216 184
        /** @var ConfigurationManager $configurationManager */
217 184
        $configurationManager = GeneralUtility::makeInstance(ConfigurationManager::class);
218
        return $configurationManager;
219
    }
220
221
    /**
222
     * Gets the Solr configuration for a specific root page id.
223
     * To be used from the backend.
224
     *
225
     * @param int $pageId Id of the (root) page to get the Solr configuration from.
226
     * @param bool $initializeTsfe Optionally initializes a full TSFE to get the configuration, defaults to FALSE
227
     * @param int $language System language uid, optional, defaults to 0
228
     * @return TypoScriptConfiguration The Solr configuration for the requested tree.
229 59
     */
230
    public static function getSolrConfigurationFromPageId(
231
        $pageId,
232
        $initializeTsfe = false,
233
        $language = 0
234 59
    ) {
235 59
        $rootPath = '';
236
        return self::getConfigurationFromPageId($pageId, $rootPath, $initializeTsfe, $language);
237
    }
238
239
    /**
240
     * Loads the TypoScript configuration for a given page id and language.
241
     * Language usage may be disabled to get the default TypoScript
242
     * configuration.
243
     *
244
     * @param int $pageId Id of the (root) page to get the Solr configuration from.
245
     * @param string $path The TypoScript configuration path to retrieve.
246
     * @param bool $initializeTsfe Optionally initializes a full TSFE to get the configuration, defaults to FALSE
247
     * @param int|bool $language System language uid or FALSE to disable language usage, optional, defaults to 0
248
     * @param bool $useTwoLevelCache Flag to enable the two level cache for the typoscript configuration array
249
     * @return TypoScriptConfiguration The Solr configuration for the requested tree.
250 61
     */
251
    public static function getConfigurationFromPageId(
252
        $pageId,
253
        $path,
254
        $initializeTsfe = false,
255
        $language = 0,
256
        $useTwoLevelCache = true
257 61
    ) {
258 61
        static $configurationObjectCache = [];
259 61
        $cacheId = md5($pageId . '|' . $path . '|' . $language);
260 53
        if (isset($configurationObjectCache[$cacheId])) {
261
            return $configurationObjectCache[$cacheId];
262
        }
263
264
        // If we're on UID 0, we cannot retrieve a configuration currently.
265
        // getRootline() below throws an exception (since #typo3-60 )
266 61
        // as UID 0 cannot have any parent rootline by design.
267 2
        if ($pageId == 0) {
268
            return $configurationObjectCache[$cacheId] = self::buildTypoScriptConfigurationFromArray([], $pageId, $language, $path);
269
        }
270 60
271
        if ($useTwoLevelCache) {
272 60
            /** @var $cache TwoLevelCache */
273 60
            $cache = GeneralUtility::makeInstance(TwoLevelCache::class, 'tx_solr_configuration');
274
            $configurationArray = $cache->get($cacheId);
275
        }
276 60
277
        if (!empty($configurationArray)) {
278
            // we have a cache hit and can return it.
279
            return $configurationObjectCache[$cacheId] = self::buildTypoScriptConfigurationFromArray($configurationArray, $pageId, $language, $path);
280
        }
281
282 60
        // we have nothing in the cache. We need to build the configurationToUse
283
        $configurationArray = self::buildConfigurationArray($pageId, $path, $initializeTsfe, $language);
284 60
285 60
        if ($useTwoLevelCache && isset($cache)) {
286
            $cache->set($cacheId, $configurationArray);
287
        }
288 60
289
        return $configurationObjectCache[$cacheId] = self::buildTypoScriptConfigurationFromArray($configurationArray, $pageId, $language, $path);
290
    }
291
292
293
    /**
294
     * Initializes a TSFE, if required and builds an configuration array, containing the solr configuration.
295
     *
296
     * @param integer $pageId
297
     * @param string $path
298
     * @param boolean $initializeTsfe
299
     * @param integer $language
300
     * @return array
301 60
     */
302
    protected static function buildConfigurationArray($pageId, $path, $initializeTsfe, $language)
303 60
    {
304 2
        if ($initializeTsfe) {
305 2
            self::initializeTsfe($pageId, $language);
306
            $configurationToUse = self::getConfigurationFromInitializedTSFE($path);
307 60
        } else {
308
            $configurationToUse = self::getConfigurationFromExistingTSFE($pageId, $path, $language);
309
        }
310 60
311
        return is_array($configurationToUse) ? $configurationToUse : [];
312
    }
313
314
    /**
315
     * Builds the configuration object from a config array and returns it.
316
     *
317
     * @param array $configurationToUse
318
     * @param int $pageId
319
     * @param int $languageId
320
     * @param string $typoScriptPath
321
     * @return TypoScriptConfiguration
322 61
     */
323
    protected static function buildTypoScriptConfigurationFromArray(array $configurationToUse, $pageId, $languageId, $typoScriptPath)
324 61
    {
325 61
        $configurationManager = self::getConfigurationManager();
326
        return $configurationManager->getTypoScriptConfiguration($configurationToUse, $pageId, $languageId, $typoScriptPath);
327
    }
328
329
    /**
330
     * This function is used to retrieve the configuration from a previous initialized TSFE
331
     * (see: getConfigurationFromPageId)
332
     *
333
     * @param string $path
334
     * @return mixed
335 2
     */
336
    private static function getConfigurationFromInitializedTSFE($path)
337
    {
338 2
        /** @var $tmpl ExtendedTemplateService */
339 2
        $tmpl = GeneralUtility::makeInstance(ExtendedTemplateService::class);
340 2
        $configuration = $tmpl->ext_getSetup($GLOBALS['TSFE']->tmpl->setup, $path);
341 2
        $configurationToUse = $configuration[0];
342
        return $configurationToUse;
343
    }
344
345
    /**
346
     * This function is used to retrieve the configuration from an existing TSFE instance
347
     * @param $pageId
348
     * @param $path
349
     * @param $language
350
     * @return mixed
351 60
     */
352
    private static function getConfigurationFromExistingTSFE($pageId, $path, $language)
353 60
    {
354 59
        if (is_int($language)) {
355
            GeneralUtility::_GETset($language, 'L');
356
        }
357
358 60
            /** @var $pageSelect PageRepository */
359 60
        $pageSelect = GeneralUtility::makeInstance(PageRepository::class);
360
        $rootLine = $pageSelect->getRootLine($pageId);
361 60
362 60
        $initializedTsfe = false;
363 60
        $initializedPageSelect = false;
364 51
        if (empty($GLOBALS['TSFE']->sys_page)) {
365 51
            if (empty($GLOBALS['TSFE'])) {
366 51
                $GLOBALS['TSFE'] = new \stdClass();
367 51
                $GLOBALS['TSFE']->tmpl = new \stdClass();
368 51
                $GLOBALS['TSFE']->tmpl->rootLine = $rootLine;
369 51
                $GLOBALS['TSFE']->sys_page = $pageSelect;
370 51
                $GLOBALS['TSFE']->id = $pageId;
371 51
                $GLOBALS['TSFE']->tx_solr_initTsfe = 1;
372
                $initializedTsfe = true;
373
            }
374 51
375 51
            $GLOBALS['TSFE']->sys_page = $pageSelect;
376
            $initializedPageSelect = true;
377
        }
378 60
            /** @var $tmpl ExtendedTemplateService */
379 60
        $tmpl = GeneralUtility::makeInstance(ExtendedTemplateService::class);
380 60
        $tmpl->tt_track = false; // Do not log time-performance information
381 60
        $tmpl->init();
382 60
        $tmpl->runThroughTemplates($rootLine); // This generates the constants/config + hierarchy info for the template.
383
        $tmpl->generateConfig();
384 60
385 60
        $getConfigurationFromInitializedTSFEAndWriteToCache = $tmpl->ext_getSetup($tmpl->setup, $path);
386
        $configurationToUse = $getConfigurationFromInitializedTSFEAndWriteToCache[0];
387 60
388 51
        if ($initializedPageSelect) {
389
            $GLOBALS['TSFE']->sys_page = null;
390 60
        }
391 51
        if ($initializedTsfe) {
392
            unset($GLOBALS['TSFE']);
393 60
        }
394
        return $configurationToUse;
395
    }
396
397
    /**
398
     * Initializes the TSFE for a given page ID and language.
399
     *
400
     * @param int $pageId The page id to initialize the TSFE for
401
     * @param int $language System language uid, optional, defaults to 0
402
     * @param bool $useCache Use cache to reuse TSFE
403
     * @return void
404 15
     */
405
    public static function initializeTsfe(
406
        $pageId,
407
        $language = 0,
408
        $useCache = true
409 15
    ) {
410
        static $tsfeCache = [];
411
412 15
        // resetting, a TSFE instance with data from a different page Id could be set already
413
        unset($GLOBALS['TSFE']);
414 15
415
        $cacheId = $pageId . '|' . $language;
416 15
417 15
        if (!is_object($GLOBALS['TT'])) {
418
            $GLOBALS['TT'] = GeneralUtility::makeInstance(NullTimeTracker::class);
419
        }
420 15
421 15
        if (!isset($tsfeCache[$cacheId]) || !$useCache) {
422
            GeneralUtility::_GETset($language, 'L');
423 15
424 15
            $GLOBALS['TSFE'] = GeneralUtility::makeInstance(TypoScriptFrontendController::class,
425
                $GLOBALS['TYPO3_CONF_VARS'], $pageId, 0);
426
427
            // for certain situations we need to trick TSFE into granting us
428
            // access to the page in any case to make getPageAndRootline() work
429 15
            // see http://forge.typo3.org/issues/42122
430 15
            $pageRecord = BackendUtility::getRecord('pages', $pageId, 'fe_group');
431 15
            $groupListBackup = $GLOBALS['TSFE']->gr_list;
432
            $GLOBALS['TSFE']->gr_list = $pageRecord['fe_group'];
433 15
434 15
            $GLOBALS['TSFE']->sys_page = GeneralUtility::makeInstance(PageRepository::class);
435
            $GLOBALS['TSFE']->getPageAndRootline();
436
437 15
            // restore gr_list
438
            $GLOBALS['TSFE']->gr_list = $groupListBackup;
439 15
440 15
            $GLOBALS['TSFE']->initTemplate();
441 15
            $GLOBALS['TSFE']->forceTemplateParsing = true;
442 15
            $GLOBALS['TSFE']->initFEuser();
443
            $GLOBALS['TSFE']->initUserGroups();
444
            //  $GLOBALS['TSFE']->getCompressedTCarray(); // seems to cause conflicts sometimes
445 15
446 15
            $GLOBALS['TSFE']->no_cache = true;
447 15
            $GLOBALS['TSFE']->tmpl->start($GLOBALS['TSFE']->rootLine);
448 15
            $GLOBALS['TSFE']->no_cache = false;
449
            $GLOBALS['TSFE']->getConfigArray();
450 15
451 15
            $GLOBALS['TSFE']->settingLanguage();
452
            if (!$useCache) {
453
                $GLOBALS['TSFE']->settingLocale();
454
            }
455 15
456 15
            $GLOBALS['TSFE']->newCObj();
457 15
            $GLOBALS['TSFE']->absRefPrefix = self::getAbsRefPrefixFromTSFE($GLOBALS['TSFE']);
458
            $GLOBALS['TSFE']->calculateLinkVars();
459 15
460 15
            if ($useCache) {
461
                $tsfeCache[$cacheId] = $GLOBALS['TSFE'];
462
            }
463
        }
464 15
465 15
        if ($useCache) {
466 15
            $GLOBALS['TSFE'] = $tsfeCache[$cacheId];
467
            $GLOBALS['TSFE']->settingLocale();
468 15
        }
469
    }
470
471
    /**
472
     * Determines the rootpage ID for a given page.
473
     *
474
     * @param int $pageId A page ID somewhere in a tree.
475
     * @param bool $forceFallback Force the explicit detection and do not use the current frontend root line
476
     * @return int The page's tree branch's root page ID
477 90
     */
478
    public static function getRootPageId($pageId = 0, $forceFallback = false)
479
    {
480 90
        /** @var Rootline $rootLine */
481 90
        $rootLine = GeneralUtility::makeInstance(Rootline::class);
482
        $rootPageId = intval($pageId) ? intval($pageId) : $GLOBALS['TSFE']->id;
483
484 90
        // frontend
485 54
        if (!empty($GLOBALS['TSFE']->rootLine)) {
486
            $rootLine->setRootLineArray($GLOBALS['TSFE']->rootLine);
487
        }
488
489 90
        // fallback, backend
490 47
        if ($pageId != 0 && ($forceFallback || !$rootLine->getHasRootPage())) {
491 47
            $pageSelect = GeneralUtility::makeInstance(PageRepository::class);
492 47
            $rootLineArray = $pageSelect->getRootLine($pageId, '', true);
493
            $rootLine->setRootLineArray($rootLineArray);
494
        }
495 90
496 90
        $rootPageFromRootLine = $rootLine->getRootPageId();
497
        return $rootPageFromRootLine === 0 ? $rootPageId : $rootPageFromRootLine;
498
    }
499
500
    /**
501
     * Takes a page Id and checks whether the page is marked as root page.
502
     *
503
     * @param int $pageId Page ID
504
     * @return bool TRUE if the page is marked as root page, FALSE otherwise
505 51
     * @deprecated since 6.1 will be removed in 7.0
506
     */
507 51
    public static function isRootPage($pageId)
508 51
    {
509
        GeneralUtility::logDeprecatedFunction();
510 51
        $rootPageResolver = GeneralUtility::makeInstance(RootPageResolver::class);
511 51
512 26
        return $rootPageResolver->getIsRootPageId($pageId);
513
    }
514
515 51
    /**
516
     * Gets the site hash for a domain
517 51
     *
518 1
     * @deprecated since 6.1 will be removed in 7.0. use SiteHashService->getSiteHashForDomain now.
519 1
     * @param string $domain Domain to calculate the site hash for.
520 1
     * @return string site hash for $domain
521 1
     */
522
    public static function getSiteHashForDomain($domain)
523
    {
524
        GeneralUtility::logDeprecatedFunction();
525 50
            /** @var $siteHashService SiteHashService */
526 50
        $siteHashService = GeneralUtility::makeInstance(SiteHashService::class);
527
        return $siteHashService->getSiteHashForDomain($domain);
528 50
    }
529
530
    /**
531
     * Resolves magic keywords in allowed sites configuration.
532
     * Supported keywords:
533
     *   __solr_current_site - The domain of the site the query has been started from
534
     *   __current_site - Same as __solr_current_site
535
     *   __all - Adds all domains as allowed sites
536
     *   * - Means all sites are allowed, same as no siteHash
537
     *
538
     * @deprecated since 6.1 will be removed in 7.0. use SiteHashService->getAllowedSitesForPageIdAndAllowedSitesConfiguration now.
539
     * @param int $pageId A page ID that is then resolved to the site it belongs to
540
     * @param string $allowedSitesConfiguration TypoScript setting for allowed sites
541
     * @return string List of allowed sites/domains, magic keywords resolved
542
     */
543
    public static function resolveSiteHashAllowedSites($pageId, $allowedSitesConfiguration)
544
    {
545
        /** @var $siteHashService SiteHashService */
546
        GeneralUtility::logDeprecatedFunction();
547
        $siteHashService = GeneralUtility::makeInstance(SiteHashService::class);
548
        return $siteHashService->getAllowedSitesForPageIdAndAllowedSitesConfiguration($pageId, $allowedSitesConfiguration);
549
    }
550
551
    /**
552
     * Check if record ($table, $uid) is a workspace record
553
     *
554
     * @param string $table The table the record belongs to
555
     * @param int $uid The record's uid
556
     * @return bool TRUE if the record is in a draft workspace, FALSE if it's a LIVE record
557
     */
558
    public static function isDraftRecord($table, $uid)
559
    {
560
        $isWorkspaceRecord = false;
561
562
        if ((ExtensionManagementUtility::isLoaded('workspaces')) && (BackendUtility::isTableWorkspaceEnabled($table))) {
563
            $record = BackendUtility::getRecord($table, $uid, 'pid, t3ver_state');
564
565
            if ($record['pid'] == '-1' || $record['t3ver_state'] > 0) {
566
                $isWorkspaceRecord = true;
567
            }
568
        }
569
570
        return $isWorkspaceRecord;
571
    }
572
573
    /**
574 35
     * Checks whether a record is a localization overlay.
575
     *
576 35
     * @param string $tableName The record's table name
577
     * @param array $record The record to check
578 35
     * @return bool TRUE if the record is a language overlay, FALSE otherwise
579
     */
580
    public static function isLocalizedRecord($tableName, array $record)
581
    {
582
        $isLocalizedRecord = false;
583
584
        if (isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])) {
585
            $translationOriginalPointerField = $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'];
586 35
587
            if ($record[$translationOriginalPointerField] > 0) {
588
                $isLocalizedRecord = true;
589
            }
590
        }
591
592
        return $isLocalizedRecord;
593
    }
594
595
    /**
596 28
     * Check if the page type of a page record is allowed
597
     *
598 28
     * @param array $pageRecord The pages database row
599
     * @param string $configurationName The name of the configuration to use.
600 28
     *
601 6
     * @return bool TRUE if the page type is allowed, otherwise FALSE
602
     */
603 6
    public static function isAllowedPageType(array $pageRecord, $configurationName = 'pages')
604 3
    {
605
        $isAllowedPageType = false;
606
        $configurationName = is_null($configurationName) ? 'pages' : $configurationName;
607
        $allowedPageTypes = self::getAllowedPageTypes($pageRecord['uid'], $configurationName);
608 28
609
        if (in_array($pageRecord['doktype'], $allowedPageTypes)) {
610
            $isAllowedPageType = true;
611
        }
612
613
        return $isAllowedPageType;
614
    }
615
616
    /**
617
     * Get allowed page types
618
     *
619 27
     * @param int $pageId Page ID
620
     * @param string $configurationName The name of the configuration to use.
621 27
     *
622 27
     * @return array Allowed page types to compare to a doktype of a page record
623 27
     */
624
    public static function getAllowedPageTypes($pageId, $configurationName = 'pages')
625 27
    {
626 26
        $rootPath = '';
627
        $configuration = self::getConfigurationFromPageId($pageId, $rootPath);
628
        return $configuration->getIndexQueueAllowedPageTypesArrayByConfigurationName($configurationName);
629 27
    }
630
631
    /**
632
     * Method to check if a page exists.
633
     *
634
     * @param int $pageId
635
     * @return bool
636
     */
637
    public static function pageExists($pageId)
638
    {
639
        $page = BackendUtility::getRecord('pages', (int)$pageId, 'uid');
640 27
641
        if (!is_array($page) || $page['uid'] != $pageId) {
642 27
            return false;
643 27
        }
644 27
645
        return true;
646
    }
647
648
    /**
649
     * Resolves the configured absRefPrefix to a valid value and resolved if absRefPrefix
650
     * is set to "auto".
651
     *
652
     * @param TypoScriptFrontendController $TSFE
653
     * @return string
654
     */
655
    public static function getAbsRefPrefixFromTSFE(TypoScriptFrontendController $TSFE)
656
    {
657
        $absRefPrefix = '';
658
        if (empty($TSFE->config['config']['absRefPrefix'])) {
659
            return $absRefPrefix;
660
        }
661
662
        $absRefPrefix = trim($TSFE->config['config']['absRefPrefix']);
663
        if ($absRefPrefix === 'auto') {
664
            $absRefPrefix = GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
665
        }
666
667
        return $absRefPrefix;
668
    }
669
670
    /**
671 15
     * This function can be used to check if one of the strings in needles is
672
     * contained in the haystack.
673 15
     *
674 15
     *
675 12
     * Example:
676
     *
677
     * haystack: the brown fox
678 3
     * needles: ['hello', 'world']
679 3
     * result: false
680 1
     *
681
     * haystack: the brown fox
682
     * needles: ['is', 'fox']
683 3
     * result: true
684
     *
685
     * @param string $haystack
686
     * @param array $needles
687
     * @return bool
688
     */
689
    public static function containsOneOfTheStrings($haystack, array $needles)
690
    {
691
        foreach ($needles as $needle) {
692
            $position = strpos($haystack, $needle);
693
            if ($position !== false) {
694
                return true;
695
            }
696
        }
697
698
        return false;
699
    }
700
}
701