Completed
Pull Request — master (#747)
by Timo
16:40
created

Util::utcIsoToTimestamp()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
604
605 5
        if (isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])) {
606 1
            $translationOriginalPointerField = $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'];
607
608 1
            if ($record[$translationOriginalPointerField] > 0) {
609
                $isLocalizedRecord = true;
610
            }
611
        }
612
613 5
        return $isLocalizedRecord;
614
    }
615
616
    /**
617
     * Check if the page type of a page record is allowed
618
     *
619
     * @param array $pageRecord The pages database row
620
     *
621
     * @return bool TRUE if the page type is allowed, otherwise FALSE
622
     */
623 9
    public static function isAllowedPageType(array $pageRecord)
624
    {
625 9
        $isAllowedPageType = false;
626 9
        $allowedPageTypes = self::getAllowedPageTypes($pageRecord['uid']);
627
628 9
        if (in_array($pageRecord['doktype'], $allowedPageTypes)) {
629 8
            $isAllowedPageType = true;
630
        }
631
632 9
        return $isAllowedPageType;
633
    }
634
635
    /**
636
     * Get allowed page types
637
     *
638
     * @param int $pageId Page ID
639
     *
640
     * @return array Allowed page types to compare to a doktype of a page record
641
     */
642 9
    public static function getAllowedPageTypes($pageId)
643
    {
644 9
        $rootPath = '';
645 9
        $configuration = self::getConfigurationFromPageId($pageId, $rootPath);
646 9
        return $configuration->getIndexQueuePagesAllowedPageTypesArray();
647
    }
648
649
    /**
650
     * Method to check if a page exists.
651
     *
652
     * @param int $pageId
653
     * @return bool
654
     */
655
    public static function pageExists($pageId)
656
    {
657
        $page = BackendUtility::getRecord('pages', (int)$pageId, 'uid');
658
659
        if (!is_array($page) || $page['uid'] != $pageId) {
660
            return false;
661
        }
662
663
        return true;
664
    }
665
666
    /**
667
     * Resolves the configured absRefPrefix to a valid value and resolved if absRefPrefix
668
     * is set to "auto".
669
     *
670
     * @param TypoScriptFrontendController $TSFE
671
     * @return string
672
     */
673 14
    public static function getAbsRefPrefixFromTSFE(TypoScriptFrontendController $TSFE)
674
    {
675 14
        $absRefPrefix = '';
676 14
        if (empty($TSFE->config['config']['absRefPrefix'])) {
677 11
            return $absRefPrefix;
678
        }
679
680 3
        $absRefPrefix = trim($TSFE->config['config']['absRefPrefix']);
681 3
        if ($absRefPrefix === 'auto') {
682 1
            $absRefPrefix = GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
683
        }
684
685 3
        return $absRefPrefix;
686
    }
687
688
    /**
689
     * This function can be used to check if one of the strings in needles is
690
     * contained in the haystack.
691
     *
692
     *
693
     * Example:
694
     *
695
     * haystack: the brown fox
696
     * needles: ['hello', 'world']
697
     * result: false
698
     *
699
     * haystack: the brown fox
700
     * needles: ['is', 'fox']
701
     * result: true
702
     *
703
     * @param string $haystack
704
     * @param array $needles
705
     * @return bool
706
     */
707 33
    public static function containsOneOfTheStrings($haystack, array $needles)
708
    {
709 33
        foreach ($needles as $needle) {
710 33
            $position = strpos($haystack, $needle);
711 33
            if ($position !== false) {
712 33
                return true;
713
            }
714
        }
715
716 30
        return false;
717
    }
718
}
719