Passed
Push — master ( 934601...b68881 )
by Rafael
44:37
created

Page::validateMountPoint()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 35
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 3.1406

Importance

Changes 0
Metric Value
eloc 22
c 0
b 0
f 0
dl 0
loc 35
ccs 21
cts 28
cp 0.75
rs 9.568
cc 3
nc 4
nop 1
crap 3.1406
1
<?php
2
namespace ApacheSolrForTypo3\Solr\IndexQueue\Initializer;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2011-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 3 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
 *  A copy is found in the textfile GPL.txt and important notices to the license
19
 *  from the author is found in LICENSE.txt distributed with these scripts.
20
 *
21
 *
22
 *  This script is distributed in the hope that it will be useful,
23
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
24
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25
 *  GNU General Public License for more details.
26
 *
27
 *  This copyright notice MUST APPEAR in all copies of the script!
28
 ***************************************************************/
29
30
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\QueueItemRepository;
31
use ApacheSolrForTypo3\Solr\Domain\Site\SiteInterface;
32
use ApacheSolrForTypo3\Solr\Domain\Site\SiteRepository;
33
use ApacheSolrForTypo3\Solr\IndexQueue\Item;
34
use ApacheSolrForTypo3\Solr\IndexQueue\Queue;
35
use ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager;
36
use ApacheSolrForTypo3\Solr\System\Records\Pages\PagesRepository;
37
use Doctrine\DBAL\ConnectionException;
38
use Doctrine\DBAL\Exception as DBALException;
39
use Exception;
40
use TYPO3\CMS\Backend\Utility\BackendUtility;
41
use TYPO3\CMS\Core\Database\Connection;
42
use TYPO3\CMS\Core\Database\ConnectionPool;
43
use TYPO3\CMS\Core\Messaging\FlashMessage;
44
use TYPO3\CMS\Core\Utility\GeneralUtility;
45
46
/**
47
 * Index Queue initializer for pages which also covers resolution of mount
48
 * pages.
49
 *
50
 * @author Ingo Renner <[email protected]>
51
 */
