69883052fdc82851551ae04025ee5337235013a8
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Form / Element / SuggestDefaultReceiver.php
1 <?php
2 namespace TYPO3\CMS\Backend\Form\Element;
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 SuggestDefaultReceiver {
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 * @return void
102 */
103 public function __construct($table, $config) {
104 $this->table = $table;
105 $this->config = $config;
106 // get a list of all the pages that should be looked on
107 if (isset($config['pidList'])) {
108 $allowedPages = ($pageIds = GeneralUtility::trimExplode(',', $config['pidList']));
109 $depth = (int)$config['pidDepth'];
110 foreach ($pageIds as $pageId) {
111 if ($pageId > 0) {
112 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($allowedPages, $this->getAllSubpagesOfPage($pageId, $depth));
113 }
114 }
115 $this->allowedPages = array_unique($allowedPages);
116 }
117 if (isset($config['maxItemsInResultList'])) {
118 $this->maxItems = $config['maxItemsInResultList'];
119 }
120 if ($this->table == 'pages') {
121 $this->addWhere = ' AND ' . $GLOBALS['BE_USER']->getPagePermsClause(1);
122 }
123 // if table is versionized, only get the records from the Live Workspace
124 // the overlay itself of WS-records is done below
125 if ($GLOBALS['TCA'][$this->table]['ctrl']['versioningWS'] == TRUE) {
126 $this->addWhere .= ' AND t3ver_wsid = 0';
127 }
128 if (isset($config['addWhere'])) {
129 $this->addWhere .= ' ' . $config['addWhere'];
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 $ref The parent object
143 * @return array Array of rows or FALSE if nothing found
144 */
145 public function queryTable(&$params, $recursionCounter = 0) {
146 $rows = array();
147 $this->params = &$params;
148 $start = $recursionCounter * 50;
149 $this->prepareSelectStatement();
150 $this->prepareOrderByStatement();
151 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->table, $this->selectClause, '', $this->orderByStatement, $start . ', 50');
152 $allRowsCount = $GLOBALS['TYPO3_DB']->sql_num_rows($res);
153 if ($allRowsCount) {
154 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
155 // check if we already have collected the maximum number of records
156 if (count($rows) > $this->maxItems) {
157 break;
158 }
159 $this->manipulateRecord($row);
160 $this->makeWorkspaceOverlay($row);
161 // check if the user has access to the record
162 if (!$this->checkRecordAccess($row, $row['uid'])) {
163 continue;
164 }
165 $spriteIcon = IconUtility::getSpriteIconForRecord(
166 $this->table, $row, array('style' => 'margin: 0 4px 0 -20px; padding: 0;')
167 );
168 $uid = $row['t3ver_oid'] > 0 ? $row['t3ver_oid'] : $row['uid'];
169 $path = $this->getRecordPath($row, $uid);
170 if (strlen($path) > 30) {
171 $languageService = $this->getLanguageService();
172 $croppedPath = '<abbr title="' . htmlspecialchars($path) . '">' .
173 htmlspecialchars(
174 $languageService->csConvObj->crop($languageService->charSet, $path, 10)
175 . '...'
176 . $languageService->csConvObj->crop($languageService->charSet, $path, -20)
177 ) .
178 '</abbr>';
179 } else {
180 $croppedPath = htmlspecialchars($path);
181 }
182 $label = $this->getLabel($row);
183 $entry = array(
184 'text' => '<span class="suggest-label">' . $label . '</span><span class="suggest-uid">[' . $uid . ']</span><br />
185 <span class="suggest-path">' . $croppedPath . '</span>',
186 'table' => $this->mmForeignTable ? $this->mmForeignTable : $this->table,
187 'label' => $label,
188 'path' => $path,
189 'uid' => $uid,
190 'style' => '',
191 'class' => isset($this->config['cssClass']) ? $this->config['cssClass'] : '',
192 'sprite' => $spriteIcon
193 );
194 $rows[$this->table . '_' . $uid] = $this->renderRecord($row, $entry);
195 }
196 $GLOBALS['TYPO3_DB']->sql_free_result($res);
197 // if there are less records than we need, call this function again to get more records
198 if (count($rows) < $this->maxItems && $allRowsCount >= 50 && $recursionCounter < $this->maxItems) {
199 $tmp = self::queryTable($params, ++$recursionCounter);
200 $rows = array_merge($tmp, $rows);
201 }
202 }
203 return $rows;
204 }
205
206 /**
207 * Prepare the statement for selecting the records which will be returned to the selector. May also return some
208 * other records (e.g. from a mm-table) which will be used later on to select the real records
209 *
210 * @return void
211 */
212 protected function prepareSelectStatement() {
213 $searchWholePhrase = $this->config['searchWholePhrase'];
214 $searchString = $this->params['value'];
215 $searchUid = (int)$searchString;
216 if (strlen($searchString)) {
217 $searchString = $GLOBALS['TYPO3_DB']->quoteStr($searchString, $this->table);
218 $likeCondition = ' LIKE \'' . ($searchWholePhrase ? '%' : '') . $GLOBALS['TYPO3_DB']->escapeStrForLike($searchString, $this->table) . '%\'';
219 // Search in all fields given by label or label_alt
220 $selectFieldsList = $GLOBALS['TCA'][$this->table]['ctrl']['label'] . ',' . $GLOBALS['TCA'][$this->table]['ctrl']['label_alt'] . ',' . $this->config['additionalSearchFields'];
221 $selectFields = GeneralUtility::trimExplode(',', $selectFieldsList, TRUE);
222 $selectFields = array_unique($selectFields);
223 $selectParts = array();
224 foreach ($selectFields as $field) {
225 $selectParts[] = $field . $likeCondition;
226 }
227 $this->selectClause = '(' . implode(' OR ', $selectParts) . ')';
228 if ($searchUid > 0 && $searchUid == $searchString) {
229 $this->selectClause = '(' . $this->selectClause . ' OR uid = ' . $searchUid . ')';
230 }
231 }
232 if (isset($GLOBALS['TCA'][$this->table]['ctrl']['delete'])) {
233 $this->selectClause .= ' AND ' . $GLOBALS['TCA'][$this->table]['ctrl']['delete'] . ' = 0';
234 }
235 if (count($this->allowedPages)) {
236 $pidList = $GLOBALS['TYPO3_DB']->cleanIntArray($this->allowedPages);
237 if (count($pidList)) {
238 $this->selectClause .= ' AND pid IN (' . implode(', ', $pidList) . ') ';
239 }
240 }
241 // add an additional search condition comment
242 if (isset($this->config['searchCondition']) && strlen($this->config['searchCondition']) > 0) {
243 $this->selectClause .= ' AND ' . $this->config['searchCondition'];
244 }
245 // add the global clauses to the where-statement
246 $this->selectClause .= $this->addWhere;
247 }
248
249 /**
250 * Selects all subpages of one page, optionally only up to a certain level
251 *
252 * @param int $uid The uid of the page
253 * @param int $depth The depth to select up to. Defaults to 99
254 * @return array of page IDs
255 */
256 protected function getAllSubpagesOfPage($uid, $depth = 99) {
257 $pageIds = array($uid);
258 $level = 0;
259 $pages = array($uid);
260 // fetch all
261 while ($depth - $level > 0 && !empty($pageIds)) {
262 ++$level;
263 $pidList = $GLOBALS['TYPO3_DB']->cleanIntArray($pageIds);
264 $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid', 'pages', 'pid IN (' . implode(', ', $pidList) . ')', '', '', '', 'uid');
265 if (count($rows) > 0) {
266 $pageIds = array_keys($rows);
267 $pages = array_merge($pages, $pageIds);
268 } else {
269 break;
270 }
271 }
272 return $pages;
273 }
274
275 /**
276 * Prepares the clause by which the result elements are sorted. See description of ORDER BY in
277 * SQL standard for reference.
278 *
279 * @return void
280 */
281 protected function prepareOrderByStatement() {
282 if ($GLOBALS['TCA'][$this->table]['ctrl']['label']) {
283 $this->orderByStatement = $GLOBALS['TCA'][$this->table]['ctrl']['label'];
284 }
285 }
286
287 /**
288 * Manipulate a record before using it to render the selector; may be used to replace a MM-relation etc.
289 *
290 * @param array $row
291 */
292 protected function manipulateRecord(&$row) {
293
294 }
295
296 /**
297 * Selects whether the logged in Backend User is allowed to read a specific record
298 *
299 * @param array $row
300 * @param int $uid
301 * @return bool
302 */
303 protected function checkRecordAccess($row, $uid) {
304 $retValue = TRUE;
305 $table = $this->mmForeignTable ?: $this->table;
306 if ($table == 'pages') {
307 if (!BackendUtility::readPageAccess($uid, $GLOBALS['BE_USER']->getPagePermsClause(1))) {
308 $retValue = FALSE;
309 }
310 } elseif (isset($GLOBALS['TCA'][$table]['ctrl']['is_static']) && (bool)$GLOBALS['TCA'][$table]['ctrl']['is_static']) {
311 $retValue = TRUE;
312 } else {
313 if (!is_array(BackendUtility::readPageAccess($row['pid'], $GLOBALS['BE_USER']->getPagePermsClause(1)))) {
314 $retValue = FALSE;
315 }
316 }
317 return $retValue;
318 }
319
320 /**
321 * Overlay the given record with its workspace-version, if any
322 *
323 * @param array The record to get the workspace version for
324 * @return void (passed by reference)
325 */
326 protected function makeWorkspaceOverlay(&$row) {
327 // Check for workspace-versions
328 if ($GLOBALS['BE_USER']->workspace != 0 && $GLOBALS['TCA'][$this->table]['ctrl']['versioningWS'] == TRUE) {
329 BackendUtility::workspaceOL($this->mmForeignTable ? $this->mmForeignTable : $this->table, $row);
330 }
331 }
332
333 /**
334 * Return the icon for a record - just a wrapper for two functions from \TYPO3\CMS\Backend\Utility\IconUtility
335 *
336 * @param array $row The record to get the icon for
337 * @return string The path to the icon
338 */
339 protected function getIcon($row) {
340 $icon = IconUtility::getIcon($this->mmForeignTable ? $this->mmForeignTable : $this->table, $row);
341 return IconUtility::skinImg('', $icon, '', 1);
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 }