Passed
Push — master ( b7dc69...b39217 )
by Timo
41:01 queued 19:34
created

ConnectionManager::getConfigurationsBySite()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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