Completed
Branch master (b22b71)
by Timo
13:13 queued 21s
created

Util::rootlineContainsRootPage()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 1
crap 3
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\Frontend\Controller\TypoScriptFrontendController;
36
use TYPO3\CMS\Frontend\Page\PageRepository;
37
38
/**
39
 * Utility class for tx_solr
40
 *
41
 * @author Ingo Renner <[email protected]>
42
 */
43
class Util
44
{
45
    const SOLR_ISO_DATETIME_FORMAT = 'Y-m-d\TH:i:s\Z';
46
47
    /**
48
     * Generates a document id for documents representing page records.
49
     *
50
     * @param int $uid The page's uid
51
     * @param int $typeNum The page's typeNum
52
     * @param int $language the language id, defaults to 0
53
     * @param string $accessGroups comma separated list of uids of groups that have access to that page
54
     * @param string $mountPointParameter The mount point parameter that is used to access the page.
55
     * @return string The document id for that page
56
     */
57 32
    public static function getPageDocumentId(
58
        $uid,
59
        $typeNum = 0,
60
        $language = 0,
61
        $accessGroups = '0,-1',
62
        $mountPointParameter = ''
63
    ) {
64 32
        $additionalParameters = $typeNum . '/' . $language . '/' . $accessGroups;
65
66 32
        if ((string)$mountPointParameter !== '') {
67
            $additionalParameters = $mountPointParameter . '/' . $additionalParameters;
68
        }
69
70 32
        $documentId = self::getDocumentId(
71 32
            'pages',
72 32
            $uid,
73 32
            $uid,
74
            $additionalParameters
75 32
        );
76
77 32
        return $documentId;
78
    }
79
80
    /**
81
     * Generates a document id in the form $siteHash/$type/$uid.
82
     *
83
     * @param string $table The records table name
84
     * @param int $pid The record's pid
85
     * @param int $uid The record's uid
86
     * @param string $additionalIdParameters Additional ID parameters
87
     * @return string A document id
88
     */
89 42
    public static function getDocumentId(
90
        $table,
91
        $pid,
92
        $uid,
93
        $additionalIdParameters = ''
94
    ) {
95 42
        $siteHash = Site::getSiteByPageId($pid)->getSiteHash();
96
97 42
        $documentId = $siteHash . '/' . $table . '/' . $uid;
98 42
        if (!empty($additionalIdParameters)) {
99 32
            $documentId .= '/' . $additionalIdParameters;
100 32
        }
101
102 42
        return $documentId;
103
    }
104
105
    /**
106
     * Converts a date from unix timestamp to ISO 8601 format.
107
     *
108
     * @param int $timestamp unix timestamp
109
     * @return string the date in ISO 8601 format
110
     */
111 45
    public static function timestampToIso($timestamp)
112
    {
113 45
        return date(self::SOLR_ISO_DATETIME_FORMAT, $timestamp);
114
    }
115
116
    /**
117
     * Converts a date from ISO 8601 format to unix timestamp.
118
     *
119
     * @param string $isoTime date in ISO 8601 format
120
     * @return int unix timestamp
121
     */
122 18
    public static function isoToTimestamp($isoTime)
123
    {
124 18
        $dateTime = \DateTime::createFromFormat(self::SOLR_ISO_DATETIME_FORMAT,
125 18
            $isoTime);
126 18
        return $dateTime ? (int)$dateTime->format('U') : 0;
127
    }
128
129
    /**
130
     * Converts a date from unix timestamp to ISO 8601 format in UTC timezone.
131
     *
132
     * @param int $timestamp unix timestamp
133
     * @return string the date in ISO 8601 format
134
     */
135
    public static function timestampToUtcIso($timestamp)
136
    {
137
        return gmdate(self::SOLR_ISO_DATETIME_FORMAT, $timestamp);
138
    }
139
140
    /**
141
     * Converts a date from ISO 8601 format in UTC timezone to unix timestamp.
142
     *
143
     * @param string $isoTime date in ISO 8601 format
144
     * @return int unix timestamp
145
     */
146
    public static function utcIsoToTimestamp($isoTime)
147
    {
148
        $utcTimeZone = new \DateTimeZone('UTC');
149
        $dateTime = \DateTime::createFromFormat(self::SOLR_ISO_DATETIME_FORMAT,
150
            $isoTime, $utcTimeZone);
151
        return $dateTime ? (int)$dateTime->format('U') : 0;
152
    }
153
154
    /**
155
     * Returns given word as CamelCased.
156
     *
157
     * Converts a word like "send_email" to "SendEmail". It
158
     * will remove non alphanumeric characters from the word, so
159
     * "who's online" will be converted to "WhoSOnline"
160
     *
161
     * @param string $word Word to convert to camel case
162
     * @return string UpperCamelCasedWord
163
     */
164
    public static function camelize($word)
165
    {
166
        return str_replace(' ', '',
167
            ucwords(preg_replace('![^A-Z^a-z^0-9]+!', ' ', $word)));
168
    }
169
170
    /**
171
     * Returns a given CamelCasedString as an lowercase string with underscores.
172
     * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
173
     *
174
     * @param string $string String to be converted to lowercase underscore
175
     * @return string     lowercase_and_underscored_string
176
     */
177
    public static function camelCaseToLowerCaseUnderscored($string)
178
    {
179
        return strtolower(preg_replace('/(?<=\w)([A-Z])/', '_\\1', $string));
180
    }
181
182
    /**
183
     * Returns a given string with underscores as UpperCamelCase.
184
     * Example: Converts blog_example to BlogExample
185
     *
186
     * @param string $string String to be converted to camel case
187
     * @return string     UpperCamelCasedWord
188
     */
189 26
    public static function underscoredToUpperCamelCase($string)
190
    {
191 26
        return str_replace(' ', '',
192 26
            ucwords(str_replace('_', ' ', strtolower($string))));
193
    }
194
195
    /**
196
     * Shortcut to retrieve the TypoScript configuration for EXT:solr
197
     * (plugin.tx_solr) from TSFE.
198
     *
199
     * @return TypoScriptConfiguration
200
     */
201 124
    public static function getSolrConfiguration()
202
    {
203 124
        $configurationManager = self::getConfigurationManager();
204
205 124
        return $configurationManager->getTypoScriptConfiguration();
206
    }
207
208
    /**
209
     * @return ConfigurationManager
210
     */
211 144
    private static function getConfigurationManager()
212
    {
213
        /** @var ConfigurationManager $configurationManager */
214 144
        $configurationManager = GeneralUtility::makeInstance(ConfigurationManager::class);
215 144
        return $configurationManager;
216
    }
217
218
    /**
219
     * Gets the Solr configuration for a specific root page id.
220
     * To be used from the backend.
221
     *
222
     * @param int $pageId Id of the (root) page to get the Solr configuration from.
223
     * @param bool $initializeTsfe Optionally initializes a full TSFE to get the configuration, defaults to FALSE
224
     * @param int $language System language uid, optional, defaults to 0
225
     * @return TypoScriptConfiguration The Solr configuration for the requested tree.
226
     */
227 32
    public static function getSolrConfigurationFromPageId(
228
        $pageId,
229
        $initializeTsfe = false,
230
        $language = 0
231
    ) {
232 32
        $rootPath = '';
233 32
        return self::getConfigurationFromPageId($pageId, $rootPath, $initializeTsfe, $language);
234
    }
235
236
    /**
237
     * Loads the TypoScript configuration for a given page id and language.
238
     * Language usage may be disabled to get the default TypoScript
239
     * configuration.
240
     *
241
     * @param int $pageId Id of the (root) page to get the Solr configuration from.
242
     * @param string $path The TypoScript configuration path to retrieve.
243
     * @param bool $initializeTsfe Optionally initializes a full TSFE to get the configuration, defaults to FALSE
244
     * @param int|bool $language System language uid or FALSE to disable language usage, optional, defaults to 0
245
     * @param bool $useCache
246
     * @return TypoScriptConfiguration The Solr configuration for the requested tree.
247
     */
248 35
    public static function getConfigurationFromPageId(
249
        $pageId,
250
        $path,
251
        $initializeTsfe = false,
252
        $language = 0,
253
        $useCache = true
254
    ) {
255 35
        static $configurationsByCacheKey = array();
256 35
        $cacheId = md5($pageId . '|' . $path . '|' . $language);
257
258 35
        if (isset($configurationsByCacheKey[$cacheId])) {
259 28
            return $configurationsByCacheKey[$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 35
        if ($pageId == 0) {
266 1
            return self::buildTypoScriptConfigurationFromArray(array(), $pageId, $language, $path);
267
        }
268
269 34
        if ($useCache) {
270
            /** @var $cache TwoLevelCache */
271 34
            $cache = GeneralUtility::makeInstance(TwoLevelCache::class, 'tx_solr_configuration');
272 34
            $configurationToUse = $cache->get($cacheId);
273 34
        }
274
275 34
        if ($initializeTsfe) {
276 1
            self::initializeTsfe($pageId, $language);
277 1
            if (!empty($configurationToUse)) {
278
                return self::buildTypoScriptConfigurationFromArray($configurationToUse, $pageId, $language, $path);
279
            }
280 1
            $configurationToUse = self::getConfigurationFromInitializedTSFE($path);
281 1
        } else {
282 34
            if (!empty($configurationToUse)) {
283
                return self::buildTypoScriptConfigurationFromArray($configurationToUse, $pageId, $language, $path);
284
            }
285 34
            $configurationToUse = self::getConfigurationFromExistingTSFE($pageId, $path, $language);
286
        }
287
288 34
        if ($useCache) {
289 34
            $cache->set($cacheId, $configurationToUse);
0 ignored issues
show
Bug introduced by
The variable $cache does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
290 34
        }
291
292 34
        return $configurationsByCacheKey[$cacheId] = self::buildTypoScriptConfigurationFromArray($configurationToUse, $pageId, $language, $path);
293
    }
294
295
    /**
296
     * Builds the configuration object from a config array and returns it.
297
     *
298
     * @param array $configurationToUse
299
     * @param int $pageId
300
     * @param int $languageId
301
     * @param string $typoScriptPath
302
     * @return TypoScriptConfiguration
303
     */
304 35
    protected static function buildTypoScriptConfigurationFromArray(array $configurationToUse, $pageId, $languageId, $typoScriptPath)
305
    {
306 35
        $configurationManager = self::getConfigurationManager();
307 35
        return $configurationManager->getTypoScriptConfiguration($configurationToUse, $pageId, $languageId, $typoScriptPath);
308
    }
309
310
    /**
311
     * This function is used to retrieve the configuration from a previous initialized TSFE
312
     * (see: getConfigurationFromPageId)
313
     *
314
     * @param string $path
315
     * @return mixed
316
     */
317 1
    private static function getConfigurationFromInitializedTSFE($path)
318
    {
319
        /** @var $tmpl ExtendedTemplateService */
320 1
        $tmpl = GeneralUtility::makeInstance(ExtendedTemplateService::class);
321 1
        $configuration = $tmpl->ext_getSetup($GLOBALS['TSFE']->tmpl->setup, $path);
322 1
        $configurationToUse = $configuration[0];
323 1
        return $configurationToUse;
324
    }
325
326
    /**
327
     * This function is used to retrieve the configuration from an existing TSFE instance
328
     * @param $pageId
329
     * @param $path
330
     * @param $language
331
     * @return mixed
332
     */
333 34
    private static function getConfigurationFromExistingTSFE($pageId, $path, $language)
334
    {
335 34
        if (is_int($language)) {
336 33
            GeneralUtility::_GETset($language, 'L');
337 33
        }
338
339
            /** @var $pageSelect PageRepository */
340 34
        $pageSelect = GeneralUtility::makeInstance(PageRepository::class);
341 34
        $rootLine = $pageSelect->getRootLine($pageId);
342
343 34
        $initializedTsfe = false;
344 34
        $initializedPageSelect = false;
345 34
        if (empty($GLOBALS['TSFE']->sys_page)) {
346 34
            if (empty($GLOBALS['TSFE'])) {
347 34
                $GLOBALS['TSFE'] = new \stdClass();
348 34
                $GLOBALS['TSFE']->tmpl = new \stdClass();
349 34
                $GLOBALS['TSFE']->tmpl->rootLine = $rootLine;
350 34
                $GLOBALS['TSFE']->sys_page = $pageSelect;
351 34
                $GLOBALS['TSFE']->id = $pageId;
352 34
                $GLOBALS['TSFE']->tx_solr_initTsfe = 1;
353 34
                $initializedTsfe = true;
354 34
            }
355
356 34
            $GLOBALS['TSFE']->sys_page = $pageSelect;
357 34
            $initializedPageSelect = true;
358 34
        }
359
            /** @var $tmpl ExtendedTemplateService */
360 34
        $tmpl = GeneralUtility::makeInstance(ExtendedTemplateService::class);
361 34
        $tmpl->tt_track = false; // Do not log time-performance information
362 34
        $tmpl->init();
363 34
        $tmpl->runThroughTemplates($rootLine); // This generates the constants/config + hierarchy info for the template.
364 34
        $tmpl->generateConfig();
365
366 34
        $getConfigurationFromInitializedTSFEAndWriteToCache = $tmpl->ext_getSetup($tmpl->setup, $path);
367 34
        $configurationToUse = $getConfigurationFromInitializedTSFEAndWriteToCache[0];
368
369 34
        if ($initializedPageSelect) {
370 34
            $GLOBALS['TSFE']->sys_page = null;
371 34
        }
372 34
        if ($initializedTsfe) {
373 34
            unset($GLOBALS['TSFE']);
374 34
        }
375 34
        return $configurationToUse;
376
    }
377
378
    /**
379
     * Initializes the TSFE for a given page ID and language.
380
     *
381
     * @param int $pageId The page id to initialize the TSFE for
382
     * @param int $language System language uid, optional, defaults to 0
383
     * @param bool $useCache Use cache to reuse TSFE
384
     * @return void
385
     */
386 14
    public static function initializeTsfe(
387
        $pageId,
388
        $language = 0,
389
        $useCache = true
390
    ) {
391 14
        static $tsfeCache = array();
392
393
        // resetting, a TSFE instance with data from a different page Id could be set already
394 14
        unset($GLOBALS['TSFE']);
395
396 14
        $cacheId = $pageId . '|' . $language;
397
398 14
        if (!is_object($GLOBALS['TT'])) {
399 14
            $GLOBALS['TT'] = GeneralUtility::makeInstance(NullTimeTracker::class);
400 14
        }
401
402 14
        if (!isset($tsfeCache[$cacheId]) || !$useCache) {
403 14
            GeneralUtility::_GETset($language, 'L');
404
405 14
            $GLOBALS['TSFE'] = GeneralUtility::makeInstance(TypoScriptFrontendController::class,
406 14
                $GLOBALS['TYPO3_CONF_VARS'], $pageId, 0);
407
408
            // for certain situations we need to trick TSFE into granting us
409
            // access to the page in any case to make getPageAndRootline() work
410
            // see http://forge.typo3.org/issues/42122
411 14
            $pageRecord = BackendUtility::getRecord('pages', $pageId);
412 14
            $groupListBackup = $GLOBALS['TSFE']->gr_list;
413 14
            $GLOBALS['TSFE']->gr_list = $pageRecord['fe_group'];
414
415 14
            $GLOBALS['TSFE']->sys_page = GeneralUtility::makeInstance(PageRepository::class);
416 14
            $GLOBALS['TSFE']->getPageAndRootline();
417
418
            // restore gr_list
419 14
            $GLOBALS['TSFE']->gr_list = $groupListBackup;
420
421 14
            $GLOBALS['TSFE']->initTemplate();
422 14
            $GLOBALS['TSFE']->forceTemplateParsing = true;
423 14
            $GLOBALS['TSFE']->initFEuser();
424 14
            $GLOBALS['TSFE']->initUserGroups();
425
            // $GLOBALS['TSFE']->getCompressedTCarray(); // seems to cause conflicts sometimes
426
427 14
            $GLOBALS['TSFE']->no_cache = true;
428 14
            $GLOBALS['TSFE']->tmpl->start($GLOBALS['TSFE']->rootLine);
429 14
            $GLOBALS['TSFE']->no_cache = false;
430 14
            $GLOBALS['TSFE']->getConfigArray();
431
432 14
            $GLOBALS['TSFE']->settingLanguage();
433 14
            if (!$useCache) {
434
                $GLOBALS['TSFE']->settingLocale();
435
            }
436
437 14
            $GLOBALS['TSFE']->newCObj();
438 14
            $GLOBALS['TSFE']->absRefPrefix = self::getAbsRefPrefixFromTSFE($GLOBALS['TSFE']);
439 14
            $GLOBALS['TSFE']->calculateLinkVars();
440
441 14
            if ($useCache) {
442 14
                $tsfeCache[$cacheId] = $GLOBALS['TSFE'];
443 14
            }
444 14
        }
445
446 14
        if ($useCache) {
447 14
            $GLOBALS['TSFE'] = $tsfeCache[$cacheId];
448 14
            $GLOBALS['TSFE']->settingLocale();
449 14
        }
450 14
    }
451
452
    /**
453
     * Determines the rootpage ID for a given page.
454
     *
455
     * @param int $pageId A page ID somewhere in a tree.
456
     * @param bool $forceFallback Force the explicit detection and do not use the current frontend root line
457
     * @return int The page's tree branch's root page ID
458
     */
459 57
    public static function getRootPageId($pageId = 0, $forceFallback = false)
460
    {
461
        /** @var Rootline $rootLine */
462 57
        $rootLine = GeneralUtility::makeInstance(Rootline::class);
463 57
        $rootPageId = intval($pageId) ? intval($pageId) : $GLOBALS['TSFE']->id;
464
465
        // frontend
466 57
        if (!empty($GLOBALS['TSFE']->rootLine)) {
467 42
            $rootLine->setRootLineArray($GLOBALS['TSFE']->rootLine);
468 42
        }
469
470
        // fallback, backend
471 57
        if ($pageId != 0 && ($forceFallback || !$rootLine->getHasRootPage())) {
472 25
            $pageSelect = GeneralUtility::makeInstance(PageRepository::class);
473 25
            $rootLineArray = $pageSelect->getRootLine($pageId, '', true);
474 25
            $rootLine->setRootLineArray($rootLineArray);
475 25
        }
476
477 57
        $rootPageFromRootLine = $rootLine->getRootPageId();
478 57
        return $rootPageFromRootLine === 0 ? $rootPageId : $rootPageFromRootLine;
479
    }
480
481
    /**
482
     * Takes a page Id and checks whether the page is marked as root page.
483
     *
484
     * @param int $pageId Page ID
485
     * @return bool TRUE if the page is marked as root page, FALSE otherwise
486
     */
487 23
    public static function isRootPage($pageId)
488
    {
489 23
        $isRootPage = false;
490
491 23
        $page = BackendUtility::getRecord('pages', $pageId);
492 23
        if ($page['is_siteroot']) {
493 23
            $isRootPage = true;
494 23
        }
495
496 23
        return $isRootPage;
497
    }
498
499
    /**
500
     * Gets the site hash for a domain
501
     *
502
     * @param string $domain Domain to calculate the site hash for.
503
     * @return string site hash for $domain
504
     */
505 44
    public static function getSiteHashForDomain($domain)
506
    {
507 44
        static $siteHashes = [];
508 44
        if (isset($siteHashes[$domain])) {
509 43
            return $siteHashes[$domain];
510
        }
511
512 44
        $siteHashes[$domain] = sha1(
513
            $domain .
514 44
            $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] .
515
            'tx_solr'
516 44
        );
517
518 44
        return $siteHashes[$domain];
519
    }
520
521
    /**
522
     * Resolves magic keywords in allowed sites configuration.
523
     * Supported keywords:
524
     *   __solr_current_site - The domain of the site the query has been started from
525
     *   __current_site - Same as __solr_current_site
526
     *   __all - Adds all domains as allowed sites
527
     *   * - Same as __all
528
     *
529
     * @param int $pageId A page ID that is then resolved to the site it belongs to
530
     * @param string $allowedSitesConfiguration TypoScript setting for allowed sites
531
     * @return string List of allowed sites/domains, magic keywords resolved
532
     */
533 23
    public static function resolveSiteHashAllowedSites(
534
        $pageId,
535
        $allowedSitesConfiguration
536
    ) {
537 23
        if ($allowedSitesConfiguration == '*' || $allowedSitesConfiguration == '__all') {
538
            $sites = Site::getAvailableSites();
539
            $domains = array();
540
            foreach ($sites as $site) {
541
                $domains[] = $site->getDomain();
542
            }
543
544
            $allowedSites = implode(',', $domains);
545
        } else {
546 23
            $allowedSites = str_replace(
547 23
                array('__solr_current_site', '__current_site'),
548 23
                Site::getSiteByPageId($pageId)->getDomain(),
549
                $allowedSitesConfiguration
550 23
            );
551
        }
552
553 23
        return $allowedSites;
554
    }
555
556
    /**
557
     * Check if record ($table, $uid) is a workspace record
558
     *
559
     * @param string $table The table the record belongs to
560
     * @param int $uid The record's uid
561
     * @return bool TRUE if the record is in a draft workspace, FALSE if it's a LIVE record
562
     */
563 16
    public static function isDraftRecord($table, $uid)
564
    {
565 16
        $isWorkspaceRecord = false;
566
567 16
        if (BackendUtility::isTableWorkspaceEnabled($table)) {
568 16
            $record = BackendUtility::getRecord($table, $uid);
569
570 16
            if ($record['pid'] == '-1' || $record['t3ver_state'] > 0) {
571
                $isWorkspaceRecord = true;
572
            }
573 16
        }
574
575 16
        return $isWorkspaceRecord;
576
    }
577
578
    /**
579
     * Checks whether a record is a localization overlay.
580
     *
581
     * @param string $tableName The record's table name
582
     * @param array $record The record to check
583
     * @return bool TRUE if the record is a language overlay, FALSE otherwise
584
     */
585 11
    public static function isLocalizedRecord($tableName, array $record)
586
    {
587 11
        $isLocalizedRecord = false;
588
589 11
        if (isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])) {
590 4
            $translationOriginalPointerField = $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'];
591
592 4
            if ($record[$translationOriginalPointerField] > 0) {
593 3
                $isLocalizedRecord = true;
594 3
            }
595 4
        }
596
597 11
        return $isLocalizedRecord;
598
    }
