Passed
Push — master ( c790c5...628def )
by Timo
04:12
created

Util::pageExists()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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