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