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

ConnectionManager::getLanguageName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3.0052

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 11
cts 12
cp 0.9167
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 11
nc 3
nop 1
crap 3.0052
1
<?php
2
namespace ApacheSolrForTypo3\Solr;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2010-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\Site\SiteRepository;
28
use ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager;
29
use ApacheSolrForTypo3\Solr\System\Page\Rootline;
30
use TYPO3\CMS\Backend\Routing\UriBuilder;
31
use TYPO3\CMS\Backend\Toolbar\ClearCacheActionsHookInterface;
32
use TYPO3\CMS\Core\Imaging\Icon;
33
use TYPO3\CMS\Core\Imaging\IconFactory;
34
use TYPO3\CMS\Core\Registry;
35
use TYPO3\CMS\Core\SingletonInterface;
36
use TYPO3\CMS\Core\TypoScript\ExtendedTemplateService;
37
use TYPO3\CMS\Core\Utility\GeneralUtility;
38
use TYPO3\CMS\Core\Utility\VersionNumberUtility;
39
use TYPO3\CMS\Frontend\Page\PageRepository;
40
41
/**
42
 * A class to easily create a connection to a Solr server.
43
 *
44
 * Internally keeps track of already existing connections and makes sure that no
45
 * duplicate connections are created.
46
 *
47
 * @author Ingo Renner <[email protected]>
48
 */
