Completed
Push — master ( 5919d7...94bd1b )
by Rafael
05:28
created

ConnectionManager::buildSolrConnection()   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 6
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 ApacheSolrForTypo3\Solr\System\Solr\SolrConnection;
33
use TYPO3\CMS\Backend\Routing\UriBuilder;
34
use TYPO3\CMS\Backend\Toolbar\ClearCacheActionsHookInterface;
35
use TYPO3\CMS\Core\Registry;
36
use TYPO3\CMS\Core\SingletonInterface;
37
use TYPO3\CMS\Core\TypoScript\ExtendedTemplateService;
38
use TYPO3\CMS\Core\Utility\GeneralUtility;
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\Records\SystemLanguage\SystemLanguageRepository
59
     */
60
    protected $systemLanguageRepository;
61
62
    /**
63
     * @var \ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager
64
     */
65
    protected $logger = null;
66
67
    /**
68
     * @var PagesRepositoryAtExtSolr
69
     */
70
    protected $pagesRepositoryAtExtSolr;
71
72
    /**
73
     * @param SystemLanguageRepository $systemLanguageRepository
74
     * @param PagesRepositoryAtExtSolr|null $pagesRepositoryAtExtSolr
75
     * @param SolrLogManager $solrLogManager
76 108
     */
77
    public function __construct(SystemLanguageRepository $systemLanguageRepository = null, PagesRepositoryAtExtSolr $pagesRepositoryAtExtSolr = null, SolrLogManager $solrLogManager = null)
78 108
    {
79 108
        $this->systemLanguageRepository = isset($systemLanguageRepository) ? $systemLanguageRepository : GeneralUtility::makeInstance(SystemLanguageRepository::class);
80 108
        $this->pagesRepositoryAtExtSolr = isset($pagesRepositoryAtExtSolr) ? $pagesRepositoryAtExtSolr : GeneralUtility::makeInstance(PagesRepositoryAtExtSolr::class);
81 108
        $this->logger                   = isset($solrLogManager) ? $solrLogManager : GeneralUtility::makeInstance(SolrLogManager::class, __CLASS__);
82
    }
83
84
    /**
85
     * Gets a Solr connection.
86
     *
87
     * Instead of generating a new connection with each call, connections are
88
     * kept and checked whether the requested connection already exists. If a
89
     * connection already exists, it's reused.
90
     *
91
     * @param string $host Solr host (optional)
92
     * @param int $port Solr port (optional)
93
     * @param string $path Solr path (optional)
94
     * @param string $scheme Solr scheme, defaults to http, can be https (optional)
95
     * @param string $username Solr user name (optional)
96
     * @param string $password Solr password (optional)
97
     * @return SolrConnection A solr connection.
98 101
     */
99
    public function getConnection($host = '', $port = 8983, $path = '/solr/', $scheme = 'http', $username = '', $password = '')
100 101
    {
101 1
        if (empty($host)) {
102 1
            $this->logger->log(
103 1
                SolrLogManager::WARNING,
104
                '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.'
105
            );
106 1
107 1
            $configuration = Util::getSolrConfiguration();
108 1
            $host = $configuration->getSolrHost();
109 1
            $port = $configuration->getSolrPort();
110 1
            $path = $configuration->getSolrPath();
111 1
            $scheme = $configuration->getSolrScheme();
112 1
            $username = $configuration->getSolrUsername();
113
            $password = $configuration->getSolrPassword();
114
        }
115 101
116 101
        $connectionHash = md5($scheme . '://' . $host . $port . $path . $username . $password);
117 101
        if (!isset(self::$connections[$connectionHash])) {
118 100
            $connection = $this->buildSolrConnection($host, $port, $path, $scheme, $username, $password);
119 1
            self::$connections[$connectionHash] = $connection;
120
        }
121
122 100
        return self::$connections[$connectionHash];
123
    }
124
125 100
    /**
126
     * Create a Solr Service instance from the passed connection configuration.
127
     *
128
     * @param string $host
129
     * @param int $port
130
     * @param string $path
131
     * @param string $scheme
132
     * @param string $username
133
     * @param string $password
134
     * @return SolrConnection|object
135
     */
136
    protected function buildSolrConnection($host, $port, $path, $scheme, $username = '', $password = '')
137 96
    {
138
        return GeneralUtility::makeInstance(SolrConnection::class, $host, $port, $path, $scheme, $username, $password);
139 96
    }
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 SolrConnection
146
     */
