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