49
class ConnectionManager implements SingletonInterface, ClearCacheActionsHookInterface
50
{
51
52
    /**
53
     * @var array
54
     */
55
    protected static $connections = [];
56
57
    /**
58
     * @var \ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager
59
     */
60
    protected $logger = null;
61
62
    /**
63
     * Gets a Solr connection.
64
     *
65
     * Instead of generating a new connection with each call, connections are
66
     * kept and checked whether the requested connection already exists. If a
67
     * connection already exists, it's reused.
68
     *
69
     * @param string $host Solr host (optional)
70
     * @param int $port Solr port (optional)
71
     * @param string $path Solr path (optional)
72
     * @param string $scheme Solr scheme, defaults to http, can be https (optional)
73
     * @param string $username Solr user name (optional)
74
     * @param string $password Solr password (optional)
75
     * @return SolrService A solr connection.
76
     */
77
78 76
    public function getConnection($host = '', $port = 8983, $path = '/solr/', $scheme = 'http', $username = '', $password = '')
79
    {
80 76
        if (empty($host)) {
81 1
            $this->logger = GeneralUtility::makeInstance(SolrLogManager::class, __CLASS__);
82 1
            $this->logger->log(
83 1
                SolrLogManager::WARNING,
84
                'ApacheSolrForTypo3\Solr\ConnectionManager::getConnection() called with empty host parameter. Using configuration from TSFE, might be inaccurate. Always provide a host or use the getConnectionBy* methods.'
85 1
            );
86
87 1
            $configuration = Util::getSolrConfiguration();
88 1
            $host = $configuration->getSolrHost();
89 1
            $port = $configuration->getSolrPort();
90 1
            $path = $configuration->getSolrPath();
91 1
            $scheme = $configuration->getSolrScheme();
92 1
            $username = $configuration->getSolrUsername();
93 1
            $password = $configuration->getSolrPassword();
94 47
        }
95
96 76
        $connectionHash = md5($scheme . '://' . $host . $port . $path . $username . $password);
97 76
        if (!isset(self::$connections[$connectionHash])) {
98 76
            $connection = $this->buildSolrService($host, $port, $path, $scheme);
99 75
            if (trim($username) !== '') {
100 1
                $connection->setAuthenticationCredentials($username, $password);
101 1
            }
102
103 75
            self::$connections[$connectionHash] = $connection;
104 75
        }
105
106 75
        return self::$connections[$connectionHash];
107
    }
108
109
    /**
110
     * Create a Solr Service instance from the passed connection configuration.
111
     *
112
     * @param string $host
113
     * @param int $port
114
     * @param string $path
115
     * @param string $scheme
116
     * @return SolrService|object
117
     */
118 71
    protected function buildSolrService($host, $port, $path, $scheme)
119
    {
120 71
        return GeneralUtility::makeInstance(SolrService::class, $host, $port, $path, $scheme);
121
    }
122
123
    /**
124
     * Creates a solr configuration from the configuration array and returns it.
125
     *
126
     * @param array $config The solr configuration array
127
     * @return SolrService
128
     */
129 69
    protected function getConnectionFromConfiguration(array $config)
130
    {
131 69
        return $this->getConnection(
132 69
            $config['solrHost'],
133 69
            $config['solrPort'],
134 69
            $config['solrPath'],
135 69
            $config['solrScheme'],
136 69
            $config['solrUsername'],
137 69
            $config['solrPassword']
138 69
        );
139
    }
140
141
    /**
142
     * Gets a Solr configuration for a page ID.
143
     *
144
     * @param int $pageId A page ID.
145
     * @param int $language The language ID to get the connection for as the path may differ. Optional, defaults to 0.
146
     * @param string $mount Comma list of MountPoint parameters
147
     * @return array A solr configuration.
148
     * @throws NoSolrConnectionFoundException
149
     */
150 59
    public function getConfigurationByPageId($pageId, $language = 0, $mount = '')
151
    {
152
        // find the root page
153 59
        $pageSelect = GeneralUtility::makeInstance(PageRepository::class);
154
155
        /** @var Rootline $rootLine */
156 59
        $rootLine = GeneralUtility::makeInstance(Rootline::class, $pageSelect->getRootLine($pageId, $mount));
157 59
        $siteRootPageId = $rootLine->getRootPageId();
158
159
        try {
160 59
            $solrConfiguration = $this->getConfigurationByRootPageId($siteRootPageId, $language);
161 59
        } catch (NoSolrConnectionFoundException $nscfe) {
162
            /* @var $noSolrConnectionException NoSolrConnectionFoundException */
163 2
            $noSolrConnectionException = GeneralUtility::makeInstance(
164 2
                NoSolrConnectionFoundException::class,
165 2
                $nscfe->getMessage() . ' Initial page used was [' . $pageId . ']',
166
                1275399922
167 2
            );
168 2
            $noSolrConnectionException->setPageId($pageId);
169
170 2
            throw $noSolrConnectionException;
171
        }
172
173 58
        return $solrConfiguration;
174
    }
175
176
    /**
177
     * Gets a Solr connection for a page ID.
178
     *
179
     * @param int $pageId A page ID.
180
     * @param int $language The language ID to get the connection for as the path may differ. Optional, defaults to 0.
181
     * @param string $mount Comma list of MountPoint parameters
182
     * @return SolrService A solr connection.
183
     * @throws NoSolrConnectionFoundException
184
     */
185 59
    public function getConnectionByPageId($pageId, $language = 0, $mount = '')
186
    {
187 59
        $solrServer = $this->getConfigurationByPageId($pageId, $language, $mount);
188 58
        $solrConnection = $this->getConnectionFromConfiguration($solrServer);
189 58
        return $solrConnection;
190
    }
191
192
    /**
193
     * Gets a Solr configuration for a root page ID.
194
     *
195
     * @param int $pageId A root page ID.
196
     * @param int $language The language ID to get the configuration for as the path may differ. Optional, defaults to 0.
197
     * @return array A solr configuration.
198
     * @throws NoSolrConnectionFoundException
199
     */
200 60
    public function getConfigurationByRootPageId($pageId, $language = 0)
201
    {
202 60
        $connectionKey = $pageId . '|' . $language;
203 60
        $solrServers = $this->getAllConfigurations();
204
205 60
        if (isset($solrServers[$connectionKey])) {
206 58
            $solrConfiguration = $solrServers[$connectionKey];
207 58
        } else {
208
            /* @var $noSolrConnectionException NoSolrConnectionFoundException */
209 3
            $noSolrConnectionException = GeneralUtility::makeInstance(
210 3
                NoSolrConnectionFoundException::class,
211
                'Could not find a Solr connection for root page ['
212 3
                . $pageId . '] and language [' . $language . '].',
213
                1275396474
214 3
            );
215 3
            $noSolrConnectionException->setRootPageId($pageId);
216 3
            $noSolrConnectionException->setLanguageId($language);
217
218 3
            throw $noSolrConnectionException;
219
        }
220
221 58
        return $solrConfiguration;
222
    }
223
224
    /**
225
     * Gets a Solr connection for a root page ID.
226
     *
227
     * @param int $pageId A root page ID.
228
     * @param int $language The language ID to get the connection for as the path may differ. Optional, defaults to 0.
229
     * @return SolrService A solr connection.
230
     * @throws NoSolrConnectionFoundException
231
     */
232 6
    public function getConnectionByRootPageId($pageId, $language = 0)
233
    {
234 6
        $config = $this->getConfigurationByRootPageId($pageId, $language);
235 6
        $solrConnection = $this->getConnectionFromConfiguration($config);
236
237 6
        return $solrConnection;
238
    }
239
240
    /**
241
     * Gets all connection configurations found.
242
     *
243
     * @return array An array of connection configurations.
244
     */
245 73
    public function getAllConfigurations()
246
    {
247
        /** @var $registry Registry */
248 73
        $registry = GeneralUtility::makeInstance(Registry::class);
249 73
        $solrConfigurations = $registry->get('tx_solr', 'servers', []);
250
251 73
        return $solrConfigurations;
252
    }
253
254
    /**
255
     * Stores the connections in the registry.
256
     *
257
     * @param array $solrConfigurations
258
     */
259 3
    protected function setAllConfigurations(array $solrConfigurations)
260
    {
261
        /** @var $registry Registry */
262 3
        $registry = GeneralUtility::makeInstance(Registry::class);
263 3
        $registry->set('tx_solr', 'servers', $solrConfigurations);
264 3
    }
265
266
    /**
267
     * Gets all connections found.
268
     *
269
     * @return SolrService[] An array of initialized ApacheSolrForTypo3\Solr\SolrService connections
270
     */
271 7
    public function getAllConnections()
272
    {
273 7
        $connections = [];
274
275 7
        $solrConfigurations = $this->getAllConfigurations();
276 7
        foreach ($solrConfigurations as $solrConfiguration) {
277 7
            $connections[] = $this->getConnectionFromConfiguration($solrConfiguration);
278 7
        }
279
280 7
        return $connections;
281
    }
282
283
    /**
284
     * Gets all connection configurations for a given site.
285
     *
286
     * @param Site $site A TYPO3 site
287
     * @return array An array of Solr connection configurations for a site
288
     */
289 22
    public function getConfigurationsBySite(Site $site)
290
    {
291 22
        $solrConfigurations = [];
292
293 22
        $allConfigurations = $this->getAllConfigurations();
294 22
        foreach ($allConfigurations as $configuration) {
295 22
            if ($configuration['rootPageUid'] == $site->getRootPageId()) {
296 22
                $solrConfigurations[] = $configuration;
297 22
            }
298 22
        }
299
300 22
        return $solrConfigurations;
301
    }
302
303
    /**
304
     * Gets all connections configured for a given site.
305
     *
306
     * @param Site $site A TYPO3 site
307
     * @return SolrService[] An array of Solr connection objects (ApacheSolrForTypo3\Solr\SolrService)
308
     */
309 16
    public function getConnectionsBySite(Site $site)
310
    {
311 16
        $connections = [];
312
313 16
        $solrServers = $this->getConfigurationsBySite($site);
314 16
        foreach ($solrServers as $solrServer) {
315 16
            $connections[] = $this->getConnectionFromConfiguration($solrServer);
316 16
        }
317
318 16
        return $connections;
319
    }
320
321
    // updates
322
323
    /**
324
     * Adds a menu entry to the clear cache menu to detect Solr connections.
325
     *
326
     * @param array $cacheActions Array of CacheMenuItems
327
     * @param array $optionValues Array of AccessConfigurations-identifiers (typically  used by userTS with options.clearCache.identifier)
328
     */
329
    public function manipulateCacheActions(&$cacheActions, &$optionValues)
330
    {
331
        if ($GLOBALS['BE_USER']->isAdmin()) {
332
            $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
333
            $optionValues[] = 'clearSolrConnectionCache';
334
335
            // @Todo This should be removed when we don't support 7.6 LTS anymore
336
            if (VersionNumberUtility::convertVersionNumberToInteger(TYPO3_branch) >= VersionNumberUtility::convertVersionNumberToInteger('8.0')) {
337
                $cacheActions[] = [
338
                    'id' => 'clearSolrConnectionCache',
339
                    'title' => 'LLL:EXT:solr/Resources/Private/Language/locallang.xlf:cache_initialize_solr_connections',
340
                    'href' => $uriBuilder->buildUriFromRoute('ajax_solr_updateConnections'),
341
                    'iconIdentifier' => 'extensions-solr-module-initsolrconnections'
342
                ];
343
            } else {
344
                $title = 'Initialize Solr connections';
345
                $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
346
347
                $cacheActions[] = [
348
                    'id' => 'clearSolrConnectionCache',
349
                    'title' => $title,
350
                    'href' => $uriBuilder->buildUriFromRoute('ajax_solr_updateConnections'),
351
                    'icon' => $iconFactory->getIcon('extensions-solr-module-initsolrconnections', Icon::SIZE_SMALL)
352
                ];
353
            }
354
        }
355
    }
356
357
    /**
358
     * Updates the connections in the registry.
359
     *
360
     */
361 2
    public function updateConnections()
362
    {
363 2
        $solrConnections = $this->getConfiguredSolrConnections();
364 2
        $solrConnections = $this->filterDuplicateConnections($solrConnections);
365
366 2
        if (!empty($solrConnections)) {
367 2
            $this->setAllConfigurations($solrConnections);
368 2
        }
369 2
    }
370
371
    /**
372
     * Entrypoint for the ajax request
373
     */
374
    public function updateConnectionsInCacheMenu()
375
    {
376
        $this->updateConnections();
377
    }
378
379
    /**
380
     * Updates the Solr connections for a specific root page ID / site.
381
     *
382
     * @param int $rootPageId A site root page id
383
     */
384 1
    public function updateConnectionByRootPageId($rootPageId)
385
    {
386 1
        $systemLanguages = $this->getSystemLanguages();
387 1
        $siteRepository = GeneralUtility::makeInstance(SiteRepository::class);
388 1
        $site = $siteRepository->getSiteByRootPageId($rootPageId);
389 1
        $rootPage = $site->getRootPage();
390
391 1
        $updatedSolrConnections = [];
392 1
        foreach ($systemLanguages as $languageId) {
393 1
            $connection = $this->getConfiguredSolrConnectionByRootPage($rootPage, $languageId);
394
395 1
            if (!empty($connection)) {
396 1
                $updatedSolrConnections[$connection['connectionKey']] = $connection;
397 1
            }
398 1
        }
399
400 1
        $solrConnections = $this->getAllConfigurations();
401 1
        $solrConnections = array_merge($solrConnections, $updatedSolrConnections);
402 1
        $solrConnections = $this->filterDuplicateConnections($solrConnections);
403 1
        $this->setAllConfigurations($solrConnections);
404 1
    }
405
406
    /**
407
     * Finds the configured Solr connections. Also respects multi-site
408
     * environments.
409
     *
410
     * @return array An array with connections, each connection with keys rootPageTitle, rootPageUid, solrHost, solrPort, solrPath
411
     */
412 2
    protected function getConfiguredSolrConnections()
413
    {
414 2
        $configuredSolrConnections = [];
415
416
        // find website roots and languages for this installation
417 2
        $rootPages = $this->getRootPages();
418 2
        $languages = $this->getSystemLanguages();
419
420
        // find solr configurations and add them as function menu entries
421 2
        foreach ($rootPages as $rootPage) {
422 2
            foreach ($languages as $languageId) {
423 2
                $connection = $this->getConfiguredSolrConnectionByRootPage($rootPage,
424 2
                    $languageId);
425
426 2
                if (!empty($connection)) {
427 2
                    $configuredSolrConnections[$connection['connectionKey']] = $connection;
428 2
                }
429 2
            }
430 2
        }
431
432 2
        return $configuredSolrConnections;
433
    }
434
435
    /**
436
     * Gets the configured Solr connection for a specific root page and language ID.
437
     *
438
     * @param array $rootPage A root page record with at least title and uid
439
     * @param int $languageId ID of a system language
440
     * @return array A solr connection configuration.
441
     */
442 3
    protected function getConfiguredSolrConnectionByRootPage(array $rootPage, $languageId)
443
    {
444 3
        $connection = [];
445
446 3
        $languageId = intval($languageId);
447 3
        GeneralUtility::_GETset($languageId, 'L');
448 3
        $connectionKey = $rootPage['uid'] . '|' . $languageId;
449
450 3
        $pageSelect = GeneralUtility::makeInstance(PageRepository::class);
451 3
        $rootLine = $pageSelect->getRootLine($rootPage['uid']);
452
453 3
        $tmpl = GeneralUtility::makeInstance(ExtendedTemplateService::class);
454 3
        $tmpl->tt_track = false; // Do not log time-performance information
455 3
        $tmpl->init();
456 3
        $tmpl->runThroughTemplates($rootLine); // This generates the constants/config + hierarchy info for the template.
457
458
        // fake micro TSFE to get correct condition parsing
459 3
        $GLOBALS['TSFE'] = new \stdClass();
460 3
        $GLOBALS['TSFE']->tmpl = new \stdClass();
461 3
        $GLOBALS['TSFE']->cObjectDepthCounter = 50;
462 3
        $GLOBALS['TSFE']->tmpl->rootLine = $rootLine;
463 3
        $GLOBALS['TSFE']->sys_page = $pageSelect;
464 3
        $GLOBALS['TSFE']->id = $rootPage['uid'];
465 3
        $GLOBALS['TSFE']->page = $rootPage;
466
467 3
        $tmpl->generateConfig();
468 3
        $GLOBALS['TSFE']->tmpl->setup = $tmpl->setup;
469
470 3
        $configuration = Util::getSolrConfigurationFromPageId($rootPage['uid'], false, $languageId);
471
472 3
        $solrIsEnabledAndConfigured = $configuration->getEnabled() && $configuration->getSolrHasConnectionConfiguration();
473 3
        if (!$solrIsEnabledAndConfigured) {
474
            return $connection;
475
        }
476
477
        $connection = [
478 3
            'connectionKey' => $connectionKey,
479 3
            'rootPageTitle' => $rootPage['title'],
480 3
            'rootPageUid' => $rootPage['uid'],
481 3
            'solrScheme' => $configuration->getSolrScheme(),
482 3
            'solrHost' => $configuration->getSolrHost(),
483 3
            'solrPort' => $configuration->getSolrPort(),
484 3
            'solrPath' => $configuration->getSolrPath(),
485 3
            'solrUsername' => $configuration->getSolrUsername(),
486 3
            'solrPassword' => $configuration->getSolrPassword(),
487
488
            'language' => $languageId
489 3
        ];
490
491 3
        $connection['label'] = $this->buildConnectionLabel($connection);
492 3
        return $connection;
493
    }
494
495
    /**
496
     * Gets the language name for a given language ID.
497
     *
498
     * @param int $languageId language ID
499
     * @return string Language name
500
     */
501 3
    protected function getLanguageName($languageId)
502
    {
503 3
        $languageName = '';
504
505 3
        $language = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
506 3
            'uid, title',
507 3
            'sys_language',
508
            'uid = ' . (integer)$languageId
509 3
        );
510
511 3
        if (count($language)) {
512
            $languageName = $language[0]['title'];
513 3
        } elseif ($languageId == 0) {
514 3
            $languageName = 'default';
515 3
        }
516
517 3
        return $languageName;
518
    }
