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