Failed Conditions
Push — master ( 97e960...0b92b6 )
by Timo
23:14
created

Classes/Util.php (1 issue)

Labels
Severity
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 3 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\Site\SiteRepository;
28
use ApacheSolrForTypo3\Solr\System\Cache\TwoLevelCache;
29
use ApacheSolrForTypo3\Solr\System\Configuration\ConfigurationManager;
30
use ApacheSolrForTypo3\Solr\System\Configuration\ConfigurationPageResolver;
31
use ApacheSolrForTypo3\Solr\System\Configuration\ExtensionConfiguration;
32
use ApacheSolrForTypo3\Solr\System\Configuration\TypoScriptConfiguration;
33
use ApacheSolrForTypo3\Solr\System\Mvc\Frontend\Controller\OverriddenTypoScriptFrontendController;
34
use TYPO3\CMS\Backend\Utility\BackendUtility;
0 ignored issues
show
The type TYPO3\CMS\Backend\Utility\BackendUtility was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
35
use TYPO3\CMS\Core\TimeTracker\TimeTracker;
36
use TYPO3\CMS\Core\TypoScript\ExtendedTemplateService;
37
use TYPO3\CMS\Core\Utility\GeneralUtility;
38
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
39
use TYPO3\CMS\Frontend\Page\PageRepository;
40
41
/**
42
 * Utility class for tx_solr
43
 *
44
 * @author Ingo Renner <[email protected]>
45
 */