519
520
    /**
521
     * Creates a human readable label from the connections' configuration.
522
     *
523
     * @param array $connection Connection configuration
524
     * @return string Connection label
525
     */
526 3
    protected function buildConnectionLabel(array $connection)
527
    {
528 3
        $connectionLabel = $connection['rootPageTitle']
529 3
            . ' (pid: ' . $connection['rootPageUid']
530 3
            . ', language: ' . $this->getLanguageName($connection['language'])
531 3
            . ') - '
532
#			. $connection['solrScheme'] . '://'
533 3
            . $connection['solrHost'] . ':'
534 3
            . $connection['solrPort']
535 3
            . $connection['solrPath'];
536
537 3
        return $connectionLabel;
538
    }
539
540
    /**
541
     * Filters duplicate connections. When detecting the configured connections
542
     * this is done with a little brute force by simply combining all root pages
543
     * with all languages, this method filters out the duplicates.
544
     *
545
     * @param array $connections An array of unfiltered connections, containing duplicates
546
     * @return array An array with connections, no duplicates.
547
     */
548 3
    protected function filterDuplicateConnections(array $connections)
549
    {
550 3
        $hashedConnections = [];
551 3
        $filteredConnections = [];
552
553
        // array_unique() doesn't work on multi dimensional arrays, so we need to flatten it first
554 3
        foreach ($connections as $key => $connection) {
555 3
            unset($connection['language']);
556 3
            $connectionHash = md5(implode('|', $connection));
557 3
            $hashedConnections[$key] = $connectionHash;
558 3
        }
559
560 3
        $hashedConnections = array_unique($hashedConnections);
561
562 3
        foreach ($hashedConnections as $key => $hash) {
563 3
            $filteredConnections[$key] = $connections[$key];
564 3
        }
565
566 3
        return $filteredConnections;
567
    }
568
569
    /**
570
     * Finds the system's configured languages.
571
     *
572
     * @return array An array of language IDs
573
     */
574 3
    protected function getSystemLanguages()
575
    {
576 3
        $languages = [0];
577
578 3
        $languageRecords = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
579 3
            'uid',
580 3
            'sys_language',
581
            'hidden = 0'
582 3
        );
583
584 3
        if (!is_array($languageRecords)) {
585
            return $languages;
586
        }
587
588 3
        foreach ($languageRecords as $languageRecord) {
589
            $languages[] = $languageRecord['uid'];
590 3
        }
591 3
        return $languages;
592
    }
593
594
    /**
595
     * Gets the site's root pages. The "Is root of website" flag must be set,
596
     * which usually is the case for pages with pid = 0.
597
     *
598
     * @return array An array of (partial) root page records, containing the uid and title fields
599
     */
600 2
    protected function getRootPages()
601
    {
602 2
        $rootPages = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
603 2
            'uid, title',
604 2
            'pages',
605
            'is_siteroot = 1 AND deleted = 0 AND hidden = 0 AND pid != -1'
606 2
        );
607
608 2
        return $rootPages;
609
    }
610
}
611