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