46
class Util
47
{
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 66
    public static function getPageDocumentId($uid, $typeNum = 0, $language = 0, $accessGroups = '0,-1', $mountPointParameter = '')
60
    {
61 66
        $additionalParameters = $typeNum . '/' . $language . '/' . $accessGroups;
62
63 66
        if ((string)$mountPointParameter !== '') {
64 2
            $additionalParameters = $mountPointParameter . '/' . $additionalParameters;
65
        }
66
67 66
        $documentId = self::getDocumentId('pages', $uid, $uid, $additionalParameters);
68
69 66
        return $documentId;
70
    }
71
72
    /**
73
     * Generates a document id in the form $siteHash/$type/$uid.
74
     *
75
     * @param string $table The records table name
76
     * @param int $rootPageId The record's site root id
77
     * @param int $uid The record's uid
78
     * @param string $additionalIdParameters Additional ID parameters
79
     * @return string A document id
80
     */
81 85
    public static function getDocumentId($table, $rootPageId, $uid, $additionalIdParameters = '')
82
    {
83 85
        $siteRepository = GeneralUtility::makeInstance(SiteRepository::class);
84 85
        $site = $siteRepository->getSiteByPageId($rootPageId);
85 85
        $siteHash = $site->getSiteHash();
86
87 85
        $documentId = $siteHash . '/' . $table . '/' . $uid;
88 85
        if (!empty($additionalIdParameters)) {
89 66
            $documentId .= '/' . $additionalIdParameters;
90
        }
91
92 85
        return $documentId;
93
    }
94
95
    /**
96
     * Shortcut to retrieve the TypoScript configuration for EXT:solr
97
     * (plugin.tx_solr) from TSFE.
98
     *
99
     * @return TypoScriptConfiguration
100
     */
101 175
    public static function getSolrConfiguration()
102
    {
103 175
        $configurationManager = GeneralUtility::makeInstance(ConfigurationManager::class);
104 175
        return $configurationManager->getTypoScriptConfiguration();
105
    }
106
107
    /**
108
     * Gets the Solr configuration for a specific root page id.
109
     * To be used from the backend.
110
     *
111
     * @param int $pageId Id of the (root) page to get the Solr configuration from.
112
     * @param bool $initializeTsfe Optionally initializes a full TSFE to get the configuration, defaults to FALSE
113
     * @param int $language System language uid, optional, defaults to 0
114
     * @return TypoScriptConfiguration The Solr configuration for the requested tree.
115
     */
116 151
    public static function getSolrConfigurationFromPageId($pageId, $initializeTsfe = false, $language = 0)
117
    {
118 151
        $rootPath = '';
119 151
        return self::getConfigurationFromPageId($pageId, $rootPath, $initializeTsfe, $language);
120
    }
121
122
    /**
123
     * Loads the TypoScript configuration for a given page id and language.
124
     * Language usage may be disabled to get the default TypoScript
125
     * configuration.
126
     *
127
     * @param int $pageId Id of the (root) page to get the Solr configuration from.
128
     * @param string $path The TypoScript configuration path to retrieve.
129
     * @param bool $initializeTsfe Optionally initializes a full TSFE to get the configuration, defaults to FALSE
130
     * @param int $language System language uid, optional, defaults to 0
131
     * @param bool $useTwoLevelCache Flag to enable the two level cache for the typoscript configuration array
132
     * @return TypoScriptConfiguration The Solr configuration for the requested tree.
133
     */
134 152
    public static function getConfigurationFromPageId($pageId, $path, $initializeTsfe = false, $language = 0, $useTwoLevelCache = true)
135
    {
136 152
        $pageId = self::getConfigurationPageIdToUse($pageId);
137
138 152
        static $configurationObjectCache = [];
139 152
        $cacheId = md5($pageId . '|' . $path . '|' . $language);
140 152
        if (isset($configurationObjectCache[$cacheId])) {
141 69
            return $configurationObjectCache[$cacheId];
142
        }
143
144
        // If we're on UID 0, we cannot retrieve a configuration currently.
145
        // getRootline() below throws an exception (since #typo3-60 )
146
        // as UID 0 cannot have any parent rootline by design.
147 152
        if ($pageId == 0) {
148 2
            return $configurationObjectCache[$cacheId] = self::buildTypoScriptConfigurationFromArray([], $pageId, $language, $path);
149
        }
150
151 151
        if ($useTwoLevelCache) {
152
            /** @var $cache TwoLevelCache */
153 151
            $cache = GeneralUtility::makeInstance(TwoLevelCache::class, 'tx_solr_configuration');
154 151
            $configurationArray = $cache->get($cacheId);
155
        }
156
157 151
        if (!empty($configurationArray)) {
158
            // we have a cache hit and can return it.
159
            return $configurationObjectCache[$cacheId] = self::buildTypoScriptConfigurationFromArray($configurationArray, $pageId, $language, $path);
160
        }
161
162
        // we have nothing in the cache. We need to build the configurationToUse
163 151
        $configurationArray = self::buildConfigurationArray($pageId, $path, $initializeTsfe, $language);
164
165 151
        if ($useTwoLevelCache && isset($cache)) {
166 151
            $cache->set($cacheId, $configurationArray);
167
        }
168
169 151
        return $configurationObjectCache[$cacheId] = self::buildTypoScriptConfigurationFromArray($configurationArray, $pageId, $language, $path);
170
    }
171
172
    /**
173
     * This method retrieves the closest pageId where a configuration is located, when this
174
     * feature is enabled.
175
     *
176
     * @param int $pageId
177
     * @return int
178
     */
179 152
    protected static function getConfigurationPageIdToUse($pageId)
180
    {
181 152
        $extensionConfiguration = GeneralUtility::makeInstance(ExtensionConfiguration::class);
182 152
        if ($extensionConfiguration->getIsUseConfigurationFromClosestTemplateEnabled()) {
183
            /** @var $configurationPageResolve ConfigurationPageResolver */
184
            $configurationPageResolver = GeneralUtility::makeInstance(ConfigurationPageResolver::class);
185
            $pageId = $configurationPageResolver->getClosestPageIdWithActiveTemplate($pageId);
186
            return $pageId;
187
        }
188 152
        return $pageId;
189
    }
190
191
    /**
192
     * Initializes a TSFE, if required and builds an configuration array, containing the solr configuration.
193
     *
194
     * @param integer $pageId
195
     * @param string $path
196
     * @param boolean $initializeTsfe
197
     * @param integer $language
198
     * @return array
199
     */
200 151
    protected static function buildConfigurationArray($pageId, $path, $initializeTsfe, $language)
201
    {
202 151
        if ($initializeTsfe) {
203 7
            self::initializeTsfe($pageId, $language);
204 6
            $configurationToUse = self::getConfigurationFromInitializedTSFE($path);
205
        } else {
206 151
            $configurationToUse = self::getConfigurationFromExistingTSFE($pageId, $path, $language);
207
        }
208
209 151
        return is_array($configurationToUse) ? $configurationToUse : [];
210
    }
211
212
    /**
213
     * Builds the configuration object from a config array and returns it.
214
     *
215
     * @param array $configurationToUse
216
     * @param int $pageId
217
     * @param int $languageId
218
     * @param string $typoScriptPath
219
     * @return TypoScriptConfiguration
220
     */
221 152
    protected static function buildTypoScriptConfigurationFromArray(array $configurationToUse, $pageId, $languageId, $typoScriptPath)
222
    {
223 152
        $configurationManager = GeneralUtility::makeInstance(ConfigurationManager::class);
224 152
        return $configurationManager->getTypoScriptConfiguration($configurationToUse, $pageId, $languageId, $typoScriptPath);
225
    }
226
227
    /**
228
     * This function is used to retrieve the configuration from a previous initialized TSFE
229
     * (see: getConfigurationFromPageId)
230
     *
231
     * @param string $path
232
     * @return mixed
233
     */
234 6
    private static function getConfigurationFromInitializedTSFE($path)
235
    {
236
        /** @var $tmpl ExtendedTemplateService */
237 6
        $tmpl = GeneralUtility::makeInstance(ExtendedTemplateService::class);
238 6
        $configuration = $tmpl->ext_getSetup($GLOBALS['TSFE']->tmpl->setup, $path);
239 6
        $configurationToUse = $configuration[0];
240 6
        return $configurationToUse;
241
    }
242
243
    /**
244
     * This function is used to retrieve the configuration from an existing TSFE instance
245
     * @param $pageId
246
     * @param $path
247
     * @param $language
248
     * @return mixed
249
     */
250 151
    private static function getConfigurationFromExistingTSFE($pageId, $path, $language)
251
    {
252 151
        if (is_int($language)) {
253 151
            GeneralUtility::_GETset($language, 'L');
254
        }
255
256
            /** @var $pageSelect PageRepository */
257 151
        $pageSelect = GeneralUtility::makeInstance(PageRepository::class);
258 151
        $rootLine = $pageSelect->getRootLine($pageId);
259
260 151
        $initializedTsfe = false;
261 151
        $initializedPageSelect = false;
262 151
        if (empty($GLOBALS['TSFE']->sys_page)) {
263 81
            if (empty($GLOBALS['TSFE'])) {
264 81
                $GLOBALS['TSFE'] = new \stdClass();
265 81
                $GLOBALS['TSFE']->tmpl = new \stdClass();
266 81
                $GLOBALS['TSFE']->tmpl->rootLine = $rootLine;
267 81
                $GLOBALS['TSFE']->sys_page = $pageSelect;
268 81
                $GLOBALS['TSFE']->id = $pageId;
269 81
                $GLOBALS['TSFE']->tx_solr_initTsfe = 1;
270 81
                $initializedTsfe = true;
271
            }
272
273 81
            $GLOBALS['TSFE']->sys_page = $pageSelect;
274 81
            $initializedPageSelect = true;
275
        }
276
            /** @var $tmpl ExtendedTemplateService */
277 151
        $tmpl = GeneralUtility::makeInstance(ExtendedTemplateService::class);
278 151
        $tmpl->tt_track = false; // Do not log time-performance information
279 151
        $tmpl->init();
280 151
        $tmpl->runThroughTemplates($rootLine); // This generates the constants/config + hierarchy info for the template.
281 151
        $tmpl->generateConfig();
282
283 151
        $getConfigurationFromInitializedTSFEAndWriteToCache = $tmpl->ext_getSetup($tmpl->setup, $path);
284 151
        $configurationToUse = $getConfigurationFromInitializedTSFEAndWriteToCache[0];
285
286 151
        if ($initializedPageSelect) {
287 81
            $GLOBALS['TSFE']->sys_page = null;
288
        }
289 151
        if ($initializedTsfe) {
290 81
            unset($GLOBALS['TSFE']);
291
        }
292 151
        return $configurationToUse;
293
    }
294
295
    /**
296
     * Initializes the TSFE for a given page ID and language.
297
     *
298
     * @param int $pageId The page id to initialize the TSFE for
299
     * @param int $language System language uid, optional, defaults to 0
300
     * @param bool $useCache Use cache to reuse TSFE
301
     * @return void
302
     */
303 24
    public static function initializeTsfe($pageId, $language = 0, $useCache = true)
304
    {
305 24
        static $tsfeCache = [];
306
307
        // resetting, a TSFE instance with data from a different page Id could be set already
308 24
        unset($GLOBALS['TSFE']);
309
310 24
        $cacheId = $pageId . '|' . $language;
311
312 24
        if (!is_object($GLOBALS['TT'])) {
313 24
            $GLOBALS['TT'] = GeneralUtility::makeInstance(TimeTracker::class, false);
314
        }
315
316 24
        if (!isset($tsfeCache[$cacheId]) || !$useCache) {
317 24
            GeneralUtility::_GETset($language, 'L');
318
319 24
            $GLOBALS['TSFE'] = GeneralUtility::makeInstance(OverriddenTypoScriptFrontendController::class,
320 24
                $GLOBALS['TYPO3_CONF_VARS'], $pageId, 0);
321
322
            // for certain situations we need to trick TSFE into granting us
323
            // access to the page in any case to make getPageAndRootline() work
324
            // see http://forge.typo3.org/issues/42122
325 24
            $pageRecord = BackendUtility::getRecord('pages', $pageId, 'fe_group');
326 24
            $groupListBackup = $GLOBALS['TSFE']->gr_list;
327 24
            $GLOBALS['TSFE']->gr_list = $pageRecord['fe_group'];
328
329 24
            $GLOBALS['TSFE']->sys_page = GeneralUtility::makeInstance(PageRepository::class);
330 24
            $GLOBALS['TSFE']->getPageAndRootline();
331
332
            // restore gr_list
333 24
            $GLOBALS['TSFE']->gr_list = $groupListBackup;
334
335 24
            $GLOBALS['TSFE']->initTemplate();
336 24
            $GLOBALS['TSFE']->forceTemplateParsing = true;
337 24
            $GLOBALS['TSFE']->initFEuser();
338 24
            $GLOBALS['TSFE']->initUserGroups();
339
            //  $GLOBALS['TSFE']->getCompressedTCarray(); // seems to cause conflicts sometimes
340
341 24
            $GLOBALS['TSFE']->no_cache = true;
342 24
            $GLOBALS['TSFE']->tmpl->start($GLOBALS['TSFE']->rootLine);
343 24
            $GLOBALS['TSFE']->no_cache = false;
344 24
            $GLOBALS['TSFE']->getConfigArray();
345
346 24
            $GLOBALS['TSFE']->settingLanguage();
347 24
            if (!$useCache) {
348
                $GLOBALS['TSFE']->settingLocale();
349
            }
350
351 24
            $GLOBALS['TSFE']->newCObj();
352 24
            $GLOBALS['TSFE']->absRefPrefix = self::getAbsRefPrefixFromTSFE($GLOBALS['TSFE']);
353 24
            $GLOBALS['TSFE']->calculateLinkVars();
354
355 24
            if ($useCache) {
356 24
                $tsfeCache[$cacheId] = $GLOBALS['TSFE'];
357
            }
358
        }
359
360 24
        if ($useCache) {
361 24
            $GLOBALS['TSFE'] = $tsfeCache[$cacheId];
362 24
            $GLOBALS['TSFE']->settingLocale();
363
        }
364 24
    }
365
366
    /**
367
     * Check if record ($table, $uid) is a workspace record
368
     *
369
     * @param string $table The table the record belongs to
370
     * @param int $uid The record's uid
371
     * @return bool TRUE if the record is in a draft workspace, FALSE if it's a LIVE record
372
     */
373 39
    public static function isDraftRecord($table, $uid)
374
    {
375 39
        $isWorkspaceRecord = false;
376
377 39
        if ((ExtensionManagementUtility::isLoaded('workspaces')) && (BackendUtility::isTableWorkspaceEnabled($table))) {
378
            $record = BackendUtility::getRecord($table, $uid, 'pid, t3ver_state');
379
380
            if ($record['pid'] == '-1' || $record['t3ver_state'] > 0) {
381
                $isWorkspaceRecord = true;
382
            }
383
        }
384
385 39
        return $isWorkspaceRecord;
386
    }
387
388
    /**
389
     * Checks whether a record is a localization overlay.
390
     *
391
     * @param string $tableName The record's table name
392
     * @param array $record The record to check
393
     * @return bool TRUE if the record is a language overlay, FALSE otherwise
394
     */
395 32
    public static function isLocalizedRecord($tableName, array $record)
396
    {
397 32
        $isLocalizedRecord = false;
398
399 32
        if (isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])) {
400 7
            $translationOriginalPointerField = $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'];
401
402 7
            if ($record[$translationOriginalPointerField] > 0) {
403 3
                $isLocalizedRecord = true;
404
            }
405
        }
