Completed
Push — master ( bbbeef...e4bcc6 )
by Timo
13s
created

Site::clearSitePagesCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1.037

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 3
cp 0.6667
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1.037
1
<?php
2
namespace ApacheSolrForTypo3\Solr;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2011-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 TYPO3\CMS\Backend\Utility\BackendUtility;
28
use TYPO3\CMS\Core\Utility\GeneralUtility;
29
30
/**
31
 * A site is a branch in a TYPO3 installation. Each site's root page is marked
32
 * by the "Use as Root Page" flag.
33
 *
34
 * @author Ingo Renner <[email protected]>
35
 */
36
class Site
37
{
38
39
    /**
40
     * Cache for ApacheSolrForTypo3\Solr\Site objects
41
     *
42
     * @var array
43
     */
44
    protected static $sitesCache = array();
45
    /**
46
     * Small cache for the list of pages in a site, so that the results of this
47
     * rather expensive operation can be used by all initializers without having
48
     * each initializer do it again.
49
     *
50
     * TODO Move to caching framework once TYPO3 4.6 is the minimum required
51
     * version.
52
     *
53
     * @var array
54
     */
55
    protected static $sitePagesCache = array();
56
    /**
57
     * Root page record.
58
     *
59
     * @var array
60
     */
61
    protected $rootPage = array();
62
    /**
63
     * The site's sys_language_mode
64
     *
65
     * @var string
66
     */
67
    protected $sysLanguageMode = null;
68
69
    /**
70
     * Constructor.
71
     *
72
     * @param int $rootPageId Site root page ID (uid). The page must be marked as site root ("Use as Root Page" flag).
73
     */
74 54
    public function __construct($rootPageId)
75
    {
76 54
        $page = BackendUtility::getRecord('pages', $rootPageId);
77
78 54
        if (!$page['is_siteroot']) {
79
            throw new \InvalidArgumentException(
80
                'The page for the given page ID \'' . $rootPageId
81
                . '\' is not marked as root page and can therefore not be used as site root page.',
82
                1309272922
83
            );
84
        }
85
86 54
        $this->rootPage = $page;
87 54
    }
88
89
    /**
90
     * Gets the Site for a specific page Id.
91
     *
92
     * @param int $pageId The page Id to get a Site object for.
93
     * @return Site Site for the given page Id.
94
     */
95 44
    public static function getSiteByPageId($pageId)
96
    {
97 44
        $rootPageId = Util::getRootPageId($pageId);
98
99 44
        if (!isset(self::$sitesCache[$rootPageId])) {
100 44
            self::$sitesCache[$rootPageId] = GeneralUtility::makeInstance(__CLASS__,
101
                $rootPageId);
102
        }
103
104 44
        return self::$sitesCache[$rootPageId];
105
    }
106
107
    /**
108
     * Creates a dropdown selector of available TYPO3 sites with Solr
109
     * configured.
110
     *
111
     * @param string $selectorName Name to be used in the select's name attribute
112
     * @param Site $selectedSite Optional, currently selected site
113
     * @return string Site selector HTML code
114
     * @todo Extract into own class like indexing configuration selector
115
     */
116
    public static function getAvailableSitesSelector(
117
        $selectorName,
118
        Site $selectedSite = null
119
    ) {
120
        $sites = self::getAvailableSites();
121
        $selector = '<select name="' . $selectorName . '" class="form-control">';
122
123
        foreach ($sites as $site) {
124
            $selectedAttribute = '';
125
            if ($selectedSite !== null && $site->getRootPageId() == $selectedSite->getRootPageId()) {
126
                $selectedAttribute = ' selected="selected"';
127
            }
128
129
            $selector .= '<option value="' . $site->getRootPageId() . '"' . $selectedAttribute . '>'
130
                . $site->getLabel()
131
                . '</option>';
132
        }
133
134
        $selector .= '</select>';
135
136
        return $selector;
137
    }
138
139
    /**
140
     * Gets all available TYPO3 sites with Solr configured.
141
     *
142
     * @param bool $stopOnInvalidSite
143
     *
144
     * @return Site[] An array of available sites
145
     */
146 14
    public static function getAvailableSites($stopOnInvalidSite = false)
147
    {
148 14
        $sites = array();
149
150 14
        $registry = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Registry');
151 14
        $servers = $registry->get('tx_solr', 'servers', array());
152
153 14
        foreach ($servers as $server) {
154 14
            if (isset($sites[$server['rootPageUid']])) {
155
                //get each site only once
156
                continue;
157
            }
158
159
            try {
160 14
                $sites[$server['rootPageUid']] = GeneralUtility::makeInstance(__CLASS__, $server['rootPageUid']);
161
            } catch (\InvalidArgumentException $e) {
162
                if ($stopOnInvalidSite) {
163 14
                    throw $e;
164
                }
165
            }
166
        }
167
168 14
        return $sites;
169
    }
170
171
    /**
172
     * Returns the first available Site.
173
     *
174
     * @param bool $stopOnInvalidSite
175
     *
176
     * @return Site
177
     */
178 13
    public static function getFirstAvailableSite($stopOnInvalidSite = false)
179
    {
180 13
        $sites = self::getAvailableSites($stopOnInvalidSite);
181 13
        return array_shift($sites);
182
    }
183
184
    /**
185
     * Clears the $sitePagesCache
186
     *
187
     */
188
    public static function clearSitePagesCache()
189 19
    {
190
        self::$sitePagesCache = array();
191 19
    }
192
193
    /**
194
     * Gets the site's root page ID (uid).
195
     *
196
     * @return int The site's root page ID.
197
     */
198
    public function getRootPageId()
199
    {
200 7
        return $this->rootPage['uid'];
201
    }
202 7
203 7
    /**
204
     * Gets the site's label. The label is build from the the site title and root
205 7
     * page ID (uid).
206 7
     *
207 7
     * @return string The site's label.
208 7
     */
209
    public function getLabel()
210 7
    {
211
        $rootlineTitles = array();
212
        $rootLine = BackendUtility::BEgetRootLine($this->rootPage['uid']);
213
        // Remove last
214
        array_pop($rootLine);
215
        $rootLine = array_reverse($rootLine);
216
        foreach ($rootLine as $rootLineItem) {
217
            $rootlineTitles[] = $rootLineItem['title'];
218 10
        }
219
        return implode(' - ', $rootlineTitles) . ', Root Page ID: ' . $this->rootPage['uid'];
220 10
    }
221
222
    /**
223
     * Gets the site's Solr TypoScript configuration (plugin.tx_solr.*)
224
     *
225
     * @return  \ApacheSolrForTypo3\Solr\System\Configuration\TypoScriptConfiguration The Solr TypoScript configuration
226
     */
227
    public function getSolrConfiguration()
228
    {
229
        return Util::getSolrConfigurationFromPageId($this->rootPage['uid']);
230
    }
231
232
    /**
233
     * Gets the system languages (IDs) for which Solr connections have been
234
     * configured.
235
     *
236
     * @return array Array of system language IDs for which connections have been configured on this site.
237
     */
238
    public function getLanguages()
239
    {
240
        $siteLanguages = array();
241
242
        $registry = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Registry');
243
        $solrConnections = $registry->get('tx_solr', 'servers');
244
245
        foreach ($solrConnections as $connectionKey => $solrConnection) {
246
            list($siteRootPageId, $systemLanguageId) = explode('|',
247
                $connectionKey);
248
249
            if ($siteRootPageId == $this->rootPage['uid']) {
250
                $siteLanguages[] = $systemLanguageId;
251
            }
252
        }
253
254
        return $siteLanguages;
255 1
    }
256
257 1
    /**
258
     * Gets the site's default language as configured in
259 1
     * config.sys_language_uid. If sys_language_uid is not set, 0 is assumed to
260 1
     * be the default.
261 1
     *
262 1
     * @return int The site's default language.
263 1
     */
264
    public function getDefaultLanguage()
265
    {
266 1
        $siteDefaultLanguage = 0;
267
268 1
        $configuration = Util::getConfigurationFromPageId(
269
            $this->rootPage['uid'],
270 1
            'config',
271
            false,
272
            false
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
273
        );
274
275
        $siteDefaultLanguage = $configuration->getValueByPathOrDefaultValue('sys_language_uid', $siteDefaultLanguage);
276
        // default language is set through default L GET parameter -> overruling config.sys_language_uid
277
        $siteDefaultLanguage = $configuration->getValueByPathOrDefaultValue('defaultGetVars.L', $siteDefaultLanguage);
278
279
        return $siteDefaultLanguage;
280
    }
281 5
282
    /**
283 5
     * Generates a list of page IDs in this site. Attention, this includes
284 5
     * all page types! Deleted pages are not included.
285
     *
286 5
     * @param int|string $rootPageId Page ID from where to start collection sub pages
287 5
     * @param int $maxDepth Maximum depth to descend into the site tree
288 5
     * @return array Array of pages (IDs) in this site
289 5
     */
290 5
    public function getPages($rootPageId = 'SITE_ROOT', $maxDepth = 999)
291
    {
292
        $pageIds = array();
293 5
        $maxDepth = intval($maxDepth);
294 5
295 5
        if (empty(self::$sitePagesCache[$rootPageId])) {
296 5
            $recursionRootPageId = intval($rootPageId);
297 5
            if ($rootPageId == 'SITE_ROOT') {
298
                $recursionRootPageId = $this->rootPage['uid'];
299
                $pageIds[] = $this->rootPage['uid'];
300 5
            }
301 4
302
            if ($maxDepth > 0) {
303 4
                $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
304 4
                    'uid',
305
                    'pages',
306 4
                    'pid = ' . $recursionRootPageId . ' ' . BackendUtility::deleteClause('pages')
307
                );
308
309
                while ($page = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
310 5
                    $pageIds[] = $page['uid'];
311
312
                    if ($maxDepth > 1) {
313 5
                        $pageIds = array_merge(
314
                            $pageIds,
315
                            $this->getPages($page['uid'], $maxDepth - 1)
316 5
                        );
317
                    }
318 5
                }
319
                $GLOBALS['TYPO3_DB']->sql_free_result($result);
320
            }
321 5
        } else {
322
            $pageIds = self::$sitePagesCache[$rootPageId];
323
        }
324
325
        if (empty(self::$sitePagesCache[$rootPageId])) {
326
            // exiting the recursion loop, may write to cache now
327
            self::$sitePagesCache[$rootPageId] = $pageIds;
328
        }
329
330
        return $pageIds;
331
    }
