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