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