Passed
Pull Request — master (#1249)
by
unknown
19:13
created

Util::getConfigurationFromPageId()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 42
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 7.0071

Importance

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