Some more notice fixes in smarty
[civicrm-core.git] / CRM / Core / Form / Search.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 * Base class for most search forms
14 */
15 class CRM_Core_Form_Search extends CRM_Core_Form {
16
17 /**
18 * Are we forced to run a search
19 *
20 * @var int
21 */
22 protected $_force;
23
24 /**
25 * Name of action button
26 *
27 * @var string
28 */
29 protected $_actionButtonName;
30
31 /**
32 * Form values that we will be using
33 *
34 * @var array
35 */
36 public $_formValues;
37
38 /**
39 * Have we already done this search
40 *
41 * @var bool
42 */
43 protected $_done;
44
45 /**
46 * What context are we being invoked from
47 *
48 * @var string
49 */
50 protected $_context;
51
52 /**
53 * The list of tasks or actions that a searcher can perform on a result set.
54 *
55 * @var array
56 */
57 protected $_taskList = [];
58
59 /**
60 * Declare entity reference fields as they will need to be converted.
61 *
62 * The entity reference format looks like '2,3' whereas the Query object expects array(2, 3)
63 * or array('IN' => array(2, 3). The latter is the one we are moving towards standardising on.
64 *
65 * @var array
66 */
67 protected $entityReferenceFields = [];
68
69 /**
70 * Builds the list of tasks or actions that a searcher can perform on a result set.
71 *
72 * To modify the task list, child classes should alter $this->_taskList,
73 * preferably by extending this method.
74 *
75 * @return array
76 */
77 protected function buildTaskList() {
78 return $this->_taskList;
79 }
80
81 /**
82 * Should we be adding all the metadata for contact search fields or just for the sort name.
83 *
84 * @var bool
85 */
86 protected $sortNameOnly = FALSE;
87
88 /**
89 * Metadata for fields on the search form.
90 *
91 * Instantiate with empty array for contact to prevent e-notices.
92 *
93 * @var array
94 */
95 protected $searchFieldMetadata = ['Contact' => []];
96
97 /**
98 * @return array
99 */
100 public function getSearchFieldMetadata() {
101 return $this->searchFieldMetadata;
102 }
103
104 /**
105 * @param array $searchFieldMetadata
106 */
107 public function addSearchFieldMetadata($searchFieldMetadata) {
108 $this->searchFieldMetadata = array_merge($this->searchFieldMetadata, $searchFieldMetadata);
109 }
110
111 /**
112 * Prepare for search by loading options from the url, handling force searches, retrieving form values.
113 *
114 * @throws \CRM_Core_Exception
115 * @throws \CiviCRM_API3_Exception
116 */
117 public function preProcess() {
118 $this->loadStandardSearchOptionsFromUrl();
119 if ($this->_force) {
120 $this->handleForcedSearch();
121 }
122 $this->_formValues = $this->getFormValues();
123 // For searchResultsTasks.tpl.
124 $this->addExpectedSmartyVariables(['savedSearch', 'selectorLabel']);
125 }
126
127 /**
128 * This virtual function is used to set the default values of various form elements.
129 *
130 * @return array|NULL
131 * reference to the array of default values
132 * @throws \CRM_Core_Exception
133 */
134 public function setDefaultValues() {
135 // Use the form values stored to the form. Ideally 'formValues'
136 // would remain 'pure' & another array would be wrangled.
137 // We don't do that - so we want the version of formValues stored early on.
138 $defaults = (array) $this->get('formValues');
139 foreach (array_keys($this->getSearchFieldMetadata()) as $entity) {
140 $defaults = array_merge($this->getEntityDefaults($entity), $defaults);
141 }
142 return $defaults;
143 }
144
145 /**
146 * Set the form values based on input and preliminary processing.
147 *
148 * @throws \CRM_Core_Exception
149 */
150 protected function setFormValues() {
151 $this->_formValues = $this->getFormValues();
152 $this->set('formValues', $this->_formValues);
153 $this->convertTextStringsToUseLikeOperator();
154 }
155
156 /**
157 * Common buildForm tasks required by all searches.
158 *
159 * @throws \CRM_Core_Exception
160 */
161 public function buildQuickForm() {
162 CRM_Core_Resources::singleton()
163 ->addScriptFile('civicrm', 'js/crm.searchForm.js', 1, 'html-header')
164 ->addStyleFile('civicrm', 'css/searchForm.css', 1, 'html-header');
165
166 $this->addButtons([
167 [
168 'type' => 'refresh',
169 'name' => ts('Search'),
170 'isDefault' => TRUE,
171 ],
172 ]);
173
174 $this->addClass('crm-search-form');
175
176 $tasks = $this->buildTaskList();
177 $this->addTaskMenu($tasks);
178 }
179
180 /**
181 * Add any fields described in metadata to the form.
182 *
183 * The goal is to describe all fields in metadata and handle from metadata rather
184 * than existing ad hoc handling.
185 *
186 * @throws \CiviCRM_API3_Exception
187 */
188 public function addFormFieldsFromMetadata() {
189 $this->addFormRule(['CRM_Core_Form_Search', 'formRule'], $this);
190 $this->_action = CRM_Core_Action::ADVANCED;
191 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
192 foreach ($fields as $fieldName => $fieldSpec) {
193 $fieldType = $fieldSpec['type'] ?? '';
194 if ($fieldType === CRM_Utils_Type::T_DATE || $fieldType === (CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) || $fieldType === CRM_Utils_Type::T_TIMESTAMP) {
195 $title = empty($fieldSpec['unique_title']) ? $fieldSpec['title'] : $fieldSpec['unique_title'];
196 $this->addDatePickerRange($fieldName, $title, ($fieldType === (CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) || $fieldType === CRM_Utils_Type::T_TIMESTAMP));
197 }
198 else {
199 // Not quite sure about moving to a mix of keying by entity vs permitting entity to
200 // be passed in. The challenge of the former is that it doesn't permit ordering.
201 // Perhaps keying was the wrong starting point & we should do a flat array as all
202 // fields eventually need to be unique.
203 $props = ['entity' => $fieldSpec['entity'] ?? $entity];
204 if (isset($fields[$fieldName]['unique_title'])) {
205 $props['label'] = $fields[$fieldName]['unique_title'];
206 }
207 elseif (isset($fields[$fieldName]['html']['label'])) {
208 $props['label'] = $fields[$fieldName]['html']['label'];
209 }
210 elseif (isset($fields[$fieldName]['title'])) {
211 $props['label'] = $fields[$fieldName]['title'];
212 }
213 if (empty($fieldSpec['is_pseudofield'])) {
214 $this->addField($fieldName, $props);
215 }
216 }
217 }
218 }
219 }
220
221 /**
222 * Global validation rules for the form.
223 *
224 * @param array $fields
225 * Posted values of the form.
226 * @param array $files
227 * @param object $form
228 *
229 * @return array
230 * list of errors to be posted back to the form
231 */
232 public static function formRule($fields, $files, $form) {
233 $errors = [];
234 if (!is_a($form, 'CRM_Core_Form_Search')) {
235 // So this gets hit with a form object when doing an activity date search from
236 // advanced search, but a NULL object when doing a pledge search.
237 return $errors;
238 }
239 foreach ($form->getSearchFieldMetadata() as $entity => $spec) {
240 foreach ($spec as $fieldName => $fieldSpec) {
241 if ($fieldSpec['type'] === CRM_Utils_Type::T_DATE || $fieldSpec['type'] === (CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)) {
242 if (!empty($fields[$fieldName . '_high']) && !empty($fields[$fieldName . '_low']) && empty($fields[$fieldName . '_relative'])) {
243 if (strtotime($fields[$fieldName . '_low']) > strtotime($fields[$fieldName . '_high'])) {
244 $errors[$fieldName . '_low'] = ts('%1: Please check that your date range is in correct chronological order.', [1 => $fieldSpec['title']]);
245 }
246 }
247 }
248 }
249 }
250 return $errors;
251 }
252
253 /**
254 * Get the validation rule to apply to a function.
255 *
256 * Alphanumeric is designed to always be safe & for now we just return
257 * that but in future we can use tighter rules for types like int, bool etc.
258 *
259 * @param string $entity
260 * @param string $fieldName
261 *
262 * @return string
263 */
264 protected function getValidationTypeForField($entity, $fieldName) {
265 switch ($this->getSearchFieldMetadata()[$entity][$fieldName]['type']) {
266 case CRM_Utils_Type::T_BOOLEAN:
267 return 'Boolean';
268
269 case CRM_Utils_Type::T_INT:
270 return 'CommaSeparatedIntegers';
271
272 case CRM_Utils_Type::T_DATE:
273 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
274 return 'Timestamp';
275
276 default:
277 return 'Alphanumeric';
278 }
279 }
280
281 /**
282 * Get the defaults for the entity for any fields described in metadata.
283 *
284 * @param string $entity
285 *
286 * @return array
287 *
288 * @throws \CRM_Core_Exception
289 */
290 protected function getEntityDefaults($entity) {
291 $defaults = [];
292 foreach (CRM_Utils_Array::value($entity, $this->getSearchFieldMetadata(), []) as $fieldName => $fieldSpec) {
293 if (empty($_POST[$fieldName])) {
294 $value = CRM_Utils_Request::retrieveValue($fieldName, $this->getValidationTypeForField($entity, $fieldName), NULL, NULL, 'GET');
295 if ($value !== NULL) {
296 if ($fieldSpec['html']['type'] === 'Select') {
297 $defaults[$fieldName] = explode(',', $value);
298 }
299 else {
300 $defaults[$fieldName] = $value;
301 }
302 }
303 if ($fieldSpec['type'] === CRM_Utils_Type::T_DATE || ($fieldSpec['type'] === CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)) {
304 $low = CRM_Utils_Request::retrieveValue($fieldName . '_low', 'Timestamp', NULL, NULL, 'GET');
305 $high = CRM_Utils_Request::retrieveValue($fieldName . '_high', 'Timestamp', NULL, NULL, 'GET');
306 if ($low !== NULL || $high !== NULL) {
307 $defaults[$fieldName . '_relative'] = 0;
308 $defaults[$fieldName . '_low'] = $low ? date('Y-m-d H:i:s', strtotime($low)) : NULL;
309 $defaults[$fieldName . '_high'] = $high ? date('Y-m-d H:i:s', strtotime($high)) : NULL;
310 }
311 else {
312 $relative = CRM_Utils_Request::retrieveValue($fieldName . '_relative', 'String', NULL, NULL, 'GET');
313 if (!empty($relative) && isset(CRM_Core_OptionGroup::values('relative_date_filters')[$relative])) {
314 $defaults[$fieldName . '_relative'] = $relative;
315 }
316 }
317 }
318 }
319 }
320 return $defaults;
321 }
322
323 /**
324 * Convert any submitted text fields to use 'like' rather than '=' as the operator.
325 *
326 * This excludes any with options.
327 *
328 * Note this will only pick up fields declared via metadata.
329 */
330 protected function convertTextStringsToUseLikeOperator() {
331 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
332 foreach ($fields as $fieldName => $field) {
333 if (!empty($this->_formValues[$fieldName]) && empty($field['options']) && empty($field['pseudoconstant'])) {
334 if (in_array($field['type'], [CRM_Utils_Type::T_STRING, CRM_Utils_Type::T_TEXT])) {
335 $this->_formValues[$fieldName] = ['LIKE' => CRM_Contact_BAO_Query::getWildCardedValue(TRUE, 'LIKE', trim($this->_formValues[$fieldName]))];
336 }
337 }
338 }
339 }
340 }
341
342 /**
343 * Add checkboxes for each row plus a master checkbox.
344 *
345 * @param array $rows
346 */
347 public function addRowSelectors($rows) {
348 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
349 if (!empty($rows)) {
350 foreach ($rows as $row) {
351 if (!empty($row['checkbox'])) {
352 $this->addElement('checkbox', $row['checkbox'], NULL, NULL, ['class' => 'select-row']);
353 }
354 }
355 }
356 }
357
358 /**
359 * Add actions menu to search results form.
360 *
361 * @param array $tasks
362 */
363 public function addTaskMenu($tasks) {
364 $taskMetaData = [];
365 foreach ($tasks as $key => $task) {
366 $taskMetaData[$key] = ['title' => $task];
367 }
368 parent::addTaskMenu($taskMetaData);
369 }
370
371 /**
372 * Add the sort-name field to the form.
373 *
374 * There is a setting to determine whether email is included in the search & we look this up to determine
375 * which text to choose.
376 *
377 * Note that for translation purposes the full string works better than using 'prefix' hence we use override-able functions
378 * to define the string.
379 *
380 * @throws \CiviCRM_API3_Exception
381 */
382 protected function addSortNameField() {
383 $title = civicrm_api3('setting', 'getvalue', ['name' => 'includeEmailInName', 'group' => 'Search Preferences']) ? $this->getSortNameLabelWithEmail() : $this->getSortNameLabelWithOutEmail();
384 $this->addElement(
385 'text',
386 'sort_name',
387 $title,
388 CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')
389 );
390 $this->searchFieldMetadata['Contact']['sort_name'] = array_merge(CRM_Contact_DAO_Contact::fields()['sort_name'], ['name' => 'sort_name', 'title' => $title, 'type' => CRM_Utils_Type::T_STRING]);
391 }
392
393 /**
394 * Get the label for the sortName field if email searching is on.
395 *
396 * (email searching is a setting under search preferences).
397 *
398 * @return string
399 */
400 protected function getSortNameLabelWithEmail() {
401 return ts('Name or Email');
402 }
403
404 /**
405 * Get the label for the sortName field if email searching is off.
406 *
407 * (email searching is a setting under search preferences).
408 *
409 * @return string
410 */
411 protected function getSortNameLabelWithOutEmail() {
412 return ts('Name');
413 }
414
415 /**
416 * Explicitly declare the form context for addField().
417 */
418 public function getDefaultContext() {
419 return 'search';
420 }
421
422 /**
423 * Add generic fields that specify the contact.
424 *
425 * @throws \CiviCRM_API3_Exception
426 */
427 protected function addContactSearchFields() {
428 if (!$this->isFormInViewOrEditMode()) {
429 return;
430 }
431 $this->addSortNameField();
432 if ($this->sortNameOnly) {
433 return;
434 }
435
436 $this->_group = CRM_Core_PseudoConstant::nestedGroup();
437 if ($this->_group) {
438 $this->add('select', 'group', $this->getGroupLabel(), $this->_group, FALSE,
439 [
440 'id' => 'group',
441 'multiple' => 'multiple',
442 'class' => 'crm-select2',
443 ]
444 );
445 $this->searchFieldMetadata['Contact']['group'] = ['name' => 'group', 'type' => CRM_Utils_Type::T_INT, 'is_pseudofield' => TRUE, 'html' => ['type' => 'Select']];
446 }
447
448 $contactTags = CRM_Core_BAO_Tag::getTags();
449 if ($contactTags) {
450 $this->add('select', 'contact_tags', $this->getTagLabel(), $contactTags, FALSE,
451 [
452 'id' => 'contact_tags',
453 'multiple' => 'multiple',
454 'class' => 'crm-select2',
455 ]
456 );
457 }
458 $this->searchFieldMetadata['Contact']['contact_tags'] = ['name' => 'contact_tags', 'type' => CRM_Utils_Type::T_INT, 'is_pseudofield' => TRUE, 'html' => ['type' => 'Select']];
459 $this->addField('contact_type', ['entity' => 'Contact']);
460 $this->searchFieldMetadata['Contact']['contact_type'] = CRM_Contact_DAO_Contact::fields()['contact_type'];
461
462 if (CRM_Core_Permission::check('access deleted contacts') && Civi::settings()->get('contact_undelete')) {
463 $this->addElement('checkbox', 'deleted_contacts', ts('Search in Trash') . '<br />' . ts('(deleted contacts)'));
464 $this->searchFieldMetadata['Contact']['deleted_contacts'] = ['name' => 'deleted_contacts', 'type' => CRM_Utils_Type::T_INT, 'is_pseudofield' => TRUE, 'html' => ['type' => 'Checkbox']];
465 }
466
467 }
468
469 /**
470 * Get the label for the group field.
471 *
472 * @return string
473 */
474 protected function getGroupLabel() {
475 return ts('Group(s)');
476 }
477
478 /**
479 * Get the label for the tag field.
480 *
481 * We do this in a function so the 'ts' wraps the whole string to allow
482 * better translation.
483 *
484 * @return string
485 */
486 protected function getTagLabel() {
487 return ts('Tag(s)');
488 }
489
490 /**
491 * we allow the controller to set force/reset externally, useful when we are being
492 * driven by the wizard framework
493 *
494 * @throws \CRM_Core_Exception
495 */
496 protected function loadStandardSearchOptionsFromUrl() {
497 $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
498 $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
499 $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
500 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'search');
501 $this->_ssID = CRM_Utils_Request::retrieve('ssID', 'Positive', $this);
502 $this->assign("context", $this->_context);
503 }
504
505 /**
506 * Get user submitted values.
507 *
508 * Get it from controller only if form has been submitted, else preProcess has set this
509 */
510 protected function loadFormValues() {
511 if (!empty($_POST) && !$this->controller->isModal()) {
512 $this->_formValues = $this->controller->exportValues($this->_name);
513 }
514 else {
515 $this->_formValues = $this->get('formValues');
516 }
517
518 if (empty($this->_formValues)) {
519 if (isset($this->_ssID)) {
520 $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
521 }
522 }
523 }
524
525 /**
526 * Get the form values.
527 *
528 * @todo consolidate with loadFormValues()
529 *
530 * @return array
531 *
532 * @throws \CRM_Core_Exception
533 */
534 protected function getFormValues() {
535 if (!empty($_POST) && !$this->_force) {
536 return $this->controller->exportValues($this->_name);
537 }
538 if ($this->_force) {
539 return $this->setDefaultValues();
540 }
541 return (array) $this->get('formValues');
542 }
543
544 /**
545 * Get the string processed to determine sort order.
546 *
547 * This looks like 'sort_name_u' for Sort name ascending.
548 *
549 * @return string|null
550 */
551 protected function getSortID() {
552 if ($this->get(CRM_Utils_Sort::SORT_ID)) {
553 return CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
554 $this->get(CRM_Utils_Sort::SORT_DIRECTION)
555 );
556 }
557 return NULL;
558 }
559
560 /**
561 * Set the metadata for the form.
562 *
563 * @throws \CiviCRM_API3_Exception
564 */
565 protected function setSearchMetadata() {}
566
567 /**
568 * Handle force=1 in the url.
569 *
570 * Search field metadata is normally added in buildForm but we are bypassing that in this flow
571 * (I've always found the flow kinda confusing & perhaps that is the problem but this mitigates)
572 *
573 * @throws \CiviCRM_API3_Exception
574 */
575 protected function handleForcedSearch() {
576 $this->setSearchMetadata();
577 $this->addContactSearchFields();
578 $this->postProcess();
579 $this->set('force', 0);
580 }
581
582 }