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