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