b18912e66d853db94d457967307b01cc2031f5bc
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Search / LiveSearch / LiveSearch.php
1 <?php
2 namespace TYPO3\CMS\Backend\Search\LiveSearch;
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\Imaging\Icon;
19 use TYPO3\CMS\Core\Imaging\IconFactory;
20 use TYPO3\CMS\Core\Type\Bitmask\Permission;
21 use TYPO3\CMS\Core\Utility\GeneralUtility;
22 use TYPO3\CMS\Core\Utility\MathUtility;
23
24 /**
25 * Class for handling backend live search.
26 */
27 class LiveSearch
28 {
29 /**
30 * @var string
31 */
32 const PAGE_JUMP_TABLE = 'pages';
33
34 /**
35 * @var int
36 */
37 const RECURSIVE_PAGE_LEVEL = 99;
38
39 /**
40 * @var int
41 */
42 const GROUP_TITLE_MAX_LENGTH = 15;
43
44 /**
45 * @var int
46 */
47 const RECORD_TITLE_MAX_LENGTH = 28;
48
49 /**
50 * @var string
51 */
52 private $queryString = '';
53
54 /**
55 * @var int
56 */
57 private $startCount = 0;
58
59 /**
60 * @var int
61 */
62 private $limitCount = 5;
63
64 /**
65 * @var string
66 */
67 protected $userPermissions = '';
68
69 /**
70 * @var \TYPO3\CMS\Backend\Search\LiveSearch\QueryParser
71 */
72 protected $queryParser = null;
73
74 /**
75 * Initialize access settings
76 */
77 public function __construct()
78 {
79 $this->userPermissions = $GLOBALS['BE_USER']->getPagePermsClause(1);
80 $this->queryParser = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Search\LiveSearch\QueryParser::class);
81 }
82
83 /**
84 * Find records from database based on the given $searchQuery.
85 *
86 * @param string $searchQuery
87 * @return array Result list of database search.
88 */
89 public function find($searchQuery)
90 {
91 $recordArray = array();
92 $pageList = array();
93 $mounts = $GLOBALS['BE_USER']->returnWebmounts();
94 foreach ($mounts as $pageId) {
95 $pageList[] = $this->getAvailablePageIds($pageId, self::RECURSIVE_PAGE_LEVEL);
96 }
97 $pageIdList = implode(',', array_unique(explode(',', implode(',', $pageList))));
98 unset($pageList);
99 $limit = $this->startCount . ',' . $this->limitCount;
100 if ($this->queryParser->isValidCommand($searchQuery)) {
101 $this->setQueryString($this->queryParser->getSearchQueryValue($searchQuery));
102 $tableName = $this->queryParser->getTableNameFromCommand($searchQuery);
103 if ($tableName) {
104 $recordArray[] = $this->findByTable($tableName, $pageIdList, $limit);
105 }
106 } else {
107 $this->setQueryString($searchQuery);
108 $recordArray = $this->findByGlobalTableList($pageIdList);
109 }
110 return $recordArray;
111 }
112
113 /**
114 * Retrieve the page record from given $id.
115 *
116 * @param int $id
117 * @return array
118 */
119 protected function findPageById($id)
120 {
121 $pageRecord = array();
122 $row = BackendUtility::getRecord(self::PAGE_JUMP_TABLE, $id);
123 if (is_array($row)) {
124 $pageRecord = $row;
125 }
126 return $pageRecord;
127 }
128
129 /**
130 * Find records from all registered TCA table & column values.
131 *
132 * @param string $pageIdList Comma separated list of page IDs
133 * @return array Records found in the database matching the searchQuery
134 */
135 protected function findByGlobalTableList($pageIdList)
136 {
137 $limit = $this->limitCount;
138 $getRecordArray = array();
139 foreach ($GLOBALS['TCA'] as $tableName => $value) {
140 // if no access for the table (read or write), skip this table
141 if (!$GLOBALS['BE_USER']->check('tables_select', $tableName) && !$GLOBALS['BE_USER']->check('tables_modify', $tableName)) {
142 continue;
143 }
144 $recordArray = $this->findByTable($tableName, $pageIdList, '0,' . $limit);
145 $recordCount = count($recordArray);
146 if ($recordCount) {
147 $limit = $limit - $recordCount;
148 $getRecordArray[] = $recordArray;
149 if ($limit <= 0) {
150 break;
151 }
152 }
153 }
154 return $getRecordArray;
155 }
156
157 /**
158 * Find records by given table name.
159 *
160 * @param string $tableName Database table name
161 * @param string $pageIdList Comma separated list of page IDs
162 * @param string $limit MySql Limit notation
163 * @return array Records found in the database matching the searchQuery
164 * @see getRecordArray()
165 * @see makeOrderByTable()
166 * @see makeQuerySearchByTable()
167 * @see extractSearchableFieldsFromTable()
168 */
169 protected function findByTable($tableName, $pageIdList, $limit)
170 {
171 $fieldsToSearchWithin = $this->extractSearchableFieldsFromTable($tableName);
172 $getRecordArray = array();
173 if (!empty($fieldsToSearchWithin)) {
174 $pageBasedPermission = $tableName == 'pages' && $this->userPermissions ? $this->userPermissions : '1=1 ';
175 $where = 'pid IN (' . $pageIdList . ') AND ' . $pageBasedPermission . $this->makeQuerySearchByTable($tableName, $fieldsToSearchWithin);
176 $getRecordArray = $this->getRecordArray($tableName, $where, $this->makeOrderByTable($tableName), $limit);
177 }
178 return $getRecordArray;
179 }
180
181 /**
182 * Process the Database operation to get the search result.
183 *
184 * @param string $tableName Database table name
185 * @param string $where
186 * @param string $orderBy
187 * @param string $limit MySql Limit notation
188 * @return array
189 * @see getTitleFromCurrentRow()
190 * @see getEditLink()
191 */
192 protected function getRecordArray($tableName, $where, $orderBy, $limit)
193 {
194 $collect = array();
195 $queryParts = array(
196 'SELECT' => '*',
197 'FROM' => $tableName,
198 'WHERE' => $where,
199 'ORDERBY' => $orderBy,
200 'LIMIT' => $limit
201 );
202 $result = $GLOBALS['TYPO3_DB']->exec_SELECT_queryArray($queryParts);
203 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
204 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
205 $title = 'id=' . $row['uid'] . ', pid=' . $row['pid'];
206 $collect[] = array(
207 'id' => $tableName . ':' . $row['uid'],
208 'pageId' => $tableName === 'pages' ? $row['uid'] : $row['pid'],
209 'typeLabel' => htmlspecialchars($this->getTitleOfCurrentRecordType($tableName)),
210 'iconHTML' => '<span title="' . htmlspecialchars($title) . '">' . $iconFactory->getIconForRecord($tableName, $row, Icon::SIZE_SMALL)->render() . '</span>',
211 'title' => htmlspecialchars(BackendUtility::getRecordTitle($tableName, $row)),
212 'editLink' => htmlspecialchars($this->getEditLink($tableName, $row))
213 );
214 }
215 $GLOBALS['TYPO3_DB']->sql_free_result($result);
216 return $collect;
217 }
218
219 /**
220 * Build a backend edit link based on given record.
221 *
222 * @param string $tableName Record table name
223 * @param array $row Current record row from database.
224 * @return string Link to open an edit window for record.
225 * @see \TYPO3\CMS\Backend\Utility\BackendUtility::readPageAccess()
226 */
227 protected function getEditLink($tableName, $row)
228 {
229 $pageInfo = BackendUtility::readPageAccess($row['pid'], $this->userPermissions);
230 $calcPerms = $GLOBALS['BE_USER']->calcPerms($pageInfo);
231 $editLink = '';
232 if ($tableName == 'pages') {
233 $localCalcPerms = $GLOBALS['BE_USER']->calcPerms(BackendUtility::getRecord('pages', $row['uid']));
234 $permsEdit = $localCalcPerms & Permission::PAGE_EDIT;
235 } else {
236 $permsEdit = $calcPerms & Permission::CONTENT_EDIT;
237 }
238 // "Edit" link - Only if permissions to edit the page-record of the content of the parent page ($this->id)
239 if ($permsEdit) {
240 $returnUrl = BackendUtility::getModuleUrl('web_list', array('id' => $row['pid']));
241 $editLink = BackendUtility::getModuleUrl('record_edit', array(
242 'edit[' . $tableName . '][' . $row['uid'] . ']' => 'edit',
243 'returnUrl' => $returnUrl
244 ));
245 }
246 return $editLink;
247 }
248
249 /**
250 * Retrieve the record name
251 *
252 * @param string $tableName Record table name
253 * @return string
254 */
255 protected function getTitleOfCurrentRecordType($tableName)
256 {
257 return $GLOBALS['LANG']->sL($GLOBALS['TCA'][$tableName]['ctrl']['title']);
258 }
259
260 /**
261 * Crops a title string to a limited length and if it really was cropped,
262 * wrap it in a <span title="...">|</span>,
263 * which offers a tooltip with the original title when moving mouse over it.
264 *
265 * @param string $title The title string to be cropped
266 * @param int $titleLength Crop title after this length - if not set, BE_USER->uc['titleLen'] is used
267 * @return string The processed title string, wrapped in <span title="...">|</span> if cropped
268 */
269 public function getRecordTitlePrep($title, $titleLength = 0)
270 {
271 // If $titleLength is not a valid positive integer, use BE_USER->uc['titleLen']:
272 if (!$titleLength || !MathUtility::canBeInterpretedAsInteger($titleLength) || $titleLength < 0) {
273 $titleLength = $GLOBALS['BE_USER']->uc['titleLen'];
274 }
275 return htmlspecialchars(GeneralUtility::fixed_lgd_cs($title, $titleLength));
276 }
277
278 /**
279 * Build the MySql where clause by table.
280 *
281 * @param string $tableName Record table name
282 * @param array $fieldsToSearchWithin User right based visible fields where we can search within.
283 * @return string
284 */
285 protected function makeQuerySearchByTable($tableName, array $fieldsToSearchWithin)
286 {
287 $queryPart = '';
288 $whereParts = array();
289 // If the search string is a simple integer, assemble an equality comparison
290 if (MathUtility::canBeInterpretedAsInteger($this->queryString)) {
291 foreach ($fieldsToSearchWithin as $fieldName) {
292 if ($fieldName == 'uid' || $fieldName == 'pid' || isset($GLOBALS['TCA'][$tableName]['columns'][$fieldName])) {
293 $fieldConfig = &$GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
294 // Assemble the search condition only if the field is an integer, or is uid or pid
295 if ($fieldName == 'uid' || $fieldName == 'pid' || $fieldConfig['type'] == 'input' && $fieldConfig['eval'] && GeneralUtility::inList($fieldConfig['eval'], 'int')) {
296 $whereParts[] = $fieldName . '=' . $this->queryString;
297 } elseif (
298 $fieldConfig['type'] == 'text' ||
299 $fieldConfig['type'] == 'flex' ||
300 ($fieldConfig['type'] == 'input' && (!$fieldConfig['eval'] ||
301 !preg_match('/date|time|int/', $fieldConfig['eval'])))) {
302 // Otherwise and if the field makes sense to be searched, assemble a like condition
303 $whereParts[] = $fieldName . ' LIKE \'%' . $this->queryString . '%\'';
304 }
305 }
306 }
307 } else {
308 $like = '\'%' . $GLOBALS['TYPO3_DB']->escapeStrForLike($GLOBALS['TYPO3_DB']->quoteStr($this->queryString, $tableName), $tableName) . '%\'';
309 foreach ($fieldsToSearchWithin as $fieldName) {
310 if (isset($GLOBALS['TCA'][$tableName]['columns'][$fieldName])) {
311 $fieldConfig = &$GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
312 // Check whether search should be case-sensitive or not
313 $format = 'LOWER(%s) LIKE LOWER(%s)';
314 if (is_array($fieldConfig['search'])) {
315 if (in_array('case', $fieldConfig['search'])) {
316 $format = '%s LIKE %s';
317 }
318 // Apply additional condition, if any
319 if ($fieldConfig['search']['andWhere']) {
320 $format = '((' . $fieldConfig['search']['andWhere'] . ') AND (' . $format . '))';
321 }
322 }
323 // Assemble the search condition only if the field makes sense to be searched
324 if ($fieldConfig['type'] == 'text' || $fieldConfig['type'] == 'flex' || $fieldConfig['type'] == 'input' && (!$fieldConfig['eval'] || !preg_match('/date|time|int/', $fieldConfig['eval']))) {
325 $whereParts[] = sprintf($format, $fieldName, $like);
326 }
327 }
328 }
329 }
330 // If at least one condition was defined, create the search query
331 if (!empty($whereParts)) {
332 $queryPart = ' AND (' . implode(' OR ', $whereParts) . ')';
333 // And the relevant conditions for deleted and versioned records
334 $queryPart .= BackendUtility::deleteClause($tableName);
335 $queryPart .= BackendUtility::versioningPlaceholderClause($tableName);
336 $queryPart .= BackendUtility::getWorkspaceWhereClause($tableName);
337 } else {
338 $queryPart = ' AND 0 = 1';
339 }
340 return $queryPart;
341 }
342
343 /**
344 * Build the MySql ORDER BY statement.
345 *
346 * @param string $tableName Record table name
347 * @return string
348 */
349 protected function makeOrderByTable($tableName)
350 {
351 $orderBy = '';
352 if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('sortby', $GLOBALS['TCA'][$tableName]['ctrl'])) {
353 $sortBy = trim($GLOBALS['TCA'][$tableName]['ctrl']['sortby']);
354 if (!empty($sortBy)) {
355 $orderBy = 'ORDER BY ' . $sortBy;
356 }
357 } else {
358 $orderBy = $GLOBALS['TCA'][$tableName]['ctrl']['default_sortby'];
359 }
360 return $GLOBALS['TYPO3_DB']->stripOrderBy($orderBy);
361 }
362
363 /**
364 * Get all fields from given table where we can search for.
365 *
366 * @param string $tableName Name of the table for which to get the searchable fields
367 * @return array
368 */
369 protected function extractSearchableFieldsFromTable($tableName)
370 {
371 // Get the list of fields to search in from the TCA, if any
372 if (isset($GLOBALS['TCA'][$tableName]['ctrl']['searchFields'])) {
373 $fieldListArray = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$tableName]['ctrl']['searchFields'], true);
374 } else {
375 $fieldListArray = array();
376 }
377 // Add special fields
378 if ($GLOBALS['BE_USER']->isAdmin()) {
379 $fieldListArray[] = 'uid';
380 $fieldListArray[] = 'pid';
381 }
382 return $fieldListArray;
383 }
384
385 /**
386 * Safely retrieve the queryString.
387 *
388 * @param string $tableName
389 * @return string
390 */
391 public function getQueryString($tableName = '')
392 {
393 return $GLOBALS['TYPO3_DB']->quoteStr($this->queryString, $tableName);
394 }
395
396 /**
397 * Setter for limit value.
398 *
399 * @param int $limitCount
400 * @return void
401 */
402 public function setLimitCount($limitCount)
403 {
404 $limit = MathUtility::convertToPositiveInteger($limitCount);
405 if ($limit > 0) {
406 $this->limitCount = $limit;
407 }
408 }
409
410 /**
411 * Setter for start count value.
412 *
413 * @param int $startCount
414 * @return void
415 */
416 public function setStartCount($startCount)
417 {
418 $this->startCount = MathUtility::convertToPositiveInteger($startCount);
419 }
420
421 /**
422 * Setter for the search query string.
423 *
424 * @param string $queryString
425 * @return void
426 */
427 public function setQueryString($queryString)
428 {
429 $this->queryString = $queryString;
430 }
431
432 /**
433 * Creates an instance of \TYPO3\CMS\Backend\Tree\View\PageTreeView which will select a
434 * page tree to $depth and return the object. In that object we will find the ids of the tree.
435 *
436 * @param int $id Page id.
437 * @param int $depth Depth to go down.
438 * @return string Comma separated list of uids
439 */
440 protected function getAvailablePageIds($id, $depth)
441 {
442 $tree = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Tree\View\PageTreeView::class);
443 $tree->init('AND ' . $this->userPermissions);
444 $tree->makeHTML = 0;
445 $tree->fieldArray = array('uid', 'php_tree_stop');
446 if ($depth) {
447 $tree->getTree($id, $depth, '');
448 }
449 $tree->ids[] = $id;
450 // add workspace pid - workspace permissions are taken into account by where clause later
451 $tree->ids[] = -1;
452 $idList = implode(',', $tree->ids);
453 return $idList;
454 }
455 }