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