406
407 32
        return $isLocalizedRecord;
408
    }
409
410
    /**
411
     * Check if the page type of a page record is allowed
412
     *
413
     * @param array $pageRecord The pages database row
414
     * @param string $configurationName The name of the configuration to use.
415
     *
416
     * @return bool TRUE if the page type is allowed, otherwise FALSE
417
     */
418 30
    public static function isAllowedPageType(array $pageRecord, $configurationName = 'pages')
419
    {
420 30
        $isAllowedPageType = false;
421 30
        $configurationName = is_null($configurationName) ? 'pages' : $configurationName;
422 30
        $allowedPageTypes = self::getAllowedPageTypes($pageRecord['uid'], $configurationName);
423
424 30
        if (in_array($pageRecord['doktype'], $allowedPageTypes)) {
425 29
            $isAllowedPageType = true;
426
        }
427
428 30
        return $isAllowedPageType;
429
    }
430
431
    /**
432
     * Get allowed page types
433
     *
434
     * @param int $pageId Page ID
435
     * @param string $configurationName The name of the configuration to use.
436
     *
437
     * @return array Allowed page types to compare to a doktype of a page record
438
     */
439 30
    public static function getAllowedPageTypes($pageId, $configurationName = 'pages')
440
    {
441 30
        $rootPath = '';
442 30
        $configuration = self::getConfigurationFromPageId($pageId, $rootPath);
443 30
        return $configuration->getIndexQueueAllowedPageTypesArrayByConfigurationName($configurationName);
444
    }