599
600
    /**
601
     * Check if the page type of a page record is allowed
602
     *
603
     * @param array $pageRecord The pages database row
604
     *
605
     * @return bool TRUE if the page type is allowed, otherwise FALSE
606
     */
607 13
    public static function isAllowedPageType(array $pageRecord)
608
    {
609 13
        $isAllowedPageType = false;
610 13
        $allowedPageTypes = self::getAllowedPageTypes($pageRecord['uid']);
611
612 13
        if (in_array($pageRecord['doktype'], $allowedPageTypes)) {
613 12
            $isAllowedPageType = true;
614 12
        }
615
616 13
        return $isAllowedPageType;
617
    }
618
619
    /**
620
     * Get allowed page types
621
     *
622
     * @param int $pageId Page ID
623
     *
624
     * @return array Allowed page types to compare to a doktype of a page record
625
     */
626 13
    public static function getAllowedPageTypes($pageId)
627
    {
628 13
        $rootPath = '';
629 13
        $configuration = self::getConfigurationFromPageId($pageId, $rootPath);
630 13
        return $configuration->getIndexQueuePagesAllowedPageTypesArray();
631
    }
632
633
    /**
634
     * Method to check if a page exists.
635
     *
636
     * @param int $pageId
637
     * @return bool
638
     */
