Merge pull request #15821 from seamuslee001/dev_core_183_custom_group
[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 * 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 }
124
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
130 * @throws \CRM_Core_Exception
131 */
132 public function setDefaultValues() {
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');
137 foreach (array_keys($this->getSearchFieldMetadata()) as $entity) {
138 $defaults = array_merge($this->getEntityDefaults($entity), $defaults);
139 }
140 return $defaults;
141 }
142
143 /**
144 * Set the form values based on input and preliminary processing.
145 *
146 * @throws \Exception
147 */
148 protected function setFormValues() {
149 $this->_formValues = $this->getFormValues();
150 $this->set('formValues', $this->_formValues);
151 $this->convertTextStringsToUseLikeOperator();
152 }
153
154 /**
155 * Common buildForm tasks required by all searches.
156 *
157 * @throws \CRM_Core_Exception
158 */
159 public function buildQuickForm() {
160 CRM_Core_Resources::singleton()
161 ->addScriptFile('civicrm', 'js/crm.searchForm.js', 1, 'html-header')
162 ->addStyleFile('civicrm', 'css/searchForm.css', 1, 'html-header');
163
164 $this->addButtons([
165 [
166 'type' => 'refresh',
167 'name' => ts('Search'),
168 'isDefault' => TRUE,
169 ],
170 ]);
171
172 $this->addClass('crm-search-form');
173
174 $tasks = $this->buildTaskList();
175 $this->addTaskMenu($tasks);
176 }
177
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.
183 *
184 * @throws \CiviCRM_API3_Exception
185 */
186 public function addFormFieldsFromMetadata() {
187 $this->addFormRule(['CRM_Core_Form_Search', 'formRule'], $this);
188 $this->_action = CRM_Core_Action::ADVANCED;
189 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
190 foreach ($fields as $fieldName => $fieldSpec) {
191 $fieldType = $fieldSpec['type'] ?? '';
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) {
193 $title = empty($fieldSpec['unique_title']) ? $fieldSpec['title'] : $fieldSpec['unique_title'];
194 $this->addDatePickerRange($fieldName, $title, ($fieldType === (CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) || $fieldType === CRM_Utils_Type::T_TIMESTAMP));
195 }
196 else {
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];
202 if (isset($fields[$fieldName]['unique_title'])) {
203 $props['label'] = $fields[$fieldName]['unique_title'];
204 }
205 elseif (isset($fields[$fieldName]['title'])) {
206 $props['label'] = $fields[$fieldName]['title'];
207 }
208 if (empty($fieldSpec['is_pseudofield'])) {
209 $this->addField($fieldName, $props);
210 }
211 }
212 }
213 }
214 }
215
216 /**
217 * Global validation rules for the form.
218 *
219 * @param array $fields
220 * Posted values of the form.
221 * @param array $files
222 * @param object $form
223 *
224 * @return array
225 * list of errors to be posted back to the form
226 */
227 public static function formRule($fields, $files, $form) {
228 $errors = [];
229 if (!is_a($form, 'CRM_Core_Form_Search')) {
230 // So this gets hit with a form object when doing an activity date search from
231 // advanced search, but a NULL object when doing a pledge search.
232 return $errors;
233 }
234 foreach ($form->getSearchFieldMetadata() as $entity => $spec) {
235 foreach ($spec as $fieldName => $fieldSpec) {
236 if ($fieldSpec['type'] === CRM_Utils_Type::T_DATE || $fieldSpec['type'] === (CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)) {
237 if (!empty($fields[$fieldName . '_high']) && !empty($fields[$fieldName . '_low']) && empty($fields[$fieldName . '_relative'])) {
238 if (strtotime($fields[$fieldName . '_low']) > strtotime($fields[$fieldName . '_high'])) {
239 $errors[$fieldName . '_low'] = ts('%1: Please check that your date range is in correct chronological order.', [1 => $fieldSpec['title']]);
240 }
241 }
242 }
243 }
244 }
245 return $errors;
246 }
247
248 /**
249 * Get the validation rule to apply to a function.
250 *
251 * Alphanumeric is designed to always be safe & for now we just return
252 * that but in future we can use tighter rules for types like int, bool etc.
253 *
254 * @param string $entity
255 * @param string $fieldName
256 *
257 * @return string
258 */
259 protected function getValidationTypeForField($entity, $fieldName) {
260 switch ($this->getSearchFieldMetadata()[$entity][$fieldName]['type']) {
261 case CRM_Utils_Type::T_BOOLEAN:
262 return 'Boolean';
263
264 case CRM_Utils_Type::T_INT:
265 return 'CommaSeparatedIntegers';
266
267 case CRM_Utils_Type::T_DATE:
268 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
269 return 'Timestamp';
270
271 default:
272 return 'Alphanumeric';
273 }
274 }
275
276 /**
277 * Get the defaults for the entity for any fields described in metadata.
278 *
279 * @param string $entity
280 *
281 * @return array
282 *
283 * @throws \CRM_Core_Exception
284 */
285 protected function getEntityDefaults($entity) {
286 $defaults = [];
287 foreach (CRM_Utils_Array::value($entity, $this->getSearchFieldMetadata(), []) as $fieldName => $fieldSpec) {
288 if (empty($_POST[$fieldName])) {
289 $value = CRM_Utils_Request::retrieveValue($fieldName, $this->getValidationTypeForField($entity, $fieldName), NULL, NULL, 'GET');
290 if ($value !== NULL) {
291 if ($fieldSpec['html']['type'] === 'Select') {
292 $defaults[$fieldName] = explode(',', $value);
293 }
294 else {
295 $defaults[$fieldName] = $value;
296 }
297 }
298 if ($fieldSpec['type'] === CRM_Utils_Type::T_DATE || ($fieldSpec['type'] === CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)) {
299 $low = CRM_Utils_Request::retrieveValue($fieldName . '_low', 'Timestamp', NULL, NULL, 'GET');
300 $high = CRM_Utils_Request::retrieveValue($fieldName . '_high', 'Timestamp', NULL, NULL, 'GET');
301 if ($low !== NULL || $high !== NULL) {
302 $defaults[$fieldName . '_relative'] = 0;
303 $defaults[$fieldName . '_low'] = $low ? date('Y-m-d H:i:s', strtotime($low)) : NULL;
304 $defaults[$fieldName . '_high'] = $high ? date('Y-m-d H:i:s', strtotime($high)) : NULL;
305 }
306 else {
307 $relative = CRM_Utils_Request::retrieveValue($fieldName . '_relative', 'String', NULL, NULL, 'GET');
308 if (!empty($relative) && isset(CRM_Core_OptionGroup::values('relative_date_filters')[$relative])) {
309 $defaults[$fieldName . '_relative'] = $relative;
310 }
311 }
312 }
313 }
314 }
315 return $defaults;
316 }
317
318 /**
319 * Convert any submitted text fields to use 'like' rather than '=' as the operator.
320 *
321 * This excludes any with options.
322 *
323 * Note this will only pick up fields declared via metadata.
324 */
325 protected function convertTextStringsToUseLikeOperator() {
326 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
327 foreach ($fields as $fieldName => $field) {
328 if (!empty($this->_formValues[$fieldName]) && empty($field['options']) && empty($field['pseudoconstant'])) {
329 if (in_array($field['type'], [CRM_Utils_Type::T_STRING, CRM_Utils_Type::T_TEXT])) {
330 $this->_formValues[$fieldName] = ['LIKE' => CRM_Contact_BAO_Query::getWildCardedValue(TRUE, 'LIKE', trim($this->_formValues[$fieldName]))];
331 }
332 }
333 }
334 }
335 }
336
337 /**
338 * Add checkboxes for each row plus a master checkbox.
339 *
340 * @param array $rows
341 */
342 public function addRowSelectors($rows) {
343 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
344 if (!empty($rows)) {
345 foreach ($rows as $row) {
346 if (!empty($row['checkbox'])) {
347 $this->addElement('checkbox', $row['checkbox'], NULL, NULL, ['class' => 'select-row']);
348 }
349 }
350 }
351 }
352
353 /**
354 * Add actions menu to search results form.
355 *
356 * @param array $tasks
357 */
358 public function addTaskMenu($tasks) {
359 $taskMetaData = [];
360 foreach ($tasks as $key => $task) {
361 $taskMetaData[$key] = ['title' => $task];
362 }
363 parent::addTaskMenu($taskMetaData);
364 }
365
366 /**
367 * Add the sort-name field to the form.
368 *
369 * There is a setting to determine whether email is included in the search & we look this up to determine
370 * which text to choose.
371 *
372 * Note that for translation purposes the full string works better than using 'prefix' hence we use override-able functions
373 * to define the string.
374 *
375 * @throws \CiviCRM_API3_Exception
376 */
377 protected function addSortNameField() {
378 $title = civicrm_api3('setting', 'getvalue', ['name' => 'includeEmailInName', 'group' => 'Search Preferences']) ? $this->getSortNameLabelWithEmail() : $this->getSortNameLabelWithOutEmail();
379 $this->addElement(
380 'text',
381 'sort_name',
382 $title,
383 CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')
384 );
385 $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]);
386 }
387
388 /**
389 * Get the label for the sortName field if email searching is on.
390 *
391 * (email searching is a setting under search preferences).
392 *
393 * @return string
394 */
395 protected function getSortNameLabelWithEmail() {
396 return ts('Name or Email');
397 }
398
399 /**
400 * Get the label for the sortName field if email searching is off.
401 *
402 * (email searching is a setting under search preferences).
403 *
404 * @return string
405 */
406 protected function getSortNameLabelWithOutEmail() {
407 return ts('Name');
408 }
409
410 /**
411 * Explicitly declare the form context for addField().
412 */
413 public function getDefaultContext() {
414 return 'search';
415 }
416
417 /**
418 * Add generic fields that specify the contact.
419 *
420 * @throws \CiviCRM_API3_Exception
421 */
422 protected function addContactSearchFields() {
423 if (!$this->isFormInViewOrEditMode()) {
424 return;
425 }
426 $this->addSortNameField();
427
428 $this->_group = CRM_Core_PseudoConstant::nestedGroup();
429 if ($this->_group) {
430 $this->add('select', 'group', $this->getGroupLabel(), $this->_group, FALSE,
431 [
432 'id' => 'group',
433 'multiple' => 'multiple',
434 'class' => 'crm-select2',
435 ]
436 );
437 }
438
439 $contactTags = CRM_Core_BAO_Tag::getTags();
440 if ($contactTags) {
441 $this->add('select', 'contact_tags', $this->getTagLabel(), $contactTags, FALSE,
442 [
443 'id' => 'contact_tags',
444 'multiple' => 'multiple',
445 'class' => 'crm-select2',
446 ]
447 );
448 }
449 $this->addField('contact_type', ['entity' => 'Contact']);
450
451 if (CRM_Core_Permission::check('access deleted contacts') && Civi::settings()->get('contact_undelete')) {
452 $this->addElement('checkbox', 'deleted_contacts', ts('Search in Trash') . '<br />' . ts('(deleted contacts)'));
453 }
454
455 }
456
457 /**
458 * Get the label for the group field.
459 *
460 * @return string
461 */
462 protected function getGroupLabel() {
463 return ts('Group(s)');
464 }
465
466 /**
467 * Get the label for the tag field.
468 *
469 * We do this in a function so the 'ts' wraps the whole string to allow
470 * better translation.
471 *
472 * @return string
473 */
474 protected function getTagLabel() {
475 return ts('Tag(s)');
476 }
477
478 /**
479 * we allow the controller to set force/reset externally, useful when we are being
480 * driven by the wizard framework
481 *
482 * @throws \CRM_Core_Exception
483 */
484 protected function loadStandardSearchOptionsFromUrl() {
485 $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
486 $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
487 $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
488 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'search');
489 $this->_ssID = CRM_Utils_Request::retrieve('ssID', 'Positive', $this);
490 $this->assign("context", $this->_context);
491 }
492
493 /**
494 * Get user submitted values.
495 *
496 * Get it from controller only if form has been submitted, else preProcess has set this
497 */
498 protected function loadFormValues() {
499 if (!empty($_POST) && !$this->controller->isModal()) {
500 $this->_formValues = $this->controller->exportValues($this->_name);
501 }
502 else {
503 $this->_formValues = $this->get('formValues');
504 }
505
506 if (empty($this->_formValues)) {
507 if (isset($this->_ssID)) {
508 $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
509 }
510 }
511 }
512
513 /**
514 * Get the form values.
515 *
516 * @todo consolidate with loadFormValues()
517 *
518 * @return array
519 *
520 * @throws \CRM_Core_Exception
521 */
522 protected function getFormValues() {
523 if (!empty($_POST) && !$this->_force) {
524 return $this->controller->exportValues($this->_name);
525 }
526 if ($this->_force) {
527 return $this->setDefaultValues();
528 }
529 return (array) $this->get('formValues');
530 }
531
532 /**
533 * Get the string processed to determine sort order.
534 *
535 * This looks like 'sort_name_u' for Sort name ascending.
536 *
537 * @return string|null
538 */
539 protected function getSortID() {
540 if ($this->get(CRM_Utils_Sort::SORT_ID)) {
541 return CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
542 $this->get(CRM_Utils_Sort::SORT_DIRECTION)
543 );
544 }
545 return NULL;
546 }
547
548 /**
549 * Set the metadata for the form.
550 *
551 * @throws \CiviCRM_API3_Exception
552 */
553 protected function setSearchMetadata() {}
554
555 /**
556 * Handle force=1 in the url.
557 *
558 * Search field metadata is normally added in buildForm but we are bypassing that in this flow
559 * (I've always found the flow kinda confusing & perhaps that is the problem but this mitigates)
560 *
561 * @throws \CiviCRM_API3_Exception
562 */
563 protected function handleForcedSearch() {
564 $this->setSearchMetadata();
565 $this->addContactSearchFields();
566 $this->postProcess();
567 $this->set('force', 0);
568 }
569
570 }