d2f8a568414ee8fcf6ac4e3786b6375634060f58
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Form / Element / SuggestElement.php
1 <?php
2 namespace TYPO3\CMS\Backend\Form\Element;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 2007-2013 Andreas Wolf <andreas.wolf@ikt-werk.de>
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the textfile GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
20 *
21 *
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
29
30 use TYPO3\CMS\Backend\Utility\BackendUtility;
31 use TYPO3\CMS\Core\Utility\GeneralUtility;
32
33 /**
34 * TCEforms wizard for rendering an AJAX selector for records
35 *
36 * @author Andreas Wolf <andreas.wolf@ikt-werk.de>
37 * @author Benjamin Mack <benni@typo3.org>
38 */
39 class SuggestElement {
40
41 // Count the number of ajax selectors used
42 public $suggestCount = 0;
43
44 public $cssClass = 'typo3-TCEforms-suggest';
45
46 /**
47 * @var \TYPO3\CMS\Backend\Form\FormEngine
48 */
49 public $TCEformsObj;
50
51 /**
52 * Initialize an instance of SuggestElement
53 *
54 * @param \TYPO3\CMS\Backend\Form\FormEngine $tceForms Reference to an TCEforms instance
55 * @return void
56 */
57 public function init(&$tceForms) {
58 $this->TCEformsObj = &$tceForms;
59 }
60
61 /**
62 * Renders an ajax-enabled text field. Also adds required JS
63 *
64 * @param string $fieldname The fieldname in the form
65 * @param string $table The table we render this selector for
66 * @param string $field The field we render this selector for
67 * @param array $row The row which is currently edited
68 * @param array $config The TSconfig of the field
69 * @return string The HTML code for the selector
70 */
71 public function renderSuggestSelector($fieldname, $table, $field, array $row, array $config) {
72 $this->suggestCount++;
73 $containerCssClass = $this->cssClass . ' ' . $this->cssClass . '-position-right';
74 $suggestId = 'suggest-' . $table . '-' . $field . '-' . $row['uid'];
75 if ($GLOBALS['TCA'][$table]['columns'][$field]['config']['type'] === 'flex') {
76 $fieldPattern = 'data[' . $table . '][' . $row['uid'] . '][';
77 $flexformField = str_replace($fieldPattern, '', $fieldname);
78 $flexformField = substr($flexformField, 0, -1);
79 $field = str_replace(array(']['), '|', $flexformField);
80 }
81 $selector = '
82 <div class="' . $containerCssClass . '" id="' . $suggestId . '">
83 <input type="text" id="' . $fieldname . 'Suggest" value="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.findRecord') . '" class="' . $this->cssClass . '-search" />
84 <div class="' . $this->cssClass . '-indicator" style="display: none;" id="' . $fieldname . 'SuggestIndicator">
85 <img src="' . $GLOBALS['BACK_PATH'] . 'gfx/spinner.gif" alt="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:alttext.suggestSearching') . '" />
86 </div>
87 <div class="' . $this->cssClass . '-choices" style="display: none;" id="' . $fieldname . 'SuggestChoices"></div>
88
89 </div>';
90 // Get minimumCharacters from TCA
91 if (isset($config['fieldConf']['config']['wizards']['suggest']['default']['minimumCharacters'])) {
92 $minChars = intval($config['fieldConf']['config']['wizards']['suggest']['default']['minimumCharacters']);
93 }
94 // Overwrite it with minimumCharacters from TSConfig (TCEFORM) if given
95 if (isset($config['fieldTSConfig']['suggest.']['default.']['minimumCharacters'])) {
96 $minChars = intval($config['fieldTSConfig']['suggest.']['default.']['minimumCharacters']);
97 }
98 $minChars = $minChars > 0 ? $minChars : 2;
99 // Replace "-" with ucwords for the JS object name
100 $jsObj = str_replace(' ', '', ucwords(str_replace('-', ' ', GeneralUtility::strtolower($suggestId))));
101 $this->TCEformsObj->additionalJS_post[] = '
102 var ' . $jsObj . ' = new TCEForms.Suggest("' . $fieldname . '", "' . $table . '", "' . $field . '", "' . $row['uid'] . '", ' . $row['pid'] . ', ' . $minChars . ');
103 ' . $jsObj . '.defaultValue = "' . GeneralUtility::slashJS($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.findRecord')) . '";
104 ';
105 return $selector;
106 }
107
108 /**
109 * Ajax handler for the "suggest" feature in TCEforms.
110 *
111 * @param array $params The parameters from the AJAX call
112 * @param \TYPO3\CMS\Core\Http\AjaxRequestHandler $ajaxObj The AJAX object representing the AJAX call
113 * @return void
114 */
115 public function processAjaxRequest($params, &$ajaxObj) {
116 // Get parameters from $_GET/$_POST
117 $search = GeneralUtility::_GP('value');
118 $table = GeneralUtility::_GP('table');
119 $field = GeneralUtility::_GP('field');
120 $uid = GeneralUtility::_GP('uid');
121 $pageId = GeneralUtility::_GP('pid');
122 // If the $uid is numeric, we have an already existing element, so get the
123 // TSconfig of the page itself or the element container (for non-page elements)
124 // otherwise it's a new element, so use given id of parent page (i.e., don't modify it here)
125 if (is_numeric($uid)) {
126 if ($table == 'pages') {
127 $pageId = $uid;
128 } else {
129 $row = BackendUtility::getRecord($table, $uid);
130 $pageId = $row['pid'];
131 }
132 }
133 $TSconfig = BackendUtility::getPagesTSconfig($pageId);
134 $queryTables = array();
135 $foreign_table_where = '';
136 $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
137 $parts = explode('|', $field);
138 if ($GLOBALS['TCA'][$table]['columns'][$parts[0]]['config']['type'] === 'flex') {
139 if (is_array($row) && count($row) > 0) {
140 $flexfieldTCAConfig = $GLOBALS['TCA'][$table]['columns'][$parts[0]]['config'];
141 $flexformDSArray = BackendUtility::getFlexFormDS($flexfieldTCAConfig, $row, $table);
142 $flexformDSArray = GeneralUtility::resolveAllSheetsInDS($flexformDSArray);
143 $flexformElement = $parts[count($parts) - 2];
144 $continue = TRUE;
145 foreach ($flexformDSArray as $sheet) {
146 foreach ($sheet as $_ => $dataStructure) {
147 if (isset($dataStructure['ROOT']['el'][$flexformElement]['TCEforms']['config'])) {
148 $fieldConfig = $dataStructure['ROOT']['el'][$flexformElement]['TCEforms']['config'];
149 $continue = FALSE;
150 break;
151 }
152 }
153 if (!$continue) {
154 break;
155 }
156 }
157 $field = str_replace('|', '][', $field);
158 }
159 }
160 $wizardConfig = $fieldConfig['wizards']['suggest'];
161 if (isset($fieldConfig['allowed'])) {
162 if ($fieldConfig['allowed'] === '*') {
163 foreach ($GLOBALS['TCA'] as $tableName => $tableConfig) {
164 // TODO: Refactor function to BackendUtility
165 if (empty($tableConfig['ctrl']['hideTable'])
166 && ($GLOBALS['BE_USER']->isAdmin()
167 || (empty($tableConfig['ctrl']['adminOnly'])
168 && (empty($tableConfig['ctrl']['rootLevel'])
169 || !empty($tableConfig['ctrl']['security']['ignoreRootLevelRestriction']))))
170 ) {
171 $queryTables[] = $tableName;
172 }
173 }
174 unset($tableName, $tableConfig);
175 } else {
176 $queryTables = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $fieldConfig['allowed']);
177 }
178 } elseif (isset($fieldConfig['foreign_table'])) {
179 $queryTables = array($fieldConfig['foreign_table']);
180 $foreign_table_where = $fieldConfig['foreign_table_where'];
181 // strip ORDER BY clause
182 $foreign_table_where = trim(preg_replace('/ORDER[[:space:]]+BY.*/i', '', $foreign_table_where));
183 }
184 $resultRows = array();
185 // fetch the records for each query table. A query table is a table from which records are allowed to
186 // be added to the TCEForm selector, originally fetched from the "allowed" config option in the TCA
187 foreach ($queryTables as $queryTable) {
188 // if the table does not exist, skip it
189 if (!is_array($GLOBALS['TCA'][$queryTable]) || !count($GLOBALS['TCA'][$queryTable])) {
190 continue;
191 }
192 $config = (array) $wizardConfig['default'];
193 if (is_array($wizardConfig[$queryTable])) {
194 $config = GeneralUtility::array_merge_recursive_overrule($config, $wizardConfig[$queryTable]);
195 }
196 // merge the configurations of different "levels" to get the working configuration for this table and
197 // field (i.e., go from the most general to the most special configuration)
198 if (is_array($TSconfig['TCEFORM.']['suggest.']['default.'])) {
199 $config = GeneralUtility::array_merge_recursive_overrule($config, $TSconfig['TCEFORM.']['suggest.']['default.']);
200 }
201 if (is_array($TSconfig['TCEFORM.']['suggest.'][$queryTable . '.'])) {
202 $config = GeneralUtility::array_merge_recursive_overrule($config, $TSconfig['TCEFORM.']['suggest.'][$queryTable . '.']);
203 }
204 // use $table instead of $queryTable here because we overlay a config
205 // for the input-field here, not for the queried table
206 if (is_array($TSconfig['TCEFORM.'][$table . '.'][$field . '.']['suggest.']['default.'])) {
207 $config = GeneralUtility::array_merge_recursive_overrule($config, $TSconfig['TCEFORM.'][$table . '.'][$field . '.']['suggest.']['default.']);
208 }
209 if (is_array($TSconfig['TCEFORM.'][$table . '.'][$field . '.']['suggest.'][$queryTable . '.'])) {
210 $config = GeneralUtility::array_merge_recursive_overrule($config, $TSconfig['TCEFORM.'][$table . '.'][$field . '.']['suggest.'][$queryTable . '.']);
211 }
212 //process addWhere
213 if (!isset($config['addWhere']) && $foreign_table_where) {
214 $config['addWhere'] = $foreign_table_where;
215 }
216 if (isset($config['addWhere'])) {
217 $config['addWhere'] = strtr(' ' . $config['addWhere'], array(
218 '###THIS_UID###' => intval($uid),
219 '###CURRENT_PID###' => intval($pageId)
220 ));
221 }
222 // instantiate the class that should fetch the records for this $queryTable
223 $receiverClassName = $config['receiverClass'];
224 if (!class_exists($receiverClassName)) {
225 $receiverClassName = 'TYPO3\\CMS\\Backend\\Form\\Element\\SuggestDefaultReceiver';
226 }
227 $receiverObj = GeneralUtility::makeInstance($receiverClassName, $queryTable, $config);
228 $params = array('value' => $search);
229 $rows = $receiverObj->queryTable($params);
230 if (empty($rows)) {
231 continue;
232 }
233 $resultRows = GeneralUtility::array_merge($resultRows, $rows);
234 unset($rows);
235 }
236 $listItems = array();
237 if (count($resultRows) > 0) {
238 // traverse all found records and sort them
239 $rowsSort = array();
240 foreach ($resultRows as $key => $row) {
241 $rowsSort[$key] = $row['text'];
242 }
243 asort($rowsSort);
244 $rowsSort = array_keys($rowsSort);
245 // Limit the number of items in the result list
246 $maxItems = $config['maxItemsInResultList'] ? $config['maxItemsInResultList'] : 10;
247 $maxItems = min(count($resultRows), $maxItems);
248 // put together the selector entry
249 for ($i = 0; $i < $maxItems; $i++) {
250 $row = $resultRows[$rowsSort[$i]];
251 $rowId = $row['table'] . '-' . $row['uid'] . '-' . $table . '-' . $uid . '-' . $field;
252 $listItems[] = '<li' . ($row['class'] != '' ? ' class="' . $row['class'] . '"' : '') . ' id="' . $rowId . '"' . ($row['style'] != '' ? ' style="' . $row['style'] . '"' : '') . '>' . $row['sprite'] . $row['text'] . '</li>';
253 }
254 }
255 if (count($listItems) > 0) {
256 $list = implode('', $listItems);
257 } else {
258 $list = '<li class="suggest-noresults"><i>' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.noRecordFound') . '</i></li>';
259 }
260 $list = '<ul class="' . $this->cssClass . '-resultlist">' . $list . '</ul>';
261 $ajaxObj->addContent(0, $list);
262 }
263
264 }
265
266
267 ?>