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