b9663a09af0bcffe4c244b571eb4e5929557ce10
[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 $rows = [];
151 $this->params = &$params;
152 $start = $recursionCounter * 50;
153 $this->prepareSelectStatement();
154 $this->prepareOrderByStatement();
155 $result = $this->queryBuilder->select('*')
156 ->from($this->table)
157 ->setFirstResult($start)
158 ->setMaxResults(50)
159 ->execute();
160 $allRowsCount = GeneralUtility::makeInstance(ConnectionPool::class)
161 ->getQueryBuilderForTable($this->table)
162 ->count('uid')
163 ->execute()
164 ->fetchColumn(0);
165 if ($allRowsCount) {
166 while ($row = $result->fetch()) {
167 // check if we already have collected the maximum number of records
168 if (count($rows) > $this->maxItems) {
169 break;
170 }
171 $this->manipulateRecord($row);
172 $this->makeWorkspaceOverlay($row);
173 // check if the user has access to the record
174 if (!$this->checkRecordAccess($row, $row['uid'])) {
175 continue;
176 }
177 $spriteIcon = $this->iconFactory->getIconForRecord($this->table, $row, Icon::SIZE_SMALL)->render();
178 $uid = $row['t3ver_oid'] > 0 ? $row['t3ver_oid'] : $row['uid'];
179 $path = $this->getRecordPath($row, $uid);
180 if (mb_strlen($path, 'utf-8') > 30) {
181 $croppedPath = '<abbr title="' . htmlspecialchars($path) . '">' .
182 htmlspecialchars(
183 mb_substr($path, 0, 10, 'utf-8')
184 . '...'
185 . mb_substr($path, -20, null, 'utf-8')
186 ) .
187 '</abbr>';
188 } else {
189 $croppedPath = htmlspecialchars($path);
190 }
191 $label = $this->getLabel($row);
192 $entry = [
193 'text' => '<span class="suggest-label">' . $label . '</span><span class="suggest-uid">[' . $uid . ']</span><br />
194 <span class="suggest-path">' . $croppedPath . '</span>',
195 'table' => $this->mmForeignTable ? $this->mmForeignTable : $this->table,
196 'label' => $label,
197 'path' => $path,
198 'uid' => $uid,
199 'style' => '',
200 'class' => $this->config['cssClass'] ?? '',
201 'sprite' => $spriteIcon
202 ];
203 $rows[$this->table . '_' . $uid] = $this->renderRecord($row, $entry);
204 }
205
206 // if there are less records than we need, call this function again to get more records
207 if (count($rows) < $this->maxItems && $allRowsCount >= 50 && $recursionCounter < $this->maxItems) {
208 $tmp = self::queryTable($params, ++$recursionCounter);
209 $rows = array_merge($tmp, $rows);
210 }
211 }
212 return $rows;
213 }
214
215 /**
216 * Prepare the statement for selecting the records which will be returned to the selector. May also return some
217 * other records (e.g. from a mm-table) which will be used later on to select the real records
218 */
219 protected function prepareSelectStatement()
220 {
221 $expressionBuilder = $this->queryBuilder->expr();
222 $searchString = $this->params['value'];
223 if ($searchString !== '') {
224 $splitStrings = $this->splitSearchString($searchString);
225 $constraints = [];
226 foreach ($splitStrings as $splitString) {
227 $constraints[] = $this->buildConstraintBlock($splitString);
228 }
229 foreach ($constraints as $constraint) {
230 $this->queryBuilder->andWhere($expressionBuilder->andX($constraint));
231 }
232 }
233 if (!empty($this->allowedPages)) {
234 $pidList = array_map('intval', $this->allowedPages);
235 if (!empty($pidList)) {
236 $this->queryBuilder->andWhere(
237 $expressionBuilder->in('pid', $pidList)
238 );
239 }
240 }
241 // add an additional search condition comment
242 if (isset($this->config['searchCondition']) && $this->config['searchCondition'] !== '') {
243 $this->queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($this->config['searchCondition']));
244 }
245 }
246
247 /**
248 * Creates OR constraints for each split searchWord.
249 *
250 * @param string $searchString
251 * @return string|\TYPO3\CMS\Core\Database\Query\Expression\CompositeExpression
252 */
253 protected function buildConstraintBlock(string $searchString)
254 {
255 $expressionBuilder = $this->queryBuilder->expr();
256 if (MathUtility::canBeInterpretedAsInteger($searchString) && (int)$searchString > 0) {
257 $searchClause = $expressionBuilder->eq('uid', (int)$searchString);
258 } else {
259 $searchWholePhrase = !isset($this->config['searchWholePhrase']) || $this->config['searchWholePhrase'];
260 $likeCondition = ($searchWholePhrase ? '%' : '') . $this->queryBuilder->escapeLikeWildcards($searchString) . '%';
261 // Search in all fields given by label or label_alt
262 $selectFieldsList = ($GLOBALS['TCA'][$this->table]['ctrl']['label'] ?? '') . ',' . ($GLOBALS['TCA'][$this->table]['ctrl']['label_alt'] ?? '') . ',' . $this->config['additionalSearchFields'];
263 $selectFields = GeneralUtility::trimExplode(',', $selectFieldsList, true);
264 $selectFields = array_unique($selectFields);
265 $selectParts = $expressionBuilder->orX();
266 foreach ($selectFields as $field) {
267 $selectParts->add($expressionBuilder->like($field, $this->queryBuilder->createPositionalParameter($likeCondition)));
268 }
269 $searchClause = $expressionBuilder->orX($selectParts);
270 }
271 return $searchClause;
272 }
273
274 /**
275 * Splits the search string by +
276 * This allows searching for "elements+basic" and will find results like
277 * "elements rte basic
278 *
279 * @param string $searchString
280 * @return array
281 */
282 protected function splitSearchString(string $searchString): array
283 {
284 $spitStrings = GeneralUtility::trimExplode('+', $searchString, true);
285 return $spitStrings;
286 }
287
288 /**
289 * Selects all subpages of one page, optionally only up to a certain level
290 *
291 * @param int $uid The uid of the page
292 * @param int $depth The depth to select up to. Defaults to 99
293 * @return array of page IDs
294 */
295 protected function getAllSubpagesOfPage($uid, $depth = 99)
296 {
297 $pageIds = [$uid];
298 $level = 0;
299 $pages = [$uid];
300 $queryBuilder = $this->getQueryBuilderForTable('pages');
301 $queryBuilder->select('uid')
302 ->from('pages');
303 // fetch all
304 while ($depth - $level > 0 && !empty($pageIds)) {
305 ++$level;
306 $rows = $queryBuilder
307 ->where(
308 $queryBuilder->expr()->in(
309 'pid',
310 $queryBuilder->createNamedParameter($pageIds, Connection::PARAM_INT_ARRAY)
311 )
312 )
313 ->execute()
314 ->fetchAll();
315
316 $rows = array_column(($rows ?: []), 'uid', 'uid');
317 if (!count($rows)) {
318 $pageIds = array_keys($rows);
319 $pages = array_merge($pages, $pageIds);
320 } else {
321 break;
322 }
323 }
324 return $pages;
325 }
326
327 /**
328 * Prepares the clause by which the result elements are sorted. See description of ORDER BY in
329 * SQL standard for reference.
330 */
331 protected function prepareOrderByStatement()
332 {
333 if (empty($this->config['orderBy'])) {
334 $this->queryBuilder->addOrderBy($GLOBALS['TCA'][$this->table]['ctrl']['label']);
335 } else {
336 foreach (QueryHelper::parseOrderBy($this->config['orderBy']) as $orderPair) {
337 list($fieldName, $order) = $orderPair;
338 $this->queryBuilder->addOrderBy($fieldName, $order);
339 }
340 }
341 }
342
343 /**
344 * Manipulate a record before using it to render the selector; may be used to replace a MM-relation etc.
345 *
346 * @param array $row
347 */
348 protected function manipulateRecord(&$row)
349 {
350 }
351
352 /**
353 * Selects whether the logged in Backend User is allowed to read a specific record
354 *
355 * @param array $row
356 * @param int $uid
357 * @return bool
358 */
359 protected function checkRecordAccess($row, $uid)
360 {
361 $retValue = true;
362 $table = $this->mmForeignTable ?: $this->table;
363 if ($table === 'pages') {
364 if (!BackendUtility::readPageAccess($uid, $GLOBALS['BE_USER']->getPagePermsClause(Permission::PAGE_SHOW))) {
365 $retValue = false;
366 }
367 } elseif (isset($GLOBALS['TCA'][$table]['ctrl']['is_static']) && (bool)$GLOBALS['TCA'][$table]['ctrl']['is_static']) {
368 $retValue = true;
369 } else {
370 if (!is_array(BackendUtility::readPageAccess($row['pid'], $GLOBALS['BE_USER']->getPagePermsClause(Permission::PAGE_SHOW)))) {
371 $retValue = false;
372 }
373 }
374 return $retValue;
375 }
376
377 /**
378 * Overlay the given record with its workspace-version, if any
379 *
380 * @param array $row The record to get the workspace version for
381 */
382 protected function makeWorkspaceOverlay(&$row)
383 {
384 // Check for workspace-versions
385 if ($GLOBALS['BE_USER']->workspace != 0 && $GLOBALS['TCA'][$this->table]['ctrl']['versioningWS'] == true) {
386 BackendUtility::workspaceOL($this->mmForeignTable ? $this->mmForeignTable : $this->table, $row);
387 }
388 }
389
390 /**
391 * Returns the path for a record. Is the whole path for all records except pages - for these the last part is cut
392 * off, because it contains the pagetitle itself, which would be double information
393 *
394 * The path is returned uncut, cutting has to be done by calling function.
395 *
396 * @param array $row The row
397 * @param int $uid UID of the record
398 * @return string The record-path
399 */
400 protected function getRecordPath(&$row, $uid)
401 {
402 $titleLimit = max($this->config['maxPathTitleLength'], 0);
403 if (($this->mmForeignTable ? $this->mmForeignTable : $this->table) === 'pages') {
404 $path = BackendUtility::getRecordPath($uid, '', $titleLimit);
405 // For pages we only want the first (n-1) parts of the path,
406 // because the n-th part is the page itself
407 $path = substr($path, 0, strrpos($path, '/', -2)) . '/';
408 } else {
409 $path = BackendUtility::getRecordPath($row['pid'], '', $titleLimit);
410 }
411 return $path;
412 }
413
414 /**
415 * Returns a label for a given record; usually only a wrapper for \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordTitle
416 *
417 * @param array $row The record to get the label for
418 * @return string The label
419 */
420 protected function getLabel($row)
421 {
422 return BackendUtility::getRecordTitle($this->mmForeignTable ? $this->mmForeignTable : $this->table, $row, true);
423 }
424
425 /**
426 * Calls a user function for rendering the page.
427 *
428 * This user function should manipulate $entry, especially $entry['text'].
429 *
430 * @param array $row The row
431 * @param array $entry The entry to render
432 * @return array The rendered entry (will be put into a <li> later on
433 */
434 protected function renderRecord($row, $entry)
435 {
436 // Call renderlet if available (normal pages etc. usually don't have one)
437 if ($this->config['renderFunc'] != '') {
438 $params = [
439 'table' => $this->table,
440 'uid' => $row['uid'],
441 'row' => $row,
442 'entry' => &$entry
443 ];
444 GeneralUtility::callUserFunction($this->config['renderFunc'], $params, $this);
445 }
446 return $entry;
447 }
448
449 /**
450 * @return LanguageService
451 */
452 protected function getLanguageService()
453 {
454 return $GLOBALS['LANG'];
455 }
456
457 /**
458 * @param string $table
459 * @return QueryBuilder
460 */
461 protected function getQueryBuilderForTable($table)
462 {
463 return GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
464 }
465 }