9ea5e0f5f07e850f9405255895ff4cdce91d834d
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Form / Wizard / SuggestWizard.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\Utility\GeneralUtility;
19 use TYPO3\CMS\Core\Utility\MathUtility;
20 use TYPO3\CMS\Lang\LanguageService;
21 use TYPO3\CMS\Backend\Form\Wizard\SuggestWizardDefaultReceiver;
22
23 /**
24 * Wizard for rendering an AJAX selector for records
25 *
26 * @author Andreas Wolf <andreas.wolf@ikt-werk.de>
27 * @author Benjamin Mack <benni@typo3.org>
28 */
29 class SuggestWizard {
30
31 /**
32 * @var string
33 */
34 protected $cssClass = 'typo3-TCEforms-suggest';
35
36 /**
37 * Renders an ajax-enabled text field. Also adds required JS
38 *
39 * @param string $fieldname The fieldname in the form
40 * @param string $table The table we render this selector for
41 * @param string $field The field we render this selector for
42 * @param array $row The row which is currently edited
43 * @param array $config The TSconfig of the field
44 * @return string The HTML code for the selector
45 */
46 public function renderSuggestSelector($fieldname, $table, $field, array $row, array $config) {
47 $languageService = $this->getLanguageService();
48 $containerCssClass = $this->cssClass . ' ' . $this->cssClass . '-position-right';
49 $suggestId = 'suggest-' . $table . '-' . $field . '-' . $row['uid'];
50 $isFlexFormField = $GLOBALS['TCA'][$table]['columns'][$field]['config']['type'] === 'flex';
51 if ($isFlexFormField) {
52 $fieldPattern = 'data[' . $table . '][' . $row['uid'] . '][';
53 $flexformField = str_replace($fieldPattern, '', $fieldname);
54 $flexformField = substr($flexformField, 0, -1);
55 $field = str_replace(array(']['), '|', $flexformField);
56 }
57 $selector = '
58 <div class="' . $containerCssClass . '" id="' . $suggestId . '">
59 <div class="input-group">
60 <span class="input-group-addon"><i class="fa fa-search"></i></span>
61 <input type="search" id="' . $fieldname . 'Suggest" value="' . $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.findRecord') . '" class="form-control ' . $this->cssClass . '-search" />
62 <div class="' . $this->cssClass . '-indicator" style="display: none;" id="' . $fieldname . 'SuggestIndicator">
63 <img src="' . $GLOBALS['BACK_PATH'] . 'gfx/spinner.gif" alt="' . $languageService->sL('LLL:EXT:lang/locallang_core.xlf:alttext.suggestSearching') . '" />
64 </div>
65 <div class="' . $this->cssClass . '-choices" style="display: none;" id="' . $fieldname . 'SuggestChoices"></div>
66 </div>
67
68 </div>';
69 // Get minimumCharacters from TCA
70 $minChars = 0;
71 if (isset($config['fieldConf']['config']['wizards']['suggest']['default']['minimumCharacters'])) {
72 $minChars = (int)$config['fieldConf']['config']['wizards']['suggest']['default']['minimumCharacters'];
73 }
74 // Overwrite it with minimumCharacters from TSConfig (TCEFORM) if given
75 if (isset($config['fieldTSConfig']['suggest.']['default.']['minimumCharacters'])) {
76 $minChars = (int)$config['fieldTSConfig']['suggest.']['default.']['minimumCharacters'];
77 }
78 $minChars = $minChars > 0 ? $minChars : 2;
79
80 // fetch the TCA field type to hand it over to the JS class
81 $type = '';
82 if (isset($config['fieldConf']['config']['type'])) {
83 $type = $config['fieldConf']['config']['type'];
84 }
85
86 $jsRow = '';
87 if ($isFlexFormField && !MathUtility::canBeInterpretedAsInteger($row['uid'])) {
88 // Ff we have a new record, we hand that row over to JS.
89 // This way we can properly retrieve the configuration of our wizard
90 // if it is shown in a flexform
91 $jsRow = serialize($row);
92 }
93
94 // Replace "-" with ucwords for the JS object name
95 $jsObj = str_replace(' ', '', ucwords(str_replace(array('-', '.'), ' ', GeneralUtility::strtolower($suggestId))));
96 $selector .=
97 '<script type="text/javascript">' . LF .
98 'var ' . $jsObj . ' = new TCEForms.Suggest("' . $fieldname . '", "' . $table . '", "' . $field . '", "' . $row['uid'] . '", ' . $row['pid'] . ', ' . $minChars . ', "' . $type . '", ' . GeneralUtility::quoteJSvalue($jsRow) . ');' . LF .
99 $jsObj . '.defaultValue = "' . GeneralUtility::slashJS($languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.findRecord')) . '";' . LF .
100 '</script>' . LF;
101
102 return $selector;
103 }
104
105 /**
106 * Search a data structure array recursively -- including within nested
107 * (repeating) elements -- for a particular field config.
108 *
109 * @param array $dataStructure The data structure
110 * @param string $fieldName The field name
111 * @return array
112 */
113 protected function getNestedDsFieldConfig(array $dataStructure, $fieldName) {
114 $fieldConfig = array();
115 $elements = $dataStructure['ROOT']['el'] ? $dataStructure['ROOT']['el'] : $dataStructure['el'];
116 if (is_array($elements)) {
117 foreach ($elements as $k => $ds) {
118 if ($k === $fieldName) {
119 $fieldConfig = $ds['TCEforms']['config'];
120 break;
121 } elseif (isset($ds['el'][$fieldName]['TCEforms']['config'])) {
122 $fieldConfig = $ds['el'][$fieldName]['TCEforms']['config'];
123 break;
124 } else {
125 $fieldConfig = $this->getNestedDsFieldConfig($ds, $fieldName);
126 }
127 }
128 }
129 return $fieldConfig;
130 }
131
132 /**
133 * Ajax handler for the "suggest" feature in TCEforms.
134 *
135 * @param array $params The parameters from the AJAX call
136 * @param \TYPO3\CMS\Core\Http\AjaxRequestHandler $ajaxObj The AJAX object representing the AJAX call
137 * @return void
138 */
139 public function processAjaxRequest($params, &$ajaxObj) {
140 // Get parameters from $_GET/$_POST
141 $search = GeneralUtility::_GP('value');
142 $table = GeneralUtility::_GP('table');
143 $field = GeneralUtility::_GP('field');
144 $uid = GeneralUtility::_GP('uid');
145 $pageId = GeneralUtility::_GP('pid');
146 $newRecordRow = GeneralUtility::_GP('newRecordRow');
147 // If the $uid is numeric, we have an already existing element, so get the
148 // TSconfig of the page itself or the element container (for non-page elements)
149 // otherwise it's a new element, so use given id of parent page (i.e., don't modify it here)
150 $row = NULL;
151 if (is_numeric($uid)) {
152 $row = BackendUtility::getRecord($table, $uid);
153 if ($table == 'pages') {
154 $pageId = $uid;
155 } else {
156 $pageId = $row['pid'];
157 }
158 } else {
159 $row = unserialize($newRecordRow);
160 }
161 $TSconfig = BackendUtility::getPagesTSconfig($pageId);
162 $queryTables = array();
163 $foreign_table_where = '';
164 $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
165 $parts = explode('|', $field);
166 if ($GLOBALS['TCA'][$table]['columns'][$parts[0]]['config']['type'] === 'flex') {
167 $flexfieldTCAConfig = $GLOBALS['TCA'][$table]['columns'][$parts[0]]['config'];
168 $flexformDSArray = BackendUtility::getFlexFormDS($flexfieldTCAConfig, $row, $table, $parts[0]);
169 $flexformDSArray = GeneralUtility::resolveAllSheetsInDS($flexformDSArray);
170 $flexformElement = $parts[count($parts) - 2];
171 $continue = TRUE;
172 foreach ($flexformDSArray as $sheet) {
173 foreach ($sheet as $dataStructure) {
174 $fieldConfig = $this->getNestedDsFieldConfig($dataStructure, $flexformElement);
175 if (count($fieldConfig) > 0) {
176 $continue = FALSE;
177 break;
178 }
179 }
180 if (!$continue) {
181 break;
182 }
183 }
184 $field = str_replace('|', '][', $field);
185 }
186 $wizardConfig = $fieldConfig['wizards']['suggest'];
187 if (isset($fieldConfig['allowed'])) {
188 if ($fieldConfig['allowed'] === '*') {
189 foreach ($GLOBALS['TCA'] as $tableName => $tableConfig) {
190 // @todo Refactor function to BackendUtility
191 if (empty($tableConfig['ctrl']['hideTable'])
192 && ($GLOBALS['BE_USER']->isAdmin()
193 || (empty($tableConfig['ctrl']['adminOnly'])
194 && (empty($tableConfig['ctrl']['rootLevel'])
195 || !empty($tableConfig['ctrl']['security']['ignoreRootLevelRestriction']))))
196 ) {
197 $queryTables[] = $tableName;
198 }
199 }
200 unset($tableName, $tableConfig);
201 } else {
202 $queryTables = GeneralUtility::trimExplode(',', $fieldConfig['allowed']);
203 }
204 } elseif (isset($fieldConfig['foreign_table'])) {
205 $queryTables = array($fieldConfig['foreign_table']);
206 $foreign_table_where = $fieldConfig['foreign_table_where'];
207 // strip ORDER BY clause
208 $foreign_table_where = trim(preg_replace('/ORDER[[:space:]]+BY.*/i', '', $foreign_table_where));
209 }
210 $resultRows = array();
211 // fetch the records for each query table. A query table is a table from which records are allowed to
212 // be added to the TCEForm selector, originally fetched from the "allowed" config option in the TCA
213 foreach ($queryTables as $queryTable) {
214 // if the table does not exist, skip it
215 if (!is_array($GLOBALS['TCA'][$queryTable]) || !count($GLOBALS['TCA'][$queryTable])) {
216 continue;
217 }
218 $config = (array)$wizardConfig['default'];
219 if (is_array($wizardConfig[$queryTable])) {
220 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($config, $wizardConfig[$queryTable]);
221 }
222 // merge the configurations of different "levels" to get the working configuration for this table and
223 // field (i.e., go from the most general to the most special configuration)
224 if (is_array($TSconfig['TCEFORM.']['suggest.']['default.'])) {
225 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($config, $TSconfig['TCEFORM.']['suggest.']['default.']);
226 }
227 if (is_array($TSconfig['TCEFORM.']['suggest.'][$queryTable . '.'])) {
228 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($config, $TSconfig['TCEFORM.']['suggest.'][$queryTable . '.']);
229 }
230 // use $table instead of $queryTable here because we overlay a config
231 // for the input-field here, not for the queried table
232 if (is_array($TSconfig['TCEFORM.'][$table . '.'][$field . '.']['suggest.']['default.'])) {
233 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($config, $TSconfig['TCEFORM.'][$table . '.'][$field . '.']['suggest.']['default.']);
234 }
235 if (is_array($TSconfig['TCEFORM.'][$table . '.'][$field . '.']['suggest.'][$queryTable . '.'])) {
236 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($config, $TSconfig['TCEFORM.'][$table . '.'][$field . '.']['suggest.'][$queryTable . '.']);
237 }
238 //process addWhere
239 if (!isset($config['addWhere']) && $foreign_table_where) {
240 $config['addWhere'] = $foreign_table_where;
241 }
242 if (isset($config['addWhere'])) {
243 $replacement = array(
244 '###THIS_UID###' => (int)$uid,
245 '###CURRENT_PID###' => (int)$pageId
246 );
247 if (isset($TSconfig['TCEFORM.'][$table . '.'][$field . '.'])) {
248 $fieldTSconfig = $TSconfig['TCEFORM.'][$table . '.'][$field . '.'];
249 if (isset($fieldTSconfig['PAGE_TSCONFIG_ID'])) {
250 $replacement['###PAGE_TSCONFIG_ID###'] = (int)$fieldTSconfig['PAGE_TSCONFIG_ID'];
251 }
252 if (isset($fieldTSconfig['PAGE_TSCONFIG_IDLIST'])) {
253 $replacement['###PAGE_TSCONFIG_IDLIST###'] = $GLOBALS['TYPO3_DB']->cleanIntList($fieldTSconfig['PAGE_TSCONFIG_IDLIST']);
254 }
255 if (isset($fieldTSconfig['PAGE_TSCONFIG_STR'])) {
256 $replacement['###PAGE_TSCONFIG_STR###'] = $GLOBALS['TYPO3_DB']->quoteStr($fieldTSconfig['PAGE_TSCONFIG_STR'], $fieldConfig['foreign_table']);
257 }
258 }
259 $config['addWhere'] = strtr(' ' . $config['addWhere'], $replacement);
260 }
261 // instantiate the class that should fetch the records for this $queryTable
262 $receiverClassName = $config['receiverClass'];
263 if (!class_exists($receiverClassName)) {
264 $receiverClassName = SuggestWizardDefaultReceiver::class;
265 }
266 $receiverObj = GeneralUtility::makeInstance($receiverClassName, $queryTable, $config);
267 $params = array('value' => $search);
268 $rows = $receiverObj->queryTable($params);
269 if (empty($rows)) {
270 continue;
271 }
272 $resultRows = $rows + $resultRows;
273 unset($rows);
274 }
275 $listItems = array();
276 if (count($resultRows) > 0) {
277 // traverse all found records and sort them
278 $rowsSort = array();
279 foreach ($resultRows as $key => $row) {
280 $rowsSort[$key] = $row['text'];
281 }
282 asort($rowsSort);
283 $rowsSort = array_keys($rowsSort);
284 // Limit the number of items in the result list
285 $maxItems = $config['maxItemsInResultList'] ?: 10;
286 $maxItems = min(count($resultRows), $maxItems);
287 // put together the selector entry
288 for ($i = 0; $i < $maxItems; $i++) {
289 $row = $resultRows[$rowsSort[$i]];
290 $rowId = $row['table'] . '-' . $row['uid'] . '-' . $table . '-' . $uid . '-' . $field;
291 $listItems[] = '<li' . ($row['class'] != '' ? ' class="' . $row['class'] . '"' : '') . ' id="' . $rowId . '"' . ($row['style'] != '' ? ' style="' . $row['style'] . '"' : '') . '>' . $row['sprite'] . $row['text'] . '</li>';
292 }
293 }
294 if (count($listItems) > 0) {
295 $list = implode('', $listItems);
296 } else {
297 $list = '<li class="suggest-noresults"><i>' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.noRecordFound') . '</i></li>';
298 }
299 $list = '<ul class="' . $this->cssClass . '-resultlist">' . $list . '</ul>';
300 $ajaxObj->addContent(0, $list);
301 }
302
303 /**
304 * @return LanguageService
305 */
306 protected function getLanguageService() {
307 return $GLOBALS['LANG'];
308 }
309
310 }