Passed
Pull Request — master (#1216)
by
unknown
35:55
created

ConnectionManager::manipulateCacheActions()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 5.9245

Importance

Changes 0
Metric Value
dl 0
loc 27
ccs 5
cts 16
cp 0.3125
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 18
nc 3
nop 2
crap 5.9245
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 75
78
    public function getConnection($host = '', $port = 8983, $path = '/solr/', $scheme = 'http', $username = '', $password = '')
79 75
    {
80 1
        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
            );
86 1
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
            $password = $configuration->getSolrPassword();
94
        }
95 75
96 75
        $connectionHash = md5($scheme . '://' . $host . $port . $path . $username . $password);
97 75
        if (!isset(self::$connections[$connectionHash])) {
98 74
            $connection = $this->buildSolrService($host, $port, $path, $scheme);
99 1
            if (trim($username) !== '') {
100
                $connection->setAuthenticationCredentials($username, $password);
101
            }
102 74
103
            self::$connections[$connectionHash] = $connection;
104
        }
105 74
106
        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 70
     */
118
    protected function buildSolrService($host, $port, $path, $scheme)
119 70
    {
120
        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 68
     */
129
    protected function getConnectionFromConfiguration(array $config)
130 68
    {
131 68
        return $this->getConnection(
132 68
            $config['solrHost'],
133 68
            $config['solrPort'],
134 68
            $config['solrPath'],
135 68
            $config['solrScheme'],
136 68
            $config['solrUsername'],
137
            $config['solrPassword']
138
        );
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 58
     */
150
    public function getConfigurationByPageId($pageId, $language = 0, $mount = '')
151
    {
152 58
        // find the root page
153
        $pageSelect = GeneralUtility::makeInstance(PageRepository::class);
154
155 58
        /** @var Rootline $rootLine */
156 58
        $rootLine = GeneralUtility::makeInstance(Rootline::class, $pageSelect->getRootLine($pageId, $mount));
157
        $siteRootPageId = $rootLine->getRootPageId();
158
159 58
        try {
160 2
            $solrConfiguration = $this->getConfigurationByRootPageId($siteRootPageId, $language);
161
        } catch (NoSolrConnectionFoundException $nscfe) {
162 2
            /* @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
            $noSolrConnectionException->setPageId($pageId);
169 2
170
            throw $noSolrConnectionException;
171
        }
172 57
173
        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 58
     */
185
    public function getConnectionByPageId($pageId, $language = 0, $mount = '')
186 58
    {
187 57
        $solrServer = $this->getConfigurationByPageId($pageId, $language, $mount);
188 57
        $solrConnection = $this->getConnectionFromConfiguration($solrServer);
189
        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 59
     */
200
    public function getConfigurationByRootPageId($pageId, $language = 0)
201 59
    {
202 59
        $connectionKey = $pageId . '|' . $language;
203
        $solrServers = $this->getAllConfigurations();
204 59
205 57
        if (isset($solrServers[$connectionKey])) {
206
            $solrConfiguration = $solrServers[$connectionKey];
207
        } else {
208 3
            /* @var $noSolrConnectionException NoSolrConnectionFoundException */
209 3
            $noSolrConnectionException = GeneralUtility::makeInstance(
210
                NoSolrConnectionFoundException::class,
211 3
                '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
            $noSolrConnectionException->setLanguageId($language);
217 3
218
            throw $noSolrConnectionException;
219
        }
220 57
221
        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 6
     */
232
    public function getConnectionByRootPageId($pageId, $language = 0)
233 6
    {
234 6
        $config = $this->getConfigurationByRootPageId($pageId, $language);
235
        $solrConnection = $this->getConnectionFromConfiguration($config);
236 6
237
        return $solrConnection;
238
    }
239
240
    /**
241
     * Gets all connection configurations found.
242
     *
243
     * @return array An array of connection configurations.
244 72
     */
245
    public function getAllConfigurations()
246
    {
247 72
        /** @var $registry Registry */
248 72
        $registry = GeneralUtility::makeInstance(Registry::class);
249
        $solrConfigurations = $registry->get('tx_solr', 'servers', []);
250 72
251
        return $solrConfigurations;
252
    }
253
254
    /**
255
     * Stores the connections in the registry.
256
     *
257
     * @param array $solrConfigurations
258 3
     */
259
    protected function setAllConfigurations(array $solrConfigurations)
260
    {
261 3
        /** @var $registry Registry */
262 3
        $registry = GeneralUtility::makeInstance(Registry::class);
263 3
        $registry->set('tx_solr', 'servers', $solrConfigurations);
264
    }
265
266
    /**
267
     * Gets all connections found.
268
     *
269
     * @return SolrService[] An array of initialized ApacheSolrForTypo3\Solr\SolrService connections
270 7
     */
271
    public function getAllConnections()
272 7
    {
273
        $connections = [];
274 7
275 7
        $solrConfigurations = $this->getAllConfigurations();
276 7
        foreach ($solrConfigurations as $solrConfiguration) {
277
            $connections[] = $this->getConnectionFromConfiguration($solrConfiguration);
278
        }
279 7
280
        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 22
     */
289
    public function getConfigurationsBySite(Site $site)
290 22
    {
291
        $solrConfigurations = [];
292 22
293 22
        $allConfigurations = $this->getAllConfigurations();
294 22
        foreach ($allConfigurations as $configuration) {
295 22
            if ($configuration['rootPageUid'] == $site->getRootPageId()) {
296
                $solrConfigurations[] = $configuration;
297
            }
298
        }
299 22
300
        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 16
     */
309
    public function getConnectionsBySite(Site $site)
310 16
    {
311
        $connections = [];
312 16
313 16
        $solrServers = $this->getConfigurationsBySite($site);
314 16
        foreach ($solrServers as $solrServer) {
315
            $connections[] = $this->getConnectionFromConfiguration($solrServer);
316
        }
317 16
318
        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 2
                    'title' => $title,
350
                    'href' => $uriBuilder->buildUriFromRoute('ajax_solr_updateConnections'),
351 2
                    'icon' => $iconFactory->getIcon('extensions-solr-module-initsolrconnections', Icon::SIZE_SMALL)
352 2
                ];
353
            }
354 2
        }
355 2
    }
356
357 2
    /**
358
     * Updates the connections in the registry.
359
     *
360
     */
361
    public function updateConnections()
362
    {
363
        $solrConnections = $this->getConfiguredSolrConnections();
364
        $solrConnections = $this->filterDuplicateConnections($solrConnections);
365
366
        if (!empty($solrConnections)) {
367
            $this->setAllConfigurations($solrConnections);
368
        }
369
    }
370
371
    /**
372 1
     * Entrypoint for the ajax request
373
     */
374 1
    public function updateConnectionsInCacheMenu()
375 1
    {
376 1
        $this->updateConnections();
377 1
    }
378
379 1
    /**
380 1
     * Updates the Solr connections for a specific root page ID / site.
381 1
     *
382
     * @param int $rootPageId A site root page id
383 1
     */
384 1
    public function updateConnectionByRootPageId($rootPageId)
385
    {
386
        $systemLanguages = $this->getSystemLanguages();
387
        $siteRepository = GeneralUtility::makeInstance(SiteRepository::class);
388 1
        $site = $siteRepository->getSiteByRootPageId($rootPageId);
389 1
        $rootPage = $site->getRootPage();
390 1
391 1
        $updatedSolrConnections = [];
392 1
        foreach ($systemLanguages as $languageId) {
393
            $connection = $this->getConfiguredSolrConnectionByRootPage($rootPage, $languageId);
394
395
            if (!empty($connection)) {
396
                $updatedSolrConnections[$connection['connectionKey']] = $connection;
397
            }
398
        }
399
400 2
        $solrConnections = $this->getAllConfigurations();
401
        $solrConnections = array_merge($solrConnections, $updatedSolrConnections);
402 2
        $solrConnections = $this->filterDuplicateConnections($solrConnections);
403
        $this->setAllConfigurations($solrConnections);
404
    }
405 2
406 2
    /**
407
     * Finds the configured Solr connections. Also respects multi-site
408
     * environments.
409 2
     *
410 2
     * @return array An array with connections, each connection with keys rootPageTitle, rootPageUid, solrHost, solrPort, solrPath
411 2
     */
412
    protected function getConfiguredSolrConnections()
413
    {
414 2
        $configuredSolrConnections = [];
415 2
416
        // find website roots and languages for this installation
417
        $rootPages = $this->getRootPages();
418
        $languages = $this->getSystemLanguages();
419
420 2
        // find solr configurations and add them as function menu entries
421
        foreach ($rootPages as $rootPage) {
422
            foreach ($languages as $languageId) {
423
                $connection = $this->getConfiguredSolrConnectionByRootPage($rootPage,
424
                    $languageId);
425
426
                if (!empty($connection)) {
427
                    $configuredSolrConnections[$connection['connectionKey']] = $connection;
428
                }
429
            }
430 3
        }
431
432 3
        return $configuredSolrConnections;
433
    }
434 3
435 3
    /**
436 3
     * Gets the configured Solr connection for a specific root page and language ID.
437
     *
438 3
     * @param array $rootPage A root page record with at least title and uid
439 3
     * @param int $languageId ID of a system language
440
     * @return array A solr connection configuration.
441 3
     */
442 3
    protected function getConfiguredSolrConnectionByRootPage(array $rootPage, $languageId)
443 3
    {
444 3
        $connection = [];
445
446
        $languageId = intval($languageId);
447 3
        GeneralUtility::_GETset($languageId, 'L');
448 3
        $connectionKey = $rootPage['uid'] . '|' . $languageId;
449 3
450 3
        $pageSelect = GeneralUtility::makeInstance(PageRepository::class);
451 3
        $rootLine = $pageSelect->getRootLine($rootPage['uid']);
452 3
453 3
        $tmpl = GeneralUtility::makeInstance(ExtendedTemplateService::class);
454
        $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 3
        // fake micro TSFE to get correct condition parsing
459
        $GLOBALS['TSFE'] = new \stdClass();
460 3
        $GLOBALS['TSFE']->tmpl = new \stdClass();
461 3
        $GLOBALS['TSFE']->cObjectDepthCounter = 50;
462
        $GLOBALS['TSFE']->tmpl->rootLine = $rootLine;
463
        $GLOBALS['TSFE']->sys_page = $pageSelect;
464
        $GLOBALS['TSFE']->id = $rootPage['uid'];
465
        $GLOBALS['TSFE']->page = $rootPage;
466 3
467 3
        $tmpl->generateConfig();
468 3
        $GLOBALS['TSFE']->tmpl->setup = $tmpl->setup;
469 3
470 3
        $configuration = Util::getSolrConfigurationFromPageId($rootPage['uid'], false, $languageId);
471 3
472 3
        $solrIsEnabledAndConfigured = $configuration->getEnabled() && $configuration->getSolrHasConnectionConfiguration();
473 3
        if (!$solrIsEnabledAndConfigured) {
474 3
            return $connection;
475
        }
476 3
477
        $connection = [
478
            'connectionKey' => $connectionKey,
479 3
            'rootPageTitle' => $rootPage['title'],
480 3
            'rootPageUid' => $rootPage['uid'],
481
            'solrScheme' => $configuration->getSolrScheme(),
482
            'solrHost' => $configuration->getSolrHost(),
483
            'solrPort' => $configuration->getSolrPort(),
484
            'solrPath' => $configuration->getSolrPath(),
485
            'solrUsername' => $configuration->getSolrUsername(),
486
            'solrPassword' => $configuration->getSolrPassword(),
487
488
            'language' => $languageId
489 3
        ];
490
491 3
        $connection['label'] = $this->buildConnectionLabel($connection);
492
        return $connection;
493 3
    }
494 3
495 3
    /**
496 3
     * Gets the language name for a given language ID.
497
     *
498
     * @param int $languageId language ID
499 3
     * @return string Language name
500
     */
501 3
    protected function getLanguageName($languageId)
502 3
    {
503
        $languageName = '';
504
505 3
        $language = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
506
            'uid, title',
507
            'sys_language',
508
            'uid = ' . (integer)$languageId
509
        );
510
511
        if (count($language)) {
512
            $languageName = $language[0]['title'];
513
        } elseif ($languageId == 0) {
514 3
            $languageName = 'default';
515
        }
516 3
517 3
        return $languageName;
518 3
    }
519 3
520
    /**
521 3
     * Creates a human readable label from the connections' configuration.
522 3
     *
523 3
     * @param array $connection Connection configuration
524
     * @return string Connection label
525 3
     */
526
    protected function buildConnectionLabel(array $connection)
527
    {
528
        $connectionLabel = $connection['rootPageTitle']
529
            . ' (pid: ' . $connection['rootPageUid']
530
            . ', language: ' . $this->getLanguageName($connection['language'])
531
            . ') - '
532
#			. $connection['solrScheme'] . '://'
533
            . $connection['solrHost'] . ':'
534
            . $connection['solrPort']
535
            . $connection['solrPath'];
536 3
537
        return $connectionLabel;
538 3
    }
539 3
540
    /**
541
     * Filters duplicate connections. When detecting the configured connections
542 3
     * this is done with a little brute force by simply combining all root pages
543 3
     * with all languages, this method filters out the duplicates.
544 3
     *
545 3
     * @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
            unset($connection['language']);
556
            $connectionHash = md5(implode('|', $connection));
557
            $hashedConnections[$key] = $connectionHash;
558
        }
559
560
        $hashedConnections = array_unique($hashedConnections);
561
562 3
        foreach ($hashedConnections as $key => $hash) {
563
            $filteredConnections[$key] = $connections[$key];
564 3
        }
565
566 3
        return $filteredConnections;
567 3
    }
568 3
569 3
    /**
570
     * Finds the system's configured languages.
571
     *
572 3
     * @return array An array of language IDs
573
     */
574
    protected function getSystemLanguages()
575
    {
576 3
        $languages = [0];
577
578
        $languageRecords = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
579 3
            'uid',
580
            'sys_language',
581
            'hidden = 0'
582
        );
583
584
        if (!is_array($languageRecords)) {
585
            return $languages;
586
        }
587
588 2
        foreach ($languageRecords as $languageRecord) {
589
            $languages[] = $languageRecord['uid'];
590 2
        }
591 2
        return $languages;
592 2
    }
593 2
594
    /**
595
     * Gets the site's root pages. The "Is root of website" flag must be set,
596 2
     * 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
    protected function getRootPages()
601
    {
602
        $rootPages = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
603
            'uid, title',
604
            'pages',
605
            'is_siteroot = 1 AND deleted = 0 AND hidden = 0 AND pid != -1'
606
        );
607
608
        return $rootPages;
609
    }
610
}
611