52
class Page extends AbstractInitializer
53
{
54
    /**
55
     * The type of items this initializer is handling.
56
     * @var string
57
     */
58
    protected $type = 'pages';
59
60
    /**
61
     * @var PagesRepository
62
     */
63
    protected $pagesRepository;
64
65
    /**
66
     * Constructor, sets type and indexingConfigurationName to "pages".
67
     *
68 11
     * @param QueueItemRepository|null $queueItemRepository
69
     * @param PagesRepository|null $pagesRepository
70 11
     */
71 11
    public function __construct(QueueItemRepository $queueItemRepository = null, PagesRepository $pagesRepository = null)
72 11
    {
73
        parent::__construct($queueItemRepository);
74
        $this->pagesRepository = $pagesRepository ?? GeneralUtility::makeInstance(PagesRepository::class);
75
    }
76
77
    /**
78
     * Overrides the general setType() implementation, forcing type to "pages".
79 10
     *
80
     * @param string $type Type to initialize (ignored).
81 10
     */
82 10
    public function setType($type)
83
    {
84
        $this->type = 'pages';
85
    }
86
87
    /**
88
     * Initializes Index Queue page items for a site. Includes regular pages
89
     * and mounted pages - no nested mount page structures though.
90 10
     *
91
     * @return bool TRUE if initialization was successful, FALSE on error.
92 10
     */
93 10
    public function initialize()
94
    {
95 10
        $pagesInitialized = parent::initialize();
96
        $mountPagesInitialized = $this->initializeMountPointPages();
97
98
        return ($pagesInitialized && $mountPagesInitialized);
99
    }
100
101
    /**
102
     * Initialize a single page that is part of a mounted tree.
103
     *
104 1
     * @param array $mountProperties Array of mount point properties mountPageSource, mountPageDestination, and mountPageOverlayed
105
     * @param int $mountedPageId The ID of the mounted page
106 1
     */
107
    public function initializeMountedPage(array $mountProperties, int $mountedPageId)
108 1
    {
109 1
        $mountedPages = [$mountedPageId];
110 1
111
        $this->addMountedPagesToIndexQueue($mountedPages, $mountProperties);
112
        $this->addIndexQueueItemIndexingProperties($mountProperties, $mountedPages);
113
    }
114
115
    /**
116
     * Initializes Mount Point(pages) to be indexed through the Index Queue. The Mount
117
     * Points are searched and their mounted virtual sub-trees are then resolved
118
     * and added to the Index Queue as if they were actually present below the
119
     * Mount Point.
120 10
     *
121
     * @return bool TRUE if initialization of the Mount Pages was successful, FALSE otherwise
122 10
     * @throws ConnectionException
123 10
     */
124
    protected function initializeMountPointPages(): bool
125 10
    {
126 4
        $mountPointsInitialized = false;
127 4
        $mountPoints = $this->pagesRepository->findAllMountPagesByWhereClause($this->buildPagesClause() . $this->buildTcaWhereClause() . ' AND doktype = 7 AND no_search = 0');
128
129
        if (empty($mountPoints)) {
130 6
            return true;
131 6
        }
132 6
133
        $databaseConnection = $this->queueItemRepository->getConnectionForAllInTransactionInvolvedTables(
134
            'tx_solr_indexqueue_item',
135 6
            'tx_solr_indexqueue_indexing_property'
136 6
        );
137 3
138
        foreach ($mountPoints as $mountPoint) {
139
            if (!$this->validateMountPoint($mountPoint)) {
140 6
                continue;
141
            }
142
143 6
            $mountedPages = $this->resolveMountPageTree($mountPoint);
144
145 3
            // handling mount_pid_ol behavior
146
            if (!$mountPoint['mountPageOverlayed']) {
147
                // Add page like a regular page, as only the sub tree is mounted.
148
                // The page itself has its own content, which is handled like standard page.
149 3
                $indexQueue = GeneralUtility::makeInstance(Queue::class);
150 3
                $indexQueue->updateItem($this->type, $mountPoint['uid']);
151
            }
152
153
            // This can happen when the mount point does not show the content of the
154
            // mounted page and the mounted page does not have any subpages.
155 6
            if (empty($mountedPages)) {
156
                continue;
157
            }
158
159 6
            $databaseConnection->beginTransaction();
160
            try {
161 6
                $this->addMountedPagesToIndexQueue($mountedPages, $mountPoint);
162 6
                $this->addIndexQueueItemIndexingProperties($mountPoint, $mountedPages);
163
164 6
                $databaseConnection->commit();
165 6
                $mountPointsInitialized = true;
166
            } catch (Exception $e) {
167
                $databaseConnection->rollBack();
168
169
                $this->logger->log(
170
                    SolrLogManager::ERROR,
171
                    'Index Queue initialization failed for mount pages',
172
                    [
173
                        $e->__toString()
174
                    ]
175
                );
176
                break;
177
            }
178
        }
179
180 6
        return $mountPointsInitialized;
181
    }
182
183
    /**
184
     * Checks whether a Mount Point page is properly configured.
185
     *
186
     * @param array $mountPoint A mount page
187
     * @return bool TRUE if the Mount Page is OK, FALSE otherwise
188
     */
189 6
    protected function validateMountPoint(array $mountPoint): bool
190
    {
191 6
        $isValidMountPage = true;
192
193 6
        if (empty($mountPoint['mountPageSource'])) {
194 3
            $isValidMountPage = false;
195
196 3
            $flashMessage = GeneralUtility::makeInstance(
197 3
                FlashMessage::class,
198 3
                'Property "Mounted page" must not be empty. Invalid Mount Page configuration for page ID ' . $mountPoint['uid'] . '.',
199 3
                'Failed to initialize Mount Page tree. ',
200 3
                FlashMessage::ERROR
201
            );
202
            // @extensionScannerIgnoreLine
203 3
            $this->flashMessageQueue->addMessage($flashMessage);
204
        }
205
206 6
        if (!$this->mountedPageExists($mountPoint['mountPageSource'])) {
207 3
            $isValidMountPage = false;
208
209 3
            $flashMessage = GeneralUtility::makeInstance(
210 3
                FlashMessage::class,
211
                'The mounted page must be accessible in the frontend. '
212
                . 'Invalid Mount Page configuration for page ID '
213 3
                . $mountPoint['uid'] . ', the mounted page with ID '
214 3
                . $mountPoint['mountPageSource']
215 3
                . ' is not accessible in the frontend.',
216 3
                'Failed to initialize Mount Page tree. ',
217 3
                FlashMessage::ERROR
218
            );
219
            // @extensionScannerIgnoreLine
220 3
            $this->flashMessageQueue->addMessage($flashMessage);
221
        }
222
223 6
        return $isValidMountPage;
224
    }
225
226
    /**
227
     * Checks whether the mounted page (mount page source) exists. That is,
228
     * whether it accessible in the frontend. So the record must exist
229
     * (deleted = 0) and must not be hidden (hidden = 0).
230
     *
231
     * @param int $mountedPageId Mounted page ID
232
     * @return bool TRUE if the page is accessible in the frontend, FALSE otherwise.
233
     */
234 6
    protected function mountedPageExists($mountedPageId): bool
235
    {
236 6
        $mountedPageExists = false;
237
238 6
        $mountedPage = BackendUtility::getRecord('pages', $mountedPageId, 'uid', ' AND hidden = 0');
239 6
        if (!empty($mountedPage)) {
240 6
            $mountedPageExists = true;
241
        }
242
243 6
        return $mountedPageExists;
244
    }
245
246
    /**
247
     * Adds the virtual / mounted pages to the Index Queue as if they would
248
     * belong to the same site where they are mounted.
249
     *
250
     * @param array $mountedPages An array of mounted page IDs
251
     * @param array $mountProperties Array with mount point properties (mountPageSource, mountPageDestination, mountPageOverlayed)
252
     */
253 7
    protected function addMountedPagesToIndexQueue(array $mountedPages, array $mountProperties)
254
    {
255 7
        $mountPointIdentifier = $this->getMountPointIdentifier($mountProperties);
256 7
        $mountPointPageIsWithExistingQueueEntry = $this->queueItemRepository->findPageIdsOfExistingMountPagesByMountIdentifier($mountPointIdentifier);
257 7
        $mountedPagesThatNeedToBeAdded = array_diff($mountedPages, $mountPointPageIsWithExistingQueueEntry);
258
259 7
        if (count($mountedPagesThatNeedToBeAdded) === 0) {
260
            //nothing to do
261
            return;
262
        }
263
264
        /* @var Connection $connection */
265 7
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_solr_indexqueue_item');
266
267 7
        $mountIdentifier = $this->getMountPointIdentifier($mountProperties);
268
        $initializationQuery = 'INSERT INTO tx_solr_indexqueue_item (root, item_type, item_uid, indexing_configuration, indexing_priority, changed, has_indexing_properties, pages_mountidentifier, errors) '
269 7
            . $this->buildSelectStatement() . ', 1, ' . $connection->quote($mountIdentifier, \PDO::PARAM_STR) . ',""'
270 7
            . 'FROM pages '
271 7
            . 'WHERE '
272 7
            . 'uid IN(' . implode(',', $mountedPagesThatNeedToBeAdded) . ') '
273 7
            . $this->buildTcaWhereClause()
274 7
            . $this->buildUserWhereClause();
275 7
        $logData = ['query' => $initializationQuery];
276
277
        try {
278 7
            $logData['rows'] = $this->queueItemRepository->initializeByNativeSQLStatement($initializationQuery);
279
        } catch (DBALException $DBALException) {
280
            $logData['error'] = $DBALException->getCode() . ': ' . $DBALException->getMessage();
281
        }
282
283 7
        $this->logInitialization($logData);
284 7
    }
285
286
    /**
287
     * Adds Index Queue item indexing properties for mounted pages. The page
288
     * indexer later needs to know that he's dealing with a mounted page, the
289
     * indexing properties will let make it possible for the indexer to
290
     * distinguish the mounted pages.
291
     *
292
     * @param array $mountPage An array with information about the root/destination Mount Page
293
     * @param array $mountedPages An array of mounted page IDs
294
     */
295 7
    protected function addIndexQueueItemIndexingProperties(array $mountPage, array $mountedPages)
296
    {
297 7
        $mountIdentifier = $this->getMountPointIdentifier($mountPage);
298 7
        $mountPageItems = $this->queueItemRepository->findAllIndexQueueItemsByRootPidAndMountIdentifierAndMountedPids($this->site->getRootPageId(), $mountIdentifier, $mountedPages);
299
300 7
        foreach ($mountPageItems as $mountPageItemRecord) {
301
            /* @var Item $mountPageItem */
302 7
            $mountPageItem = GeneralUtility::makeInstance(Item::class, /** @scrutinizer ignore-type */ $mountPageItemRecord);
303 7
            $mountPageItem->setIndexingProperty('mountPageSource', $mountPage['mountPageSource']);
304 7
            $mountPageItem->setIndexingProperty('mountPageDestination', $mountPage['mountPageDestination']);
305 7
            $mountPageItem->setIndexingProperty('isMountedPage', '1');
306
307 7
            $mountPageItem->storeIndexingProperties();
308
        }
309 7
    }
310
311
    /**
312
     * Builds an identifier of the given mount point properties.
313
     *
314
     * @param array $mountProperties Array with mount point properties (mountPageSource, mountPageDestination, mountPageOverlayed)
315
     * @return string String consisting of mountPageSource-mountPageDestination-mountPageOverlayed
316
     */
317 7
    protected function getMountPointIdentifier(array $mountProperties)
318
    {
319 7
        return $mountProperties['mountPageSource']
320 7
        . '-' . $mountProperties['mountPageDestination']
321 7
        . '-' . $mountProperties['mountPageOverlayed'];
322
    }
323
324
    // Mount Page resolution
325
326
    /**
327
     * Gets all the pages from a mounted page tree.
328
     *
329
     * @param array $mountPage
330
     * @return array An array of page IDs in the mounted page tree
331 6
     */
332
    protected function resolveMountPageTree(array $mountPage): array
333 6
    {
334 6
        $mountPageSourceId = (int)$mountPage['mountPageSource'];
335
336 6
        $mountPageTree = $this->site->getPages($mountPageSourceId, 'pages');
337
338 6
        // Do not include $mountPageSourceId in tree, if the mount point is not set to overlay.
339
        if (!empty($mountPageTree) && !$mountPage['mountPageOverlayed']) {
340 6
            $mountPageTree = array_diff($mountPageTree , [$mountPageSourceId]);
341
        }
342
343
        return $mountPageTree;
344
    }
345
}
346