Merge pull request #21578 from civicrm/5.42
[civicrm-core.git] / CRM / Core / Form / Renderer.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 require_once 'HTML/QuickForm/Renderer/ArraySmarty.php';
19
20 /**
21 * Customize QF output to meet our specific requirements
22 */
23 class CRM_Core_Form_Renderer extends HTML_QuickForm_Renderer_ArraySmarty {
24
25 /**
26 * We only need one instance of this object. So we use the singleton
27 * pattern and cache the instance in this variable
28 *
29 * @var object
30 */
31 static private $_singleton = NULL;
32
33 /**
34 * The converter from array size to css class.
35 *
36 * @var array
37 */
38 public static $_sizeMapper = [
39 2 => 'two',
40 4 => 'four',
41 6 => 'six',
42 8 => 'eight',
43 12 => 'twelve',
44 20 => 'medium',
45 30 => 'big',
46 45 => 'huge',
47 ];
48
49 /**
50 * Constructor.
51 */
52 public function __construct() {
53 $template = CRM_Core_Smarty::singleton();
54 parent::__construct($template);
55 }
56
57 /**
58 * Static instance provider.
59 *
60 * Method providing static instance of as in Singleton pattern.
61 */
62 public static function &singleton() {
63 if (!isset(self::$_singleton)) {
64 self::$_singleton = new CRM_Core_Form_Renderer();
65 }
66 return self::$_singleton;
67 }
68
69 /**
70 * Creates an array representing an element containing.
71 * the key for storing this. We allow the parent to do most of the
72 * work, but then we add some CiviCRM specific enhancements to
73 * make the html compliant with our css etc
74 *
75 *
76 * @param HTML_QuickForm_element $element
77 * @param bool $required
78 * Whether an element is required.
79 * @param string $error
80 * Error associated with the element.
81 *
82 * @return array
83 */
84 public function _elementToArray(&$element, $required, $error) {
85 self::updateAttributes($element, $required, $error);
86
87 $el = parent::_elementToArray($element, $required, $error);
88
89 // add label html
90 if (!empty($el['label'])) {
91 $id = $element->getAttribute('id');
92 if (!empty($id)) {
93 $el['label'] = '<label for="' . $id . '">' . $el['label'] . '</label>';
94 }
95 else {
96 $el['label'] = "<label>{$el['label']}</label>";
97 }
98 }
99
100 // Display-only (frozen) elements
101 if (!empty($el['frozen'])) {
102 if ($element->getAttribute('data-api-entity') && $element->getAttribute('data-entity-value')) {
103 $this->renderFrozenEntityRef($el, $element);
104 }
105 elseif ($element->getAttribute('type') == 'text' && $element->getAttribute('data-select-params')) {
106 $this->renderFrozenSelect2($el, $element);
107 }
108 elseif ($element->getAttribute('type') == 'text' && $element->getAttribute('data-crm-datepicker')) {
109 $this->renderFrozenDatepicker($el, $element);
110 }
111 elseif ($element->getAttribute('type') == 'text' && $element->getAttribute('formatType')) {
112 list($date, $time) = CRM_Utils_Date::setDateDefaults($element->getValue(), $element->getAttribute('formatType'), $element->getAttribute('format'), $element->getAttribute('timeformat'));
113 $date .= ($element->getAttribute('timeformat')) ? " $time" : '';
114 $el['html'] = $date . '<input type="hidden" value="' . $element->getValue() . '" name="' . $element->getAttribute('name') . '">';
115 }
116 // Render html for wysiwyg textareas
117 if ($el['type'] == 'textarea' && isset($element->_attributes['class']) && strstr($element->_attributes['class'], 'wysiwyg')) {
118 $el['html'] = '<span class="crm-frozen-field">' . $el['value'] . '</span>';
119 }
120 else {
121 $el['html'] = '<span class="crm-frozen-field">' . $el['html'] . '</span>';
122 }
123 }
124 // Active form elements
125 else {
126 $typesToShowEditLink = ['select', 'group'];
127 $hasEditPath = NULL !== $element->getAttribute('data-option-edit-path');
128
129 if (in_array($element->getType(), $typesToShowEditLink) && $hasEditPath) {
130 $this->addOptionsEditLink($el, $element);
131 }
132
133 if ($element->getAttribute('allowClear')) {
134 $this->appendUnselectButton($el, $element);
135 }
136 }
137
138 return $el;
139 }
140
141 /**
142 * Update the attributes of this element and add a few CiviCRM
143 * based attributes so we can style this form element better
144 *
145 *
146 * @param HTML_QuickForm_element $element
147 * @param bool $required
148 * Whether an element is required.
149 * @param string $error
150 * Error associated with the element.
151 *
152 */
153 public static function updateAttributes(&$element, $required, $error) {
154 // lets create an id for all input elements, so we can generate nice label tags
155 // to make it nice and clean, we'll just use the elementName if it is non null
156 $attributes = [];
157 if (!$element->getAttribute('id')) {
158 $name = $element->getAttribute('name');
159 if ($name) {
160 $attributes['id'] = str_replace([']', '['],
161 ['', '_'],
162 $name
163 );
164 }
165 }
166
167 $class = $element->getAttribute('class');
168 $type = $element->getType();
169 if (!$class) {
170 if ($type == 'text' || $type == 'password') {
171 $size = $element->getAttribute('size');
172 if (!empty($size)) {
173 $class = self::$_sizeMapper[$size] ?? NULL;
174 }
175 }
176 }
177
178 if ($type == 'select' && $element->getAttribute('multiple')) {
179 $type = 'multiselect';
180 }
181 // Add widget-specific class
182 if (!$class || strpos($class, 'crm-form-') === FALSE) {
183 $class = ($class ? "$class " : '') . 'crm-form-' . $type;
184 }
185 elseif (strpos($class, 'crm-form-entityref') !== FALSE) {
186 self::preProcessEntityRef($element);
187 }
188 elseif (strpos($class, 'crm-form-contact-reference') !== FALSE) {
189 self::preprocessContactReference($element);
190 }
191 // Hack to support html5 fields (number, url, etc)
192 else {
193 foreach (CRM_Core_Form::$html5Types as $type) {
194 if (strpos($class, "crm-form-$type") !== FALSE) {
195 $element->setAttribute('type', $type);
196 // Also add the "base" class for consistent styling
197 $class .= ' crm-form-text';
198 break;
199 }
200 }
201 }
202
203 if ($required) {
204 $class .= ' required';
205 }
206
207 if ($error) {
208 $class .= ' error';
209 }
210
211 $attributes['class'] = $class;
212 $element->updateAttributes($attributes);
213 }
214
215 /**
216 * Convert IDs to values and format for display.
217 *
218 * @param HTML_QuickForm_element $field
219 */
220 public static function preProcessEntityRef($field) {
221 $val = $field->getValue();
222 // Temporarily convert string values to an array
223 if (!is_array($val)) {
224 // Try to auto-detect method of serialization
225 $val = strpos($val, ',') ? explode(',', str_replace(', ', ',', $val)) : (array) CRM_Utils_Array::explodePadded($val);
226 }
227 if ($val) {
228 $entity = $field->getAttribute('data-api-entity');
229 // Get api params, ensure it is an array
230 $params = $field->getAttribute('data-api-params');
231 $params = $params ? json_decode($params, TRUE) : [];
232 $result = civicrm_api3($entity, 'getlist', ['id' => $val] + $params);
233 // Purify label output of entityreference fields
234 if (!empty($result['values'])) {
235 foreach ($result['values'] as &$res) {
236 if (!empty($res['label'])) {
237 $res['label'] = CRM_Utils_String::purifyHTML($res['label']);
238 }
239 }
240 }
241 if ($field->isFrozen()) {
242 // Prevent js from treating frozen entityRef as a "live" field
243 $field->removeAttribute('class');
244 }
245 if (!empty($result['values'])) {
246 $field->setAttribute('data-entity-value', json_encode($result['values']));
247 }
248 // CRM-15803 - Remove invalid values
249 $val = array_intersect($val, CRM_Utils_Array::collect('id', $result['values']));
250 }
251 // Convert array values back to a string
252 $field->setValue(implode(',', $val));
253 }
254
255 /**
256 * Render datepicker as text.
257 *
258 * @param array $el
259 * @param HTML_QuickForm_element $field
260 */
261 public function renderFrozenDatepicker(&$el, $field) {
262 $settings = json_decode($field->getAttribute('data-crm-datepicker'), TRUE);
263 $settings += ['date' => TRUE, 'time' => TRUE];
264 $val = $field->getValue();
265 if ($val) {
266 $dateFormat = NULL;
267 if (!$settings['time']) {
268 $val = substr($val, 0, 10);
269 }
270 elseif (!$settings['date']) {
271 $dateFormat = Civi::settings()->get('dateformatTime');
272 }
273 $val = CRM_Utils_Date::customFormat($val, $dateFormat);
274 }
275 $el['html'] = $val . '<input type="hidden" value="' . $field->getValue() . '" name="' . $field->getAttribute('name') . '">';
276 }
277
278 /**
279 * Render select2 as text.
280 *
281 * @param array $el
282 * @param HTML_QuickForm_element $field
283 */
284 public function renderFrozenSelect2(&$el, $field) {
285 $params = json_decode($field->getAttribute('data-select-params'), TRUE);
286 $val = $field->getValue();
287 if ($val && !empty($params['data'])) {
288 $display = [];
289 foreach (explode(',', $val) as $item) {
290 $match = CRM_Utils_Array::findInTree($item, $params['data']);
291 if (isset($match['text']) && strlen($match['text'])) {
292 $display[] = CRM_Utils_String::purifyHTML($match['text']);
293 }
294 }
295 $el['html'] = implode('; ', $display) . '<input type="hidden" value="' . $field->getValue() . '" name="' . $field->getAttribute('name') . '">';
296 }
297 }
298
299 /**
300 * Render entity references as text.
301 * If user has permission, format as link (for now limited to contacts).
302 *
303 * @param array $el
304 * @param HTML_QuickForm_element $field
305 */
306 public function renderFrozenEntityRef(&$el, $field) {
307 $entity = $field->getAttribute('data-api-entity');
308 $vals = json_decode($field->getAttribute('data-entity-value'), TRUE);
309 $display = [];
310
311 // Custom fields of type contactRef store their data in a slightly different format
312 if ($field->getAttribute('data-crm-custom') && $entity == 'Contact') {
313 $vals = [['id' => $vals['id'], 'label' => $vals['text']]];
314 }
315
316 foreach ($vals as $val) {
317 // Format contact as link
318 if ($entity == 'Contact' && CRM_Contact_BAO_Contact_Permission::allow($val['id'], CRM_Core_Permission::VIEW)) {
319 $url = CRM_Utils_System::url("civicrm/contact/view", ['reset' => 1, 'cid' => $val['id']]);
320 $val['label'] = '<a class="view-contact no-popup" href="' . $url . '" title="' . ts('View Contact') . '">' . CRM_Utils_String::purifyHTML($val['label']) . '</a>';
321 }
322 $display[] = $val['label'];
323 }
324
325 $el['html'] = implode('; ', $display) . '<input type="hidden" value="' . $field->getValue() . '" name="' . $field->getAttribute('name') . '">';
326 }
327
328 /**
329 * Pre-fill contact name for a custom field of type ContactReference
330 *
331 * Todo: Migrate contact reference fields to use EntityRef
332 *
333 * @param HTML_QuickForm_element $field
334 */
335 public static function preprocessContactReference($field) {
336 $val = $field->getValue();
337 $multiple = $field->getAttribute('multiple');
338 $data = [];
339 if ($val) {
340
341 $list = array_keys(CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
342 'contact_reference_options'
343 ), '1');
344
345 $return = array_unique(array_merge(['sort_name'], $list));
346
347 $cids = is_array($val) ? $val : explode(',', $val);
348
349 foreach ($cids as $cid) {
350 $contact = civicrm_api('contact', 'getsingle', ['id' => $cid, 'return' => $return, 'version' => 3]);
351 if (!empty($contact['id'])) {
352 $view = [];
353 foreach ($return as $fld) {
354 if (!empty($contact[$fld])) {
355 $view[] = $contact[$fld];
356 }
357 }
358 $data[] = [
359 'id' => $contact['id'],
360 'text' => implode(' :: ', $view),
361 ];
362 }
363 }
364 }
365
366 if ($data) {
367 $field->setAttribute('data-entity-value', json_encode($multiple ? $data : $data[0]));
368 $field->setValue(implode(',', $cids));
369 }
370 }
371
372 /**
373 * @param array $el
374 * @param HTML_QuickForm_element $field
375 */
376 public function addOptionsEditLink(&$el, $field) {
377 if (CRM_Core_Permission::check('administer CiviCRM')) {
378 // NOTE: $path is used on the client-side to know which option lists need rebuilding,
379 // that's why we need that bit of data both in the link and in the form element
380 $path = $field->getAttribute('data-option-edit-path');
381 // NOTE: If we ever needed to support arguments in this link other than reset=1 we could split $path here if it contains a ?
382 $url = CRM_Utils_System::url($path, 'reset=1');
383 $icon = CRM_Core_Page::crmIcon('fa-wrench', ts('Edit %1 Options', [1 => $field->getLabel() ?: ts('Field')]));
384 $el['html'] .= <<<HEREDOC
385 <a href="$url" class="crm-option-edit-link medium-popup crm-hover-button" target="_blank" data-option-edit-path="$path">$icon</a>
386 HEREDOC;
387 }
388 }
389
390 /**
391 * @param array $el
392 * @param HTML_QuickForm_element $field
393 */
394 public function appendUnselectButton(&$el, $field) {
395 // Initially hide if not needed
396 // Note: visibility:hidden prevents layout jumping around unlike display:none
397 $display = $field->getValue() !== NULL ? '' : ' style="visibility:hidden;"';
398 $el['html'] .= ' <a href="#" class="crm-hover-button crm-clear-link"' . $display . ' title="' . ts('Clear') . '"><i class="crm-i fa-times" aria-hidden="true"></i></a>';
399 }
400
401 }