Completed
Push — master ( 676bcb...c82269 )
by Timo
42s
created

Util::isDraftRecord()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 6.9683

Importance

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