Completed
Branch master (33af51)
by Timo
04:12
created

Util::getSolrConfigurationFromPageId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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