332
333 43
    /**
334
     * Generates the site's unique Site Hash.
335 43
     *
336
     * The Site Hash is build from the site's main domain, the system encryption
337
     * key, and the extension "tx_solr". These components are concatenated and
338
     * sha1-hashed.
339
     *
340
     * @return string Site Hash.
341
     */
342
    public function getSiteHash()
343
    {
344 44
        return Util::getSiteHashForDomain($this->getDomain());
345
    }
346 44
347 44
    /**
348
     * Gets the site's main domain. More specifically the first domain record in
349 44
     * the site tree.
350
     *
351
     * @return string The site's main domain.
352
     */
353
    public function getDomain()
354
    {
355
        $pageSelect = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
356
        $rootLine = $pageSelect->getRootLine($this->rootPage['uid']);
357
358
        return BackendUtility::firstDomainRecord($rootLine);
359
    }
360
361
    /**
362
     * Gets the site's root page.
363
     *
364
     * @return array The site's root page.
365
     */
366
    public function getRootPage()
367
    {
368
        return $this->rootPage;
369
    }
370
371
    /**
372
     * Gets the site's root page's title.
373
     *
374
     * @return string The site's root page's title
375
     */
376
    public function getTitle()
377 11
    {
378
        return $this->rootPage['title'];
379 11
    }
380 11
381 11
    /**
382
     * Gets the site's config.sys_language_mode setting
383
     *
384 11
     * @return string The site's config.sys_language_mode
385
     */
386
    public function getSysLanguageMode()
387
    {
388
        if (is_null($this->sysLanguageMode)) {
389
            Util::initializeTsfe($this->getRootPageId());
390
            $this->sysLanguageMode = $GLOBALS['TSFE']->sys_language_mode;
391
        }
392
393
        return $this->sysLanguageMode;
394
    }
395
}
396