sr-only text for wrenches
[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 }
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 \CRM_Core_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]['html']['label'])) {
206 $props['label'] = $fields[$fieldName]['html']['label'];
207 }
208 elseif (isset($fields[$fieldName]['title'])) {
209 $props['label'] = $fields[$fieldName]['title'];
210 }
211 if (empty($fieldSpec['is_pseudofield'])) {
212 $this->addField($fieldName, $props);
213 }
214 }
215 }
216 }
217 }
218
219 /**
220 * Global validation rules for the form.
221 *
222 * @param array $fields
223 * Posted values of the form.
224 * @param array $files
225 * @param object $form
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 = [];
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 }
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)) {
240 if (!empty($fields[$fieldName . '_high']) && !empty($fields[$fieldName . '_low']) && empty($fields[$fieldName . '_relative'])) {
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
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
270 case CRM_Utils_Type::T_DATE:
271 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
272 return 'Timestamp';
273
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
285 *
286 * @throws \CRM_Core_Exception
287 */
288 protected function getEntityDefaults($entity) {
289 $defaults = [];
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');
293 if ($value !== NULL) {
294 if ($fieldSpec['html']['type'] === 'Select') {
295 $defaults[$fieldName] = explode(',', $value);
296 }
297 else {
298 $defaults[$fieldName] = $value;
299 }
300 }
301 if ($fieldSpec['type'] === CRM_Utils_Type::T_DATE || ($fieldSpec['type'] === CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)) {
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) {
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;
308 }
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 }
315 }
316 }
317 }
318 return $defaults;
319 }
320
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() {
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])) {
333 $this->_formValues[$fieldName] = ['LIKE' => CRM_Contact_BAO_Query::getWildCardedValue(TRUE, 'LIKE', trim($this->_formValues[$fieldName]))];
334 }
335 }
336 }
337 }
338 }
339
340 /**
341 * Add checkboxes for each row plus a master checkbox.
342 *
343 * @param array $rows
344 */
345 public function addRowSelectors($rows) {
346 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
347 if (!empty($rows)) {
348 foreach ($rows as $row) {
349 if (!empty($row['checkbox'])) {
350 $this->addElement('checkbox', $row['checkbox'], NULL, NULL, ['class' => 'select-row']);
351 }
352 }
353 }
354 }
355
356 /**
357 * Add actions menu to search results form.
358 *
359 * @param array $tasks
360 */
361 public function addTaskMenu($tasks) {
362 $taskMetaData = [];
363 foreach ($tasks as $key => $task) {
364 $taskMetaData[$key] = ['title' => $task];
365 }
366 parent::addTaskMenu($taskMetaData);
367 }
368
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.
377 *
378 * @throws \CiviCRM_API3_Exception
379 */
380 protected function addSortNameField() {
381 $title = civicrm_api3('setting', 'getvalue', ['name' => 'includeEmailInName', 'group' => 'Search Preferences']) ? $this->getSortNameLabelWithEmail() : $this->getSortNameLabelWithOutEmail();
382 $this->addElement(
383 'text',
384 'sort_name',
385 $title,
386 CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')
387 );
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]);
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
413 /**
414 * Explicitly declare the form context for addField().
415 */
416 public function getDefaultContext() {
417 return 'search';
418 }
419
420 /**
421 * Add generic fields that specify the contact.
422 *
423 * @throws \CiviCRM_API3_Exception
424 */
425 protected function addContactSearchFields() {
426 if (!$this->isFormInViewOrEditMode()) {
427 return;
428 }
429 $this->addSortNameField();
430 if ($this->sortNameOnly) {
431 return;
432 }
433
434 $this->_group = CRM_Core_PseudoConstant::nestedGroup();
435 if ($this->_group) {
436 $this->add('select', 'group', $this->getGroupLabel(), $this->_group, FALSE,
437 [
438 'id' => 'group',
439 'multiple' => 'multiple',
440 'class' => 'crm-select2',
441 ]
442 );
443 $this->searchFieldMetadata['Contact']['group'] = ['name' => 'group', 'type' => CRM_Utils_Type::T_INT, 'is_pseudofield' => TRUE, 'html' => ['type' => 'Select']];
444 }
445
446 $contactTags = CRM_Core_BAO_Tag::getTags();
447 if ($contactTags) {
448 $this->add('select', 'contact_tags', $this->getTagLabel(), $contactTags, FALSE,
449 [
450 'id' => 'contact_tags',
451 'multiple' => 'multiple',
452 'class' => 'crm-select2',
453 ]
454 );
455 }
456 $this->searchFieldMetadata['Contact']['contact_tags'] = ['name' => 'contact_tags', 'type' => CRM_Utils_Type::T_INT, 'is_pseudofield' => TRUE, 'html' => ['type' => 'Select']];
457 $this->addField('contact_type', ['entity' => 'Contact']);
458 $this->searchFieldMetadata['Contact']['contact_type'] = CRM_Contact_DAO_Contact::fields()['contact_type'];
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)'));
462 $this->searchFieldMetadata['Contact']['deleted_contacts'] = ['name' => 'deleted_contacts', 'type' => CRM_Utils_Type::T_INT, 'is_pseudofield' => TRUE, 'html' => ['type' => 'Checkbox']];
463 }
464
465 }
466
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
488 /**
489 * we allow the controller to set force/reset externally, useful when we are being
490 * driven by the wizard framework
491 *
492 * @throws \CRM_Core_Exception
493 */
494 protected function loadStandardSearchOptionsFromUrl() {
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 */
508 protected function loadFormValues() {
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
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
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
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();
575 $this->addContactSearchFields();
576 $this->postProcess();
577 $this->set('force', 0);
578 }
579
580 }