147
    protected function getConnectionFromConfiguration(array $config)
148 94
    {
149
        return $this->getConnection(
150 94
            $config['solrHost'],
151 94
            $config['solrPort'],
152 94
            $config['solrPath'],
153 94
            $config['solrScheme'],
154 94
            $config['solrUsername'],
155 94
            $config['solrPassword']
156 94
        );
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
    public function getConfigurationByPageId($pageId, $language = 0, $mount = '')
169 84
    {
170
        // find the root page
171
        $pageSelect = GeneralUtility::makeInstance(PageRepository::class);
172 84
173
        /** @var Rootline $rootLine */
174
        $rootLine = GeneralUtility::makeInstance(Rootline::class, $pageSelect->getRootLine($pageId, $mount));
175 84
        $siteRootPageId = $rootLine->getRootPageId();
176 84
177
        try {
178
            $solrConfiguration = $this->getConfigurationByRootPageId($siteRootPageId, $language);
179 84
        } catch (NoSolrConnectionFoundException $nscfe) {
180 4
            /* @var $noSolrConnectionException NoSolrConnectionFoundException */
181
            $noSolrConnectionException = GeneralUtility::makeInstance(
182 4
                NoSolrConnectionFoundException::class,
183 4
                $nscfe->getMessage() . ' Initial page used was [' . $pageId . ']',
184 4
                1275399922
185 4
            );
186
            $noSolrConnectionException->setPageId($pageId);
187 4
188
            throw $noSolrConnectionException;
189 4
        }
190
191
        return $solrConfiguration;
192 81
    }
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 SolrConnection A solr connection.
201
     * @throws NoSolrConnectionFoundException
202
     */
203
    public function getConnectionByPageId($pageId, $language = 0, $mount = '')
204 84
    {
205
        $solrServer = $this->getConfigurationByPageId($pageId, $language, $mount);
206 84
        $solrConnection = $this->getConnectionFromConfiguration($solrServer);
207 81
        return $solrConnection;
208 81
    }
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
    public function getConfigurationByRootPageId($pageId, $language = 0)
219 85
    {
220
        $connectionKey = $pageId . '|' . $language;
221 85
        $solrServers = $this->getAllConfigurations();
222 85
223
        if (isset($solrServers[$connectionKey])) {
224 85
            $solrConfiguration = $solrServers[$connectionKey];
225 83
        } else {
226
            /* @var $noSolrConnectionException NoSolrConnectionFoundException */
227
            $noSolrConnectionException = GeneralUtility::makeInstance(
228 5
                NoSolrConnectionFoundException::class,
229 5
                'Could not find a Solr connection for root page ['
230
                . $pageId . '] and language [' . $language . '].',
231 5
                1275396474
232 5
            );
233
            $noSolrConnectionException->setRootPageId($pageId);
234 5
            $noSolrConnectionException->setLanguageId($language);
235 5
236
            throw $noSolrConnectionException;
237 5
        }
238
239
        return $solrConfiguration;
240 83
    }
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 SolrConnection A solr connection.
248
     * @throws NoSolrConnectionFoundException
249
     */
250
    public function getConnectionByRootPageId($pageId, $language = 0)
251 10
    {
252
        $config = $this->getConfigurationByRootPageId($pageId, $language);
253 10
        $solrConnection = $this->getConnectionFromConfiguration($config);
254 10
255
        return $solrConnection;
256 10
    }
257
258
    /**
259
     * Gets all connection configurations found.
260
     *
261
     * @return array An array of connection configurations.
262
     */
263
    public function getAllConfigurations()
264 98
    {
265
        /** @var $registry Registry */
266
        $registry = GeneralUtility::makeInstance(Registry::class);
267 98
        $solrConfigurations = $registry->get('tx_solr', 'servers', []);
268 98
269
        return $solrConfigurations;
270 98
    }
271
272
    /**
273
     * Stores the connections in the registry.
274
     *
275
     * @param array $solrConfigurations
276
     */
277
    protected function setAllConfigurations(array $solrConfigurations)
278 3
    {
279
        /** @var $registry Registry */
280
        $registry = GeneralUtility::makeInstance(Registry::class);
281 3
        $registry->set('tx_solr', 'servers', $solrConfigurations);
282 3
    }
283 3
284
    /**
285
     * Gets all connections found.
286
     *
287
     * @return SolrConnection[] An array of initialized ApacheSolrForTypo3\Solr\System\Solr\SolrConnection connections
288
     */
289
    public function getAllConnections()
290 7
    {
291
        $solrConnections = [];
292 7
293
        $solrConfigurations = $this->getAllConfigurations();
294 7
        foreach ($solrConfigurations as $solrConfiguration) {
295 7
            $solrConnections[] = $this->getConnectionFromConfiguration($solrConfiguration);
296 7
        }
297
298
        return $solrConnections;
299 7
    }
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
    public function getConfigurationsBySite(Site $site)
308 31
    {
309
        $solrConfigurations = [];
310 31
311
        $allConfigurations = $this->getAllConfigurations();
312 31
        foreach ($allConfigurations as $configuration) {
313 31
            if ($configuration['rootPageUid'] == $site->getRootPageId()) {
314 31
                $solrConfigurations[] = $configuration;
315 31
            }
316
        }
317
318
        return $solrConfigurations;
319 31
    }
320
321
    /**
322
     * Gets all connections configured for a given site.
323
     *
324
     * @param Site $site A TYPO3 site
325
     * @return SolrConnection[] An array of Solr connection objects (ApacheSolrForTypo3\Solr\System\Solr\SolrConnection)
326
     */
327
    public function getConnectionsBySite(Site $site)
328 16
    {
329
        $connections = [];
330 16
331
        $solrServers = $this->getConfigurationsBySite($site);
332 16
        foreach ($solrServers as $solrServer) {
333 16
            $connections[] = $this->getConnectionFromConfiguration($solrServer);
334 16
        }
335
336
        return $connections;
337 16
    }
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
    public function updateConnections()
366 2
    {
367
        $solrConnections = $this->getConfiguredSolrConnections();
368 2
        $solrConnections = $this->filterDuplicateConnections($solrConnections);
369 2
370
        if (!empty($solrConnections)) {
371 2
            $this->setAllConfigurations($solrConnections);
372 2
        }
373
    }
374 2
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
    public function updateConnectionByRootPageId($rootPageId)
381 1
    {
382
        $systemLanguages = $this->systemLanguageRepository->findSystemLanguages();
383 1
        $siteRepository = GeneralUtility::makeInstance(SiteRepository::class);
384 1
        $site = $siteRepository->getSiteByRootPageId($rootPageId);
385 1
        $rootPage = $site->getRootPage();
386 1
387
        $updatedSolrConnections = [];
388 1
        foreach ($systemLanguages as $languageId) {
389 1
            $connection = $this->getConfiguredSolrConnectionByRootPage($rootPage, $languageId);
390 1
391
            if (!empty($connection)) {
392 1
                $updatedSolrConnections[$connection['connectionKey']] = $connection;
393 1
            }
394
        }
395
396
        $solrConnections = $this->getAllConfigurations();
397 1
        $solrConnections = array_merge($solrConnections, $updatedSolrConnections);
398 1
        $solrConnections = $this->filterDuplicateConnections($solrConnections);
399 1
        $this->setAllConfigurations($solrConnections);
400 1
    }
401 1
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
    protected function getConfiguredSolrConnections()
409 2
    {
410
        $configuredSolrConnections = [];
411 2
        // find website roots and languages for this installation
412
        $rootPages = $this->pagesRepositoryAtExtSolr->findAllRootPages();
413
        $languages = $this->systemLanguageRepository->findSystemLanguages();
414 2
415 2
        // find solr configurations and add them as function menu entries
416
        foreach ($rootPages as $rootPage) {
417
            foreach ($languages as $languageId) {
418 2
                $connection = $this->getConfiguredSolrConnectionByRootPage($rootPage,
419 2
                    $languageId);
420 2
421 2
                if (!empty($connection)) {
422
                    $configuredSolrConnections[$connection['connectionKey']] = $connection;
423 2
                }
424 2
            }
425
        }
426
427
        return $configuredSolrConnections;
428
    }
429 2
430
    /**
431
     * Gets the configured Solr connection for a specific root page and language ID.
432
     *
433
     * @param array $rootPage A root page record with at least title and uid
434
     * @param int $languageId ID of a system language
435
     * @return array A solr connection configuration.
436
     */
437
    protected function getConfiguredSolrConnectionByRootPage(array $rootPage, $languageId)
438
    {
439 3
        $connection = [];
440
441 3
        $languageId = (int)$languageId;
442
        GeneralUtility::_GETset($languageId, 'L');
443 3
        $connectionKey = $rootPage['uid'] . '|' . $languageId;
444 3
445 3
        $pageSelect = GeneralUtility::makeInstance(PageRepository::class);
446
        $rootLine = $pageSelect->getRootLine($rootPage['uid']);
447 3
448 3
        $tmpl = GeneralUtility::makeInstance(ExtendedTemplateService::class);
449
        $tmpl->tt_track = false; // Do not log time-performance information
450 3
        $tmpl->init();
451 3
        $tmpl->runThroughTemplates($rootLine); // This generates the constants/config + hierarchy info for the template.
452 3
453 3
        // fake micro TSFE to get correct condition parsing
454
        $GLOBALS['TSFE'] = new \stdClass();
455
        $GLOBALS['TSFE']->tmpl = new \stdClass();
456 3
        $GLOBALS['TSFE']->cObjectDepthCounter = 50;
457 3
        $GLOBALS['TSFE']->tmpl->rootLine = $rootLine;
458 3
        $GLOBALS['TSFE']->sys_page = $pageSelect;
459 3
        $GLOBALS['TSFE']->id = $rootPage['uid'];
460 3
        $GLOBALS['TSFE']->page = $rootPage;
461 3
462 3
        $tmpl->generateConfig();
463
        $GLOBALS['TSFE']->tmpl->setup = $tmpl->setup;
464 3
465 3
        $configuration = Util::getSolrConfigurationFromPageId($rootPage['uid'], false, $languageId);
466
467 3
        $solrIsEnabledAndConfigured = $configuration->getEnabled() && $configuration->getSolrHasConnectionConfiguration();
468
        if (!$solrIsEnabledAndConfigured) {
469 3
            return $connection;
470 3
        }
471
472
        $connection = [
473
            'connectionKey' => $connectionKey,
474
            'rootPageTitle' => $rootPage['title'],
475 3
            'rootPageUid' => $rootPage['uid'],
476 3
            'solrScheme' => $configuration->getSolrScheme(),
477 3
            'solrHost' => $configuration->getSolrHost(),
478 3
            'solrPort' => $configuration->getSolrPort(),
479 3
            'solrPath' => $configuration->getSolrPath(),
480 3
            'solrUsername' => $configuration->getSolrUsername(),
481 3
            'solrPassword' => $configuration->getSolrPassword(),
482 3
483 3
            'language' => $languageId
484
        ];
485 3
486
        $connection['label'] = $this->buildConnectionLabel($connection);
487
        return $connection;
488 3
    }
489 3
490
491
492
    /**
493
     * Creates a human readable label from the connections' configuration.
494
     *
495
     * @param array $connection Connection configuration
496
     * @return string Connection label
497
     */
498
    protected function buildConnectionLabel(array $connection)
499
    {
500 3
        return $connection['rootPageTitle']
501
            . ' (pid: ' . $connection['rootPageUid']
502 3
            . ', language: ' . $this->systemLanguageRepository->findOneLanguageTitleByLanguageId($connection['language'])
503 3
            . ') - '
504 3
//            . $connection['solrScheme'] . '://'
505 3
            . $connection['solrHost'] . ':'
506
            . $connection['solrPort']
507 3
            . $connection['solrPath'];
508 3
    }
509 3
510
    /**
511 3
     * Filters duplicate connections. When detecting the configured connections
512
     * this is done with a little brute force by simply combining all root pages
513
     * with all languages, this method filters out the duplicates.
514
     *
515
     * @param array $connections An array of unfiltered connections, containing duplicates
516
     * @return array An array with connections, no duplicates.
517
     */
518
    protected function filterDuplicateConnections(array $connections)
519
    {
520
        $hashedConnections = [];
521
        $filteredConnections = [];
522 3
523
        // array_unique() doesn't work on multi dimensional arrays, so we need to flatten it first
524 3
        foreach ($connections as $key => $connection) {
525 3
            unset($connection['language']);
526
            $connectionHash = md5(implode('|', $connection));
527
            $hashedConnections[$key] = $connectionHash;
528 3
        }
529 3
530 3
        $hashedConnections = array_unique($hashedConnections);
531 3
532
        foreach ($hashedConnections as $key => $hash) {
533
            $filteredConnections[$key] = $connections[$key];
534 3
        }
535
536 3
        return $filteredConnections;
537 3
    }
538
}
539