Failed Conditions
Push — task/2976_TYPO3.11_compatibili... ( 38a128...0b41c4 )
by Rafael
25:41 queued 19:10
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

Importance

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