Completed
Branch master (b9fc31)
by Timo
05:19
created

Util::camelize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
510
    }
511
512
    /**
513
     * Gets the site hash for a domain
514
     *
515
     * @param string $domain Domain to calculate the site hash for.
516
     * @return string site hash for $domain
517
     */
518 48
    public static function getSiteHashForDomain($domain)
519
    {
520 48
        static $siteHashes = [];
521 48
        if (isset($siteHashes[$domain])) {
522 46
            return $siteHashes[$domain];
523
        }
524
525 48
        $siteHashes[$domain] = sha1(
526
            $domain .
527 48
            $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] .
528
            'tx_solr'
529 48
        );
530
531 48
        return $siteHashes[$domain];
532
    }
533
534
    /**
535
     * Resolves magic keywords in allowed sites configuration.
536
     * Supported keywords:
537
     *   __solr_current_site - The domain of the site the query has been started from
538
     *   __current_site - Same as __solr_current_site
539
     *   __all - Adds all domains as allowed sites
540
     *   * - Same as __all
541
     *
542
     * @param int $pageId A page ID that is then resolved to the site it belongs to
543
     * @param string $allowedSitesConfiguration TypoScript setting for allowed sites
544
     * @return string List of allowed sites/domains, magic keywords resolved
545
     */
546 24
    public static function resolveSiteHashAllowedSites(
547
        $pageId,
548
        $allowedSitesConfiguration
549
    ) {
550 24
        if ($allowedSitesConfiguration == '*' || $allowedSitesConfiguration == '__all') {
551
            $sites = Site::getAvailableSites();
552
            $domains = [];
553
            foreach ($sites as $site) {
554
                $domains[] = $site->getDomain();
555
            }
556
557
            $allowedSites = implode(',', $domains);
558
        } else {
559 24
            $allowedSites = str_replace(
560 24
                ['__solr_current_site', '__current_site'],
561 24
                Site::getSiteByPageId($pageId)->getDomain(),
562
                $allowedSitesConfiguration
563 24
            );
564
        }
565
566 24
        return $allowedSites;
567
    }
568
569
    /**
570
     * Check if record ($table, $uid) is a workspace record
571
     *
572
     * @param string $table The table the record belongs to
573
     * @param int $uid The record's uid
574
     * @return bool TRUE if the record is in a draft workspace, FALSE if it's a LIVE record
575
     */
576 18
    public static function isDraftRecord($table, $uid)
577
    {
578 18
        $isWorkspaceRecord = false;
579
580 18
        if ((ExtensionManagementUtility::isLoaded('workspaces')) && (BackendUtility::isTableWorkspaceEnabled($table))) {
581
            $record = BackendUtility::getRecord($table, $uid);
582
583
            if ($record['pid'] == '-1' || $record['t3ver_state'] > 0) {
584
                $isWorkspaceRecord = true;
585
            }
586
        }
587
588 18
        return $isWorkspaceRecord;
589
    }
590
591
    /**
592
     * Checks whether a record is a localization overlay.
593
     *
594
     * @param string $tableName The record's table name
595
     * @param array $record The record to check
596
     * @return bool TRUE if the record is a language overlay, FALSE otherwise
597
     */
598 13
    public static function isLocalizedRecord($tableName, array $record)
599
    {
600 13
        $isLocalizedRecord = false;
601
602 13
        if (isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])) {
603 4
            $translationOriginalPointerField = $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'];
604
605 4
            if ($record[$translationOriginalPointerField] > 0) {
606 3
                $isLocalizedRecord = true;
607 3
            }
608 4
        }
609
610 13
        return $isLocalizedRecord;
611
    }
612
613
    /**
614
     * Check if the page type of a page record is allowed
615
     *
616
     * @param array $pageRecord The pages database row
617
     * @param string $configurationName The name of the configuration to use.
618
     *
619
     * @return bool TRUE if the page type is allowed, otherwise FALSE
620
     */
621 15
    public static function isAllowedPageType(array $pageRecord, $configurationName = 'pages')
622
    {
623 15
        $isAllowedPageType = false;
624 15
        $configurationName = is_null($configurationName) ? 'pages' : $configurationName;
625 15
        $allowedPageTypes = self::getAllowedPageTypes($pageRecord['uid'], $configurationName);
626
627 15
        if (in_array($pageRecord['doktype'], $allowedPageTypes)) {
628 14
            $isAllowedPageType = true;
629 14
        }
630
631 15
        return $isAllowedPageType;
632
    }
633
634
    /**
635
     * Get allowed page types
636
     *
637
     * @param int $pageId Page ID
638
     * @param string $configurationName The name of the configuration to use.
639
     *
640
     * @return array Allowed page types to compare to a doktype of a page record
641
     */
642 15
    public static function getAllowedPageTypes($pageId, $configurationName = 'pages')
643
    {
644 15
        $rootPath = '';
645 15
        $configuration = self::getConfigurationFromPageId($pageId, $rootPath);
646 15
        return $configuration->getIndexQueueAllowedPageTypesArrayByConfigurationName($configurationName);
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 1
        }
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 3
                return true;
713
            }
714 30
        }
715
716 30
        return false;
717
    }
718
}
719