[BUGFIX] Fix collection of allowed pages in suggest receiver
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Form / Wizard / SuggestWizardDefaultReceiver.php
1 <?php
2 namespace TYPO3\CMS\Backend\Form\Wizard;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Core\Database\Connection;
19 use TYPO3\CMS\Core\Database\ConnectionPool;
20 use TYPO3\CMS\Core\Database\Query\QueryBuilder;
21 use TYPO3\CMS\Core\Database\Query\QueryHelper;
22 use TYPO3\CMS\Core\Database\Query\Restriction\BackendWorkspaceRestriction;
23 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
24 use TYPO3\CMS\Core\Imaging\Icon;
25 use TYPO3\CMS\Core\Imaging\IconFactory;
26 use TYPO3\CMS\Core\Localization\LanguageService;
27 use TYPO3\CMS\Core\Type\Bitmask\Permission;
28 use TYPO3\CMS\Core\Utility\ArrayUtility;
29 use TYPO3\CMS\Core\Utility\GeneralUtility;
30 use TYPO3\CMS\Core\Utility\MathUtility;
31
32 /**
33 * Default implementation of a handler class for an ajax record selector.
34 *
35 * Normally other implementations should be inherited from this one.
36 * queryTable() should not be overwritten under normal circumstances.
37 */
38 class SuggestWizardDefaultReceiver
39 {
40 /**
41 * The name of the table to query
42 *
43 * @var string
44 */
45 protected $table = '';
46
47 /**
48 * The name of the foreign table to query (records from this table will be used for displaying instead of the ones
49 * from $table)
50 *
51 * @var string
52 */
53 protected $mmForeignTable = '';
54
55 /**
56 * Configuration for this selector from TSconfig
57 *
58 * @var array
59 */
60 protected $config = [];
61
62 /**
63 * The list of pages that are allowed to perform the search for records on
64 *
65 * @var array Array of PIDs
66 */
67 protected $allowedPages = [];
68
69 /**
70 * The maximum number of items to select.
71 *
72 * @var int
73 */
74 protected $maxItems = 10;
75
76 /**
77 * @var array
78 */
79 protected $params = [];
80
81 /**
82 * @var IconFactory
83 */
84 protected $iconFactory;
85
86 /**
87 * @var QueryBuilder
88 */
89 protected $queryBuilder;
90
91 /**
92 * The constructor of this class
93 *
94 * @param string $table The table to query
95 * @param array $config The configuration (TCA overlaid with TSconfig) to use for this selector
96 */
97 public function __construct($table, $config)
98 {
99 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
100 $this->queryBuilder = $this->getQueryBuilderForTable($table);
101 $this->queryBuilder->getRestrictions()
102 ->removeAll()
103 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
104 // if table is versionized, only get the records from the Live Workspace
105 // the overlay itself of WS-records is done below
106 ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class, 0));
107 $this->table = $table;
108 $this->config = $config;
109 // get a list of all the pages that should be looked on
110 if (isset($config['pidList'])) {
111 $allowedPages = ($pageIds = GeneralUtility::trimExplode(',', $config['pidList']));
112 $depth = (int)$config['pidDepth'];
113 foreach ($pageIds as $pageId) {
114 if ($pageId > 0) {
115 ArrayUtility::mergeRecursiveWithOverrule($allowedPages, $this->getAllSubpagesOfPage($pageId, $depth));
116 }
117 }
118 $this->allowedPages = array_unique($allowedPages);
119 }
120 if (isset($config['maxItemsInResultList'])) {
121 $this->maxItems = $config['maxItemsInResultList'];
122 }
123 if ($this->table === 'pages') {
124 $this->queryBuilder->andWhere(
125 QueryHelper::stripLogicalOperatorPrefix($GLOBALS['BE_USER']->getPagePermsClause(Permission::PAGE_SHOW)),
126 $this->queryBuilder->expr()->eq('sys_language_uid', 0)
127 );
128 }
129 if (isset($config['addWhere'])) {
130 $this->queryBuilder->andWhere(
131 QueryHelper::stripLogicalOperatorPrefix($config['addWhere'])
132 );
133 }
134 }
135
136 /**
137 * Queries a table for records and completely processes them
138 *
139 * Returns a two-dimensional array of almost finished records; the only need to be put into a <li>-structure
140 *
141 * If you subclass this class, you will most likely only want to overwrite the functions called from here, but not
142 * this function itself
143 *
144 * @param array $params
145 * @param int $recursionCounter The parent object
146 * @return array Array of rows or FALSE if nothing found
147 */
148 public function queryTable(&$params, $recursionCounter = 0)
149 {
150 $maxQueryResults = 50;
151 $rows = [];
152 $this->params = &$params;
153 $start = $recursionCounter * $maxQueryResults;
154 $this->prepareSelectStatement();
155 $this->prepareOrderByStatement();
156 $result = $this->queryBuilder->select('*')
157 ->from($this->table)
158 ->setFirstResult($start)
159 ->setMaxResults($maxQueryResults)
160 ->execute();
161 $allRowsCount = $this->queryBuilder
162 ->count('uid')
163 ->resetQueryPart('orderBy')
164 ->execute()
165 ->fetchColumn(0);
166 if ($allRowsCount) {
167 while ($row = $result->fetch()) {
168 // check if we already have collected the maximum number of records
169 if (count($rows) > $this->maxItems) {
170 break;
171 }
172 $this->manipulateRecord($row);
173 $this->makeWorkspaceOverlay($row);
174 // check if the user has access to the record
175 if (!$this->checkRecordAccess($row, $row['uid'])) {
176 continue;
177 }
178 $spriteIcon = $this->iconFactory->getIconForRecord($this->table, $row, Icon::SIZE_SMALL)->render();
179 $uid = $row['t3ver_oid'] > 0 ? $row['t3ver_oid'] : $row['uid'];
180 $path = $this->getRecordPath($row, $uid);
181 if (mb_strlen($path, 'utf-8') > 30) {
182 $croppedPath = '<abbr title="' . htmlspecialchars($path) . '">' .
183 htmlspecialchars(
184 mb_substr($path, 0, 10, 'utf-8')
185 . '...'
186 . mb_substr($path, -20, null, 'utf-8')
187 ) .
188 '</abbr>';
189 } else {
190 $croppedPath = htmlspecialchars($path);
191 }
192 $label = $this->getLabel($row);
193 $entry = [
194 'text' => '<span class="suggest-label">' . $label . '</span><span class="suggest-uid">[' . $uid . ']</span><br />
195 <span class="suggest-path">' . $croppedPath . '</span>',
196 'table' => $this->mmForeignTable ? $this->mmForeignTable : $this->table,
197 'label' => $label,
198 'path' => $path,
199 'uid' => $uid,
200 'style' => '',
201 'class' => $this->config['cssClass'] ?? '',
202 'sprite' => $spriteIcon
203 ];
204 $rows[$this->table . '_' . $uid] = $this->renderRecord($row, $entry);
205 }
206
207 // if there are less records than we need, call this function again to get more records
208 if (count($rows) < $this->maxItems && $allRowsCount >= $maxQueryResults && $recursionCounter < $this->maxItems) {
209 $tmp = self::queryTable($params, ++$recursionCounter);
210 $rows = array_merge($tmp, $rows);
211 }
212 }
213 return $rows;
214 }
215
216 /**
217 * Prepare the statement for selecting the records which will be returned to the selector. May also return some
218 * other records (e.g. from a mm-table) which will be used later on to select the real records
219 */
220 protected function prepareSelectStatement()
221 {
222 $expressionBuilder = $this->queryBuilder->expr();
223 $searchString = $this->params['value'];
224 if ($searchString !== '') {
225 $splitStrings = $this->splitSearchString($searchString);
226 $constraints = [];
227 foreach ($splitStrings as $splitString) {
228 $constraints[] = $this->buildConstraintBlock($splitString);
229 }
230 foreach ($constraints as $constraint) {
231 $this->queryBuilder->andWhere($expressionBuilder->andX($constraint));
232 }
233 }
234 if (!empty($this->allowedPages)) {
235 $pidList = array_map('intval', $this->allowedPages);
236 if (!empty($pidList)) {
237 $this->queryBuilder->andWhere(
238 $expressionBuilder->in('pid', $pidList)
239 );
240 }
241 }
242 // add an additional search condition comment
243 if (isset($this->config['searchCondition']) && $this->config['searchCondition'] !== '') {
244 $this->queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($this->config['searchCondition']));
245 }
246 }
247
248 /**
249 * Creates OR constraints for each split searchWord.
250 *
251 * @param string $searchString
252 * @return string|\TYPO3\CMS\Core\Database\Query\Expression\CompositeExpression
253 */
254 protected function buildConstraintBlock(string $searchString)
255 {
256 $expressionBuilder = $this->queryBuilder->expr();
257 if (MathUtility::canBeInterpretedAsInteger($searchString) && (int)$searchString > 0) {
258 $searchClause = $expressionBuilder->eq('uid', (int)$searchString);
259 } else {
260 $searchWholePhrase = !isset($this->config['searchWholePhrase']) || $this->config['searchWholePhrase'];
261 $likeCondition = ($searchWholePhrase ? '%' : '') . $this->queryBuilder->escapeLikeWildcards($searchString) . '%';
262 // Search in all fields given by label or label_alt
263 $selectFieldsList = ($GLOBALS['TCA'][$this->table]['ctrl']['label'] ?? '') . ',' . ($GLOBALS['TCA'][$this->table]['ctrl']['label_alt'] ?? '') . ',' . $this->config['additionalSearchFields'];
264 $selectFields = GeneralUtility::trimExplode(',', $selectFieldsList, true);
265 $selectFields = array_unique($selectFields);
266 $selectParts = $expressionBuilder->orX();
267 foreach ($selectFields as $field) {
268 $selectParts->add($expressionBuilder->like($field, $this->queryBuilder->createPositionalParameter($likeCondition)));
269 }
270 $searchClause = $expressionBuilder->orX($selectParts);
271 }
272 return $searchClause;
273 }
274
275 /**
276 * Splits the search string by +
277 * This allows searching for "elements+basic" and will find results like
278 * "elements rte basic
279 *
280 * @param string $searchString
281 * @return array
282 */
283 protected function splitSearchString(string $searchString): array
284 {
285 $spitStrings = GeneralUtility::trimExplode('+', $searchString, true);
286 return $spitStrings;
287 }
288
289 /**
290 * Selects all subpages of one page, optionally only up to a certain level
291 *
292 * @param int $uid The uid of the page
293 * @param int $depth The depth to select up to. Defaults to 99
294 * @return array of page IDs
295 */
296 protected function getAllSubpagesOfPage($uid, $depth = 99)
297 {
298 $pageIds = [$uid];
299 $level = 0;
300 $pages = [$uid];
301 $queryBuilder = $this->getQueryBuilderForTable('pages');
302 $queryBuilder->select('uid')
303 ->from('pages');
304 // fetch all
305 while ($depth - $level > 0 && !empty($pageIds)) {
306 ++$level;
307 $rows = $queryBuilder
308 ->where(
309 $queryBuilder->expr()->in(
310 'pid',
311 $queryBuilder->createNamedParameter($pageIds, Connection::PARAM_INT_ARRAY)
312 ),
313 $queryBuilder->expr()->eq('sys_language_uid', 0)
314 )
315 ->execute()
316 ->fetchAll();
317
318 $rows = array_column(($rows ?: []), 'uid', 'uid');
319 if (!count($rows)) {
320 break;
321 }
322
323 $pageIds = array_keys($rows);
324 $pages = array_merge($pages, $pageIds);
325 }
326 return $pages;
327 }
328
329 /**
330 * Prepares the clause by which the result elements are sorted. See description of ORDER BY in
331 * SQL standard for reference.
332 */
333 protected function prepareOrderByStatement()
334 {
335 if (empty($this->config['orderBy'])) {
336 $this->queryBuilder->addOrderBy($GLOBALS['TCA'][$this->table]['ctrl']['label']);
337 } else {
338 foreach (QueryHelper::parseOrderBy($this->config['orderBy']) as $orderPair) {
339 list($fieldName, $order) = $orderPair;
340 $this->queryBuilder->addOrderBy($fieldName, $order);
341 }
342 }
343 }
344
345 /**
346 * Manipulate a record before using it to render the selector; may be used to replace a MM-relation etc.
347 *
348 * @param array $row
349 */
350 protected function manipulateRecord(&$row)
351 {
352 }
353
354 /**
355 * Selects whether the logged in Backend User is allowed to read a specific record
356 *
357 * @param array $row
358 * @param int $uid
359 * @return bool
360 */
361 protected function checkRecordAccess($row, $uid)
362 {
363 $retValue = true;
364 $table = $this->mmForeignTable ?: $this->table;
365 if ($table === 'pages') {
366 if (!BackendUtility::readPageAccess($uid, $GLOBALS['BE_USER']->getPagePermsClause(Permission::PAGE_SHOW))) {
367 $retValue = false;
368 }
369 } elseif (isset($GLOBALS['TCA'][$table]['ctrl']['is_static']) && (bool)$GLOBALS['TCA'][$table]['ctrl']['is_static']) {
370 $retValue = true;
371 } else {
372 if (!is_array(BackendUtility::readPageAccess($row['pid'], $GLOBALS['BE_USER']->getPagePermsClause(Permission::PAGE_SHOW)))) {
373 $retValue = false;
374 }
375 }
376 return $retValue;
377 }
378
379 /**
380 * Overlay the given record with its workspace-version, if any
381 *
382 * @param array $row The record to get the workspace version for
383 */
384 protected function makeWorkspaceOverlay(&$row)
385 {
386 // Check for workspace-versions
387 if ($GLOBALS['BE_USER']->workspace != 0 && $GLOBALS['TCA'][$this->table]['ctrl']['versioningWS'] == true) {
388 BackendUtility::workspaceOL($this->mmForeignTable ? $this->mmForeignTable : $this->table, $row);
389 }
390 }
391
392 /**
393 * Returns the path for a record. Is the whole path for all records except pages - for these the last part is cut
394 * off, because it contains the pagetitle itself, which would be double information
395 *
396 * The path is returned uncut, cutting has to be done by calling function.
397 *
398 * @param array $row The row
399 * @param int $uid UID of the record
400 * @return string The record-path
401 */
402 protected function getRecordPath(&$row, $uid)
403 {
404 $titleLimit = max($this->config['maxPathTitleLength'], 0);
405 if (($this->mmForeignTable ? $this->mmForeignTable : $this->table) === 'pages') {
406 $path = BackendUtility::getRecordPath($uid, '', $titleLimit);
407 // For pages we only want the first (n-1) parts of the path,
408 // because the n-th part is the page itself
409 $path = substr($path, 0, strrpos($path, '/', -2)) . '/';
410 } else {
411 $path = BackendUtility::getRecordPath($row['pid'], '', $titleLimit);
412 }
413 return $path;
414 }
415
416 /**
417 * Returns a label for a given record; usually only a wrapper for \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordTitle
418 *
419 * @param array $row The record to get the label for
420 * @return string The label
421 */
422 protected function getLabel($row)
423 {
424 return BackendUtility::getRecordTitle($this->mmForeignTable ? $this->mmForeignTable : $this->table, $row, true);
425 }
426
427 /**
428 * Calls a user function for rendering the page.
429 *
430 * This user function should manipulate $entry, especially $entry['text'].
431 *
432 * @param array $row The row
433 * @param array $entry The entry to render
434 * @return array The rendered entry (will be put into a <li> later on
435 */
436 protected function renderRecord($row, $entry)
437 {
438 // Call renderlet if available (normal pages etc. usually don't have one)
439 if ($this->config['renderFunc'] != '') {
440 $params = [
441 'table' => $this->table,
442 'uid' => $row['uid'],
443 'row' => $row,
444 'entry' => &$entry
445 ];
446 GeneralUtility::callUserFunction($this->config['renderFunc'], $params, $this);
447 }
448 return $entry;
449 }
450
451 /**
452 * @return LanguageService
453 */
454 protected function getLanguageService()
455 {
456 return $GLOBALS['LANG'];
457 }
458
459 /**
460 * @param string $table
461 * @return QueryBuilder
462 */
463 protected function getQueryBuilderForTable($table)
464 {
465 return GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
466 }
467 }