639
    public static function pageExists($pageId)
640
    {
641
        $page = BackendUtility::getRecord('pages', (int)$pageId, 'uid');
642
643
        if (!is_array($page) || $page['uid'] != $pageId) {
644
            return false;
645
        }
646
647
        return true;
648
    }
649
650
    /**
651
     * Resolves the configured absRefPrefix to a valid value and resolved if absRefPrefix
652
     * is set to "auto".
653
     *
654
     * @param TypoScriptFrontendController $TSFE
655
     * @return string
656
     */
657 14
    public static function getAbsRefPrefixFromTSFE(TypoScriptFrontendController $TSFE)
658
    {
659 14
        $absRefPrefix = '';
660 14
        if (empty($TSFE->config['config']['absRefPrefix'])) {
661 11
            return $absRefPrefix;
662
        }
663
664 3
        $absRefPrefix = trim($TSFE->config['config']['absRefPrefix']);
665 3
        if ($absRefPrefix === 'auto') {
666 1
            $absRefPrefix = GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
667 1
        }
668
669 3
        return $absRefPrefix;
670
    }
671
672
    /**
673
     * This function can be used to check if one of the strings in needles is
674
     * contained in the haystack.
675
     *
676
     *
677
     * Example:
678
     *
679
     * haystack: the brown fox
680
     * needles: ['hello', 'world']
681
     * result: false
682
     *
683
     * haystack: the brown fox
684
     * needles: ['is', 'fox']
685
     * result: true
686
     *
687
     * @param string $haystack
688
     * @param array $needles
689
     * @return bool
690
     */
691 33
    public static function containsOneOfTheStrings($haystack, array $needles)
692
    {
693 33
        foreach ($needles as $needle) {
694 33
            $position = strpos($haystack, $needle);
695 33
            if ($position !== false) {
696 3
                return true;
697
            }
698 30
        }
699
700 30
        return false;
701
    }
702
}
703