445
446
    /**
447
     * Resolves the configured absRefPrefix to a valid value and resolved if absRefPrefix
448
     * is set to "auto".
449
     *
450
     * @param OverriddenTypoScriptFrontendController $TSFE
451
     * @return string
452
     */
453 24
    public static function getAbsRefPrefixFromTSFE(OverriddenTypoScriptFrontendController $TSFE)
454
    {
455 24
        $absRefPrefix = '';
456 24
        if (empty($TSFE->config['config']['absRefPrefix'])) {
457 21
            return $absRefPrefix;
458
        }
459
460 3
        $absRefPrefix = trim($TSFE->config['config']['absRefPrefix']);
461 3
        if ($absRefPrefix === 'auto') {
462 1
            $absRefPrefix = GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
463
        }
464
465 3
        return $absRefPrefix;
466
    }
467
468
    /**
469
     * @todo This method is just added for pages_language_overlay compatibility checks and will be removed when TYPO8 support is dropped
470
     * @return boolean
471
     */
472 236
    public static function getIsTYPO3VersionBelow9()
473
    {
474 236
        return (bool)version_compare(TYPO3_branch, '9.0', '<');
475
    }
476
477
    /**
478
     * @todo This method is just added for pages_language_overlay compatibility checks and will be removed when TYPO8 support is dropped
479
     * @return string
480
     */
481
    public static function getPageOverlayTableName()
482
    {
483
        return self::getIsTYPO3VersionBelow9() ? 'pages_language_overlay' : 'pages';
484
    }
485
486
    /**
487
     * This function can be used to check if one of the strings in needles is
488
     * contained in the haystack.
489
     *
490
     *
491
     * Example:
492
     *
493
     * haystack: the brown fox
494
     * needles: ['hello', 'world']
495
     * result: false
496
     *
497
     * haystack: the brown fox
498
     * needles: ['is', 'fox']
499
     * result: true
500
     *
501
     * @param string $haystack
502
     * @param array $needles
503
     * @return bool
504
     */
505 52
    public static function containsOneOfTheStrings($haystack, array $needles)
506
    {
507 52
        foreach ($needles as $needle) {
508 52
            $position = strpos($haystack, $needle);
509 52
            if ($position !== false) {
510 52
                return true;
511
            }
512
        }
513
514 49
        return false;
515
    }
516
}
517