2 namespace TYPO3\CMS\Backend\Form\Wizard
;
5 * This file is part of the TYPO3 CMS project.
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.
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
14 * The TYPO3 project - inspiring people to share!
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
;
31 * Default implementation of a handler class for an ajax record selector.
33 * Normally other implementations should be inherited from this one.
34 * queryTable() should not be overwritten under normal circumstances.
36 class SuggestWizardDefaultReceiver
39 * The name of the table to query
43 protected $table = '';
46 * The name of the foreign table to query (records from this table will be used for displaying instead of the ones
51 protected $mmForeignTable = '';
54 * Configuration for this selector from TSconfig
58 protected $config = [];
61 * The list of pages that are allowed to perform the search for records on
63 * @var array Array of PIDs
65 protected $allowedPages = [];
68 * The maximum number of items to select.
72 protected $maxItems = 10;
77 protected $params = [];
82 protected $iconFactory;
87 protected $queryBuilder;
90 * The constructor of this class
92 * @param string $table The table to query
93 * @param array $config The configuration (TCA overlaid with TSconfig) to use for this selector
95 public function __construct($table, $config)
97 $this->iconFactory
= GeneralUtility
::makeInstance(IconFactory
::class);
98 $this->queryBuilder
= $this->getQueryBuilderForTable($table);
99 $this->queryBuilder
->getRestrictions()
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) {
113 \TYPO3\CMS\Core\Utility\ArrayUtility
::mergeRecursiveWithOverrule($allowedPages, $this->getAllSubpagesOfPage($pageId, $depth));
116 $this->allowedPages
= array_unique($allowedPages);
118 if (isset($config['maxItemsInResultList'])) {
119 $this->maxItems
= $config['maxItemsInResultList'];
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)
127 if (isset($config['addWhere'])) {
128 $this->queryBuilder
->andWhere(
129 QueryHelper
::stripLogicalOperatorPrefix($config['addWhere'])
135 * Queries a table for records and completely processes them
137 * Returns a two-dimensional array of almost finished records; the only need to be put into a <li>-structure
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
142 * @param array $params
143 * @param int $recursionCounter The parent object
144 * @return array Array of rows or FALSE if nothing found
146 public function queryTable(&$params, $recursionCounter = 0)
149 $this->params
= &$params;
150 $start = $recursionCounter * 50;
151 $this->prepareSelectStatement();
152 $this->prepareOrderByStatement();
153 $result = $this->queryBuilder
->select('*')
155 ->setFirstResult($start)
158 $allRowsCount = $result->rowCount();
160 while ($row = $result->fetch()) {
161 // check if we already have collected the maximum number of records
162 if (count($rows) > $this->maxItems
) {
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'])) {
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) . '">' .
177 mb_substr($path, 0, 10, 'utf-8')
179 . mb_substr($path, -20, null, 'utf-8')
183 $croppedPath = htmlspecialchars($path);
185 $label = $this->getLabel($row);
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
,
194 'class' => $this->config
['cssClass'] ??
'',
195 'sprite' => $spriteIcon
197 $rows[$this->table
. '_' . $uid] = $this->renderRecord($row, $entry);
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);
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
213 protected function prepareSelectStatement()
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)));
230 $searchClause = $expressionBuilder->orX($selectParts);
231 if ($searchUid > 0 && $searchUid == $searchString) {
232 $searchClause->add($expressionBuilder->eq('uid', $searchUid));
235 $this->queryBuilder
->andWhere($expressionBuilder->orX($searchClause));
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)
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']));
252 * Selects all subpages of one page, optionally only up to a certain level
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
258 protected function getAllSubpagesOfPage($uid, $depth = 99)
263 $queryBuilder = $this->getQueryBuilderForTable('pages');
264 $queryBuilder->select('uid')
267 while ($depth - $level > 0 && !empty($pageIds)) {
269 $rows = $queryBuilder
271 $queryBuilder->expr()->in(
273 $queryBuilder->createNamedParameter($pageIds, Connection
::PARAM_INT_ARRAY
)
279 $rows = array_column(($rows ?
: []), 'uid', 'uid');
281 $pageIds = array_keys($rows);
282 $pages = array_merge($pages, $pageIds);
291 * Prepares the clause by which the result elements are sorted. See description of ORDER BY in
292 * SQL standard for reference.
294 protected function prepareOrderByStatement()
296 if (empty($this->config
['orderBy'])) {
297 $this->queryBuilder
->addOrderBy($GLOBALS['TCA'][$this->table
]['ctrl']['label']);
299 foreach (QueryHelper
::parseOrderBy($this->config
['orderBy']) as $orderPair) {
300 list($fieldName, $order) = $orderPair;
301 $this->queryBuilder
->addOrderBy($fieldName, $order);
307 * Manipulate a record before using it to render the selector; may be used to replace a MM-relation etc.
311 protected function manipulateRecord(&$row)
316 * Selects whether the logged in Backend User is allowed to read a specific record
322 protected function checkRecordAccess($row, $uid)
325 $table = $this->mmForeignTable ?
: $this->table
;
326 if ($table === 'pages') {
327 if (!BackendUtility
::readPageAccess($uid, $GLOBALS['BE_USER']->getPagePermsClause(Permission
::PAGE_SHOW
))) {
330 } elseif (isset($GLOBALS['TCA'][$table]['ctrl']['is_static']) && (bool)$GLOBALS['TCA'][$table]['ctrl']['is_static']) {
333 if (!is_array(BackendUtility
::readPageAccess($row['pid'], $GLOBALS['BE_USER']->getPagePermsClause(Permission
::PAGE_SHOW
)))) {
341 * Overlay the given record with its workspace-version, if any
343 * @param array $row The record to get the workspace version for
345 protected function makeWorkspaceOverlay(&$row)
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);
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
357 * The path is returned uncut, cutting has to be done by calling function.
359 * @param array $row The row
360 * @param array $record The record
361 * @return string The record-path
363 protected function getRecordPath(&$row, $uid)
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)) . '/';
372 $path = BackendUtility
::getRecordPath($row['pid'], '', $titleLimit);
378 * Returns a label for a given record; usually only a wrapper for \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordTitle
380 * @param array $row The record to get the label for
381 * @return string The label
383 protected function getLabel($row)
385 return BackendUtility
::getRecordTitle($this->mmForeignTable ?
$this->mmForeignTable
: $this->table
, $row, true);
389 * Calls a user function for rendering the page.
391 * This user function should manipulate $entry, especially $entry['text'].
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
397 protected function renderRecord($row, $entry)
399 // Call renderlet if available (normal pages etc. usually don't have one)
400 if ($this->config
['renderFunc'] != '') {
402 'table' => $this->table
,
403 'uid' => $row['uid'],
407 GeneralUtility
::callUserFunction($this->config
['renderFunc'], $params, $this);
413 * @return LanguageService
415 protected function getLanguageService()
417 return $GLOBALS['LANG'];
421 * @param string $table
422 * @return QueryBuilder
424 protected function getQueryBuilderForTable($table)
426 return GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable($table);