Passed
Push — master ( 90f5c3...f8e2ef )
by Timo
23:55 queued 19:58
created

ConnectionManager::buildSolrService()   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

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 4
crap 1
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 101
    public function __construct(SystemLanguageRepository $systemLanguageRepository = null, PagesRepositoryAtExtSolr $pagesRepositoryAtExtSolr = null)
76
    {
77 101
        $this->systemLanguageRepository = isset($systemLanguageRepository) ? $systemLanguageRepository : GeneralUtility::makeInstance(SystemLanguageRepository::class);
78 101
        $this->pagesRepositoryAtExtSolr = isset($pagesRepositoryAtExtSolr) ? $pagesRepositoryAtExtSolr : GeneralUtility::makeInstance(PagesRepositoryAtExtSolr::class);
79 101
    }
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 94
    public function getConnection($host = '', $port = 8983, $path = '/solr/', $scheme = 'http', $username = '', $password = '')
97
    {
98 94
        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 94
        $connectionHash = md5($scheme . '://' . $host . $port . $path . $username . $password);
115 94
        if (!isset(self::$connections[$connectionHash])) {
116 94
            $connection = $this->buildSolrService($host, $port, $path, $scheme);
117 93
            if (trim($username) !== '') {
118 1
                $connection->setAuthenticationCredentials($username, $password);
119
            }
120
121 93
            self::$connections[$connectionHash] = $connection;
122
        }
123
124 93
        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 89
    protected function buildSolrService($host, $port, $path, $scheme)
137
    {
138 89
        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 87
    protected function getConnectionFromConfiguration(array $config)
148
    {
149 87
        return $this->getConnection(
150 87
            $config['solrHost'],
151 87
            $config['solrPort'],
152 87
            $config['solrPath'],
153 87
            $config['solrScheme'],
154 87
            $config['solrUsername'],
155 87
            $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 77
    public function getConfigurationByPageId($pageId, $language = 0, $mount = '')
169
    {
170
        // find the root page
171 77
        $pageSelect = GeneralUtility::makeInstance(PageRepository::class);
172
173
        /** @var Rootline $rootLine */
174 77
        $rootLine = GeneralUtility::makeInstance(Rootline::class, $pageSelect->getRootLine($pageId, $mount));
175 77
        $siteRootPageId = $rootLine->getRootPageId();
176
177
        try {
178 77
            $solrConfiguration = $this->getConfigurationByRootPageId($siteRootPageId, $language);
179 4
        } catch (NoSolrConnectionFoundException $nscfe) {
180
            /* @var $noSolrConnectionException NoSolrConnectionFoundException */
181 4
            $noSolrConnectionException = GeneralUtility::makeInstance(
182 4
                NoSolrConnectionFoundException::class,
183 4
                $nscfe->getMessage() . ' Initial page used was [' . $pageId . ']',
184 4
                1275399922
185
            );
186 4
            $noSolrConnectionException->setPageId($pageId);
187
188 4
            throw $noSolrConnectionException;
189
        }
190
191 74
        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 77
    public function getConnectionByPageId($pageId, $language = 0, $mount = '')
204
    {
205 77
        $solrServer = $this->getConfigurationByPageId($pageId, $language, $mount);
206 74
        $solrConnection = $this->getConnectionFromConfiguration($solrServer);
207 74
        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 78
    public function getConfigurationByRootPageId($pageId, $language = 0)
219
    {
220 78
        $connectionKey = $pageId . '|' . $language;
221 78
        $solrServers = $this->getAllConfigurations();
222
223 78
        if (isset($solrServers[$connectionKey])) {
224 76
            $solrConfiguration = $solrServers[$connectionKey];
225
        } else {
226
            /* @var $noSolrConnectionException NoSolrConnectionFoundException */
227 5
            $noSolrConnectionException = GeneralUtility::makeInstance(
228 5
                NoSolrConnectionFoundException::class,
229
                'Could not find a Solr connection for root page ['
230 5
                . $pageId . '] and language [' . $language . '].',
231 5
                1275396474
232
            );
233 5
            $noSolrConnectionException->setRootPageId($pageId);
234 5
            $noSolrConnectionException->setLanguageId($language);
235
236 5
            throw $noSolrConnectionException;
237
        }
238
239 76
        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 9
    public function getConnectionByRootPageId($pageId, $language = 0)
251
    {
252 9
        $config = $this->getConfigurationByRootPageId($pageId, $language);
253 9
        $solrConnection = $this->getConnectionFromConfiguration($config);
254
255 9
        return $solrConnection;
256
    }
257
258
    /**
259
     * Gets all connection configurations found.
260
     *
261
     * @return array An array of connection configurations.
262
     */
263 91
    public function getAllConfigurations()
264
    {
265
        /** @var $registry Registry */
266 91
        $registry = GeneralUtility::makeInstance(Registry::class);
267 91
        $solrConfigurations = $registry->get('tx_solr', 'servers', []);
268
269 91
        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 28
    public function getConfigurationsBySite(Site $site)
308
    {
309 28
        $solrConfigurations = [];
310
311 28
        $allConfigurations = $this->getAllConfigurations();
312 28
        foreach ($allConfigurations as $configuration) {
313 28
            if ($configuration['rootPageUid'] == $site->getRootPageId()) {
314 28
                $solrConfigurations[] = $configuration;
315
            }
316
        }
317
318 28
        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
     * Updates the Solr connections for a specific root page ID / site.
377
     *
378
     * @param int $rootPageId A site root page id
379
     */
380 1
    public function updateConnectionByRootPageId($rootPageId)
381
    {
382 1
        $systemLanguages = $this->systemLanguageRepository->findSystemLanguages();
383 1
        $siteRepository = GeneralUtility::makeInstance(SiteRepository::class);
384 1
        $site = $siteRepository->getSiteByRootPageId($rootPageId);
385 1
        $rootPage = $site->getRootPage();
386
387 1
        $updatedSolrConnections = [];
388 1
        foreach ($systemLanguages as $languageId) {
389 1
            $connection = $this->getConfiguredSolrConnectionByRootPage($rootPage, $languageId);
390
391 1
            if (!empty($connection)) {
392 1
                $updatedSolrConnections[$connection['connectionKey']] = $connection;
393
            }
394
        }
395
396 1
        $solrConnections = $this->getAllConfigurations();
397 1
        $solrConnections = array_merge($solrConnections, $updatedSolrConnections);
398 1
        $solrConnections = $this->filterDuplicateConnections($solrConnections);
399 1
        $this->setAllConfigurations($solrConnections);
400 1
    }
401
402
    /**
403
     * Finds the configured Solr connections. Also respects multi-site
404
     * environments.
405
     *
406
     * @return array An array with connections, each connection with keys rootPageTitle, rootPageUid, solrHost, solrPort, solrPath
407
     */
408 2
    protected function getConfiguredSolrConnections()
409
    {
410 2
        $configuredSolrConnections = [];
411
412
        // find website roots and languages for this installation
413 2
        $rootPages = $this->pagesRepositoryAtExtSolr->findAllRootPages();
414 2
        $languages = $this->systemLanguageRepository->findSystemLanguages();
415
416
        // find solr configurations and add them as function menu entries
417 2
        foreach ($rootPages as $rootPage) {
418 2
            foreach ($languages as $languageId) {
419 2
                $connection = $this->getConfiguredSolrConnectionByRootPage($rootPage,
420
                    $languageId);
421
422 2
                if (!empty($connection)) {
423 2
                    $configuredSolrConnections[$connection['connectionKey']] = $connection;
424
                }
425
            }
426
        }
427
428 2
        return $configuredSolrConnections;
429
    }
430
431
    /**
432
     * Gets the configured Solr connection for a specific root page and language ID.
433
     *
434
     * @param array $rootPage A root page record with at least title and uid
435
     * @param int $languageId ID of a system language
436
     * @return array A solr connection configuration.
437
     */
438 3
    protected function getConfiguredSolrConnectionByRootPage(array $rootPage, $languageId)
439
    {
440 3
        $connection = [];
441
442 3
        $languageId = intval($languageId);
443 3
        GeneralUtility::_GETset($languageId, 'L');
444 3
        $connectionKey = $rootPage['uid'] . '|' . $languageId;
445
446 3
        $pageSelect = GeneralUtility::makeInstance(PageRepository::class);
447 3
        $rootLine = $pageSelect->getRootLine($rootPage['uid']);
448
449 3
        $tmpl = GeneralUtility::makeInstance(ExtendedTemplateService::class);
450 3
        $tmpl->tt_track = false; // Do not log time-performance information
451 3
        $tmpl->init();
452 3
        $tmpl->runThroughTemplates($rootLine); // This generates the constants/config + hierarchy info for the template.
453
454
        // fake micro TSFE to get correct condition parsing
455 3
        $GLOBALS['TSFE'] = new \stdClass();
456 3
        $GLOBALS['TSFE']->tmpl = new \stdClass();
457 3
        $GLOBALS['TSFE']->cObjectDepthCounter = 50;
458 3
        $GLOBALS['TSFE']->tmpl->rootLine = $rootLine;
459 3
        $GLOBALS['TSFE']->sys_page = $pageSelect;
460 3
        $GLOBALS['TSFE']->id = $rootPage['uid'];
461 3
        $GLOBALS['TSFE']->page = $rootPage;
462
463 3
        $tmpl->generateConfig();
464 3
        $GLOBALS['TSFE']->tmpl->setup = $tmpl->setup;
465
466 3
        $configuration = Util::getSolrConfigurationFromPageId($rootPage['uid'], false, $languageId);
467
468 3
        $solrIsEnabledAndConfigured = $configuration->getEnabled() && $configuration->getSolrHasConnectionConfiguration();
469 3
        if (!$solrIsEnabledAndConfigured) {
470
            return $connection;
471
        }
472
473
        $connection = [
474 3
            'connectionKey' => $connectionKey,
475 3
            'rootPageTitle' => $rootPage['title'],
476 3
            'rootPageUid' => $rootPage['uid'],
477 3
            'solrScheme' => $configuration->getSolrScheme(),
478 3
            'solrHost' => $configuration->getSolrHost(),
479 3
            'solrPort' => $configuration->getSolrPort(),
480 3
            'solrPath' => $configuration->getSolrPath(),
481 3
            'solrUsername' => $configuration->getSolrUsername(),
482 3
            'solrPassword' => $configuration->getSolrPassword(),
483
484 3
            'language' => $languageId
485
        ];
486
487 3
        $connection['label'] = $this->buildConnectionLabel($connection);
488 3
        return $connection;
489
    }
490
491
492
493
    /**
494
     * Creates a human readable label from the connections' configuration.
495
     *
496
     * @param array $connection Connection configuration
497
     * @return string Connection label
498
     */
499 3
    protected function buildConnectionLabel(array $connection)
500
    {
501 3
        $connectionLabel = $connection['rootPageTitle']
502 3
            . ' (pid: ' . $connection['rootPageUid']
503 3
            . ', language: ' . $this->systemLanguageRepository->findOneLanguageTitleByLanguageId($connection['language'])
504 3
            . ') - '
505
#			. $connection['solrScheme'] . '://'
506 3
            . $connection['solrHost'] . ':'
507 3
            . $connection['solrPort']
508 3
            . $connection['solrPath'];
509
510 3
        return $connectionLabel;
511
    }
512
513
    /**
514
     * Filters duplicate connections. When detecting the configured connections
515
     * this is done with a little brute force by simply combining all root pages
516
     * with all languages, this method filters out the duplicates.
517
     *
518
     * @param array $connections An array of unfiltered connections, containing duplicates
519
     * @return array An array with connections, no duplicates.
520
     */
521 3
    protected function filterDuplicateConnections(array $connections)
522
    {
523 3
        $hashedConnections = [];
524 3
        $filteredConnections = [];
525
526
        // array_unique() doesn't work on multi dimensional arrays, so we need to flatten it first
527 3
        foreach ($connections as $key => $connection) {
528 3
            unset($connection['language']);
529 3
            $connectionHash = md5(implode('|', $connection));
530 3
            $hashedConnections[$key] = $connectionHash;
531
        }
532
533 3
        $hashedConnections = array_unique($hashedConnections);
534
535 3
        foreach ($hashedConnections as $key => $hash) {
536 3
            $filteredConnections[$key] = $connections[$key];
537
        }
538
539 3
        return $filteredConnections;
540
    }
541
}
542