Merge pull request #15809 from eileenmcnaughton/except
[civicrm-core.git] / CRM / Core / Form / Search.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
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 |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
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 |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * Base class for most search forms
30 */
31 class CRM_Core_Form_Search extends CRM_Core_Form {
32
33 /**
34 * Are we forced to run a search
35 *
36 * @var int
37 */
38 protected $_force;
39
40 /**
41 * Name of search button
42 *
43 * @var string
44 */
45 protected $_searchButtonName;
46
47 /**
48 * Name of action button
49 *
50 * @var string
51 */
52 protected $_actionButtonName;
53
54 /**
55 * Form values that we will be using
56 *
57 * @var array
58 */
59 public $_formValues;
60
61 /**
62 * Have we already done this search
63 *
64 * @var bool
65 */
66 protected $_done;
67
68 /**
69 * What context are we being invoked from
70 *
71 * @var string
72 */
73 protected $_context;
74
75 /**
76 * The list of tasks or actions that a searcher can perform on a result set.
77 *
78 * @var array
79 */
80 protected $_taskList = [];
81
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 */
90 protected $entityReferenceFields = [];
91
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
104 /**
105 * Metadata for fields on the search form.
106 *
107 * Instantiate with empty array for contact to prevent e-notices.
108 *
109 * @var array
110 */
111 protected $searchFieldMetadata = ['Contact' => []];
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
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
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
146 * @throws \CRM_Core_Exception
147 */
148 public function setDefaultValues() {
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');
153 foreach (array_keys($this->getSearchFieldMetadata()) as $entity) {
154 $defaults = array_merge($this->getEntityDefaults($entity), $defaults);
155 }
156 return $defaults;
157 }
158
159 /**
160 * Set the form values based on input and preliminary processing.
161 *
162 * @throws \Exception
163 */
164 protected function setFormValues() {
165 $this->_formValues = $this->getFormValues();
166 $this->set('formValues', $this->_formValues);
167 $this->convertTextStringsToUseLikeOperator();
168 }
169
170 /**
171 * Common buildForm tasks required by all searches.
172 *
173 * @throws \CRM_Core_Exception
174 */
175 public function buildQuickForm() {
176 CRM_Core_Resources::singleton()
177 ->addScriptFile('civicrm', 'js/crm.searchForm.js', 1, 'html-header')
178 ->addStyleFile('civicrm', 'css/searchForm.css', 1, 'html-header');
179
180 $this->addButtons([
181 [
182 'type' => 'refresh',
183 'name' => ts('Search'),
184 'isDefault' => TRUE,
185 ],
186 ]);
187
188 $this->addClass('crm-search-form');
189
190 $tasks = $this->buildTaskList();
191 $this->addTaskMenu($tasks);
192 }
193
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.
199 *
200 * @throws \CiviCRM_API3_Exception
201 */
202 public function addFormFieldsFromMetadata() {
203 $this->addFormRule(['CRM_Core_Form_Search', 'formRule'], $this);
204 $this->_action = CRM_Core_Action::ADVANCED;
205 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
206 foreach ($fields as $fieldName => $fieldSpec) {
207 $fieldType = $fieldSpec['type'] ?? '';
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) {
209 $title = empty($fieldSpec['unique_title']) ? $fieldSpec['title'] : $fieldSpec['unique_title'];
210 $this->addDatePickerRange($fieldName, $title, ($fieldType === (CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) || $fieldType === CRM_Utils_Type::T_TIMESTAMP));
211 }
212 else {
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];
218 if (isset($fields[$fieldName]['unique_title'])) {
219 $props['label'] = $fields[$fieldName]['unique_title'];
220 }
221 elseif (isset($fields[$fieldName]['title'])) {
222 $props['label'] = $fields[$fieldName]['title'];
223 }
224 if (empty($fieldSpec['is_pseudofield'])) {
225 $this->addField($fieldName, $props);
226 }
227 }
228 }
229 }
230 }
231
232 /**
233 * Global validation rules for the form.
234 *
235 * @param array $fields
236 * Posted values of the form.
237 * @param array $files
238 * @param object $form
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 = [];
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 }
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)) {
253 if (!empty($fields[$fieldName . '_high']) && !empty($fields[$fieldName . '_low']) && empty($fields[$fieldName . '_relative'])) {
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
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
283 case CRM_Utils_Type::T_DATE:
284 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
285 return 'Timestamp';
286
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
298 *
299 * @throws \CRM_Core_Exception
300 */
301 protected function getEntityDefaults($entity) {
302 $defaults = [];
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');
306 if ($value !== NULL) {
307 if ($fieldSpec['html']['type'] === 'Select') {
308 $defaults[$fieldName] = explode(',', $value);
309 }
310 else {
311 $defaults[$fieldName] = $value;
312 }
313 }
314 if ($fieldSpec['type'] === CRM_Utils_Type::T_DATE || ($fieldSpec['type'] === CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)) {
315 $low = CRM_Utils_Request::retrieveValue($fieldName . '_low', 'Timestamp', NULL, NULL, 'GET');
316 $high = CRM_Utils_Request::retrieveValue($fieldName . '_high', 'Timestamp', NULL, NULL, 'GET');
317 if ($low !== NULL || $high !== NULL) {
318 $defaults[$fieldName . '_relative'] = 0;
319 $defaults[$fieldName . '_low'] = $low ? date('Y-m-d H:i:s', strtotime($low)) : NULL;
320 $defaults[$fieldName . '_high'] = $high ? date('Y-m-d H:i:s', strtotime($high)) : NULL;
321 }
322 else {
323 $relative = CRM_Utils_Request::retrieveValue($fieldName . '_relative', 'String', NULL, NULL, 'GET');
324 if (!empty($relative) && isset(CRM_Core_OptionGroup::values('relative_date_filters')[$relative])) {
325 $defaults[$fieldName . '_relative'] = $relative;
326 }
327 }
328 }
329 }
330 }
331 return $defaults;
332 }
333
334 /**
335 * Convert any submitted text fields to use 'like' rather than '=' as the operator.
336 *
337 * This excludes any with options.
338 *
339 * Note this will only pick up fields declared via metadata.
340 */
341 protected function convertTextStringsToUseLikeOperator() {
342 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
343 foreach ($fields as $fieldName => $field) {
344 if (!empty($this->_formValues[$fieldName]) && empty($field['options']) && empty($field['pseudoconstant'])) {
345 if (in_array($field['type'], [CRM_Utils_Type::T_STRING, CRM_Utils_Type::T_TEXT])) {
346 $this->_formValues[$fieldName] = ['LIKE' => CRM_Contact_BAO_Query::getWildCardedValue(TRUE, 'LIKE', trim($this->_formValues[$fieldName]))];
347 }
348 }
349 }
350 }
351 }
352
353 /**
354 * Add checkboxes for each row plus a master checkbox.
355 *
356 * @param array $rows
357 */
358 public function addRowSelectors($rows) {
359 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
360 if (!empty($rows)) {
361 foreach ($rows as $row) {
362 if (!empty($row['checkbox'])) {
363 $this->addElement('checkbox', $row['checkbox'], NULL, NULL, ['class' => 'select-row']);
364 }
365 }
366 }
367 }
368
369 /**
370 * Add actions menu to search results form.
371 *
372 * @param array $tasks
373 */
374 public function addTaskMenu($tasks) {
375 $taskMetaData = [];
376 foreach ($tasks as $key => $task) {
377 $taskMetaData[$key] = ['title' => $task];
378 }
379 parent::addTaskMenu($taskMetaData);
380 }
381
382 /**
383 * Add the sort-name field to the form.
384 *
385 * There is a setting to determine whether email is included in the search & we look this up to determine
386 * which text to choose.
387 *
388 * Note that for translation purposes the full string works better than using 'prefix' hence we use override-able functions
389 * to define the string.
390 *
391 * @throws \CiviCRM_API3_Exception
392 */
393 protected function addSortNameField() {
394 $title = civicrm_api3('setting', 'getvalue', ['name' => 'includeEmailInName', 'group' => 'Search Preferences']) ? $this->getSortNameLabelWithEmail() : $this->getSortNameLabelWithOutEmail();
395 $this->addElement(
396 'text',
397 'sort_name',
398 $title,
399 CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')
400 );
401 $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]);
402 }
403
404 /**
405 * Get the label for the sortName field if email searching is on.
406 *
407 * (email searching is a setting under search preferences).
408 *
409 * @return string
410 */
411 protected function getSortNameLabelWithEmail() {
412 return ts('Name or Email');
413 }
414
415 /**
416 * Get the label for the sortName field if email searching is off.
417 *
418 * (email searching is a setting under search preferences).
419 *
420 * @return string
421 */
422 protected function getSortNameLabelWithOutEmail() {
423 return ts('Name');
424 }
425
426 /**
427 * Explicitly declare the form context for addField().
428 */
429 public function getDefaultContext() {
430 return 'search';
431 }
432
433 /**
434 * Add generic fields that specify the contact.
435 *
436 * @throws \CiviCRM_API3_Exception
437 */
438 protected function addContactSearchFields() {
439 if (!$this->isFormInViewOrEditMode()) {
440 return;
441 }
442 $this->addSortNameField();
443
444 $this->_group = CRM_Core_PseudoConstant::nestedGroup();
445 if ($this->_group) {
446 $this->add('select', 'group', $this->getGroupLabel(), $this->_group, FALSE,
447 [
448 'id' => 'group',
449 'multiple' => 'multiple',
450 'class' => 'crm-select2',
451 ]
452 );
453 }
454
455 $contactTags = CRM_Core_BAO_Tag::getTags();
456 if ($contactTags) {
457 $this->add('select', 'contact_tags', $this->getTagLabel(), $contactTags, FALSE,
458 [
459 'id' => 'contact_tags',
460 'multiple' => 'multiple',
461 'class' => 'crm-select2',
462 ]
463 );
464 }
465 $this->addField('contact_type', ['entity' => 'Contact']);
466
467 if (CRM_Core_Permission::check('access deleted contacts') && Civi::settings()->get('contact_undelete')) {
468 $this->addElement('checkbox', 'deleted_contacts', ts('Search in Trash') . '<br />' . ts('(deleted contacts)'));
469 }
470
471 }
472
473 /**
474 * Get the label for the group field.
475 *
476 * @return string
477 */
478 protected function getGroupLabel() {
479 return ts('Group(s)');
480 }
481
482 /**
483 * Get the label for the tag field.
484 *
485 * We do this in a function so the 'ts' wraps the whole string to allow
486 * better translation.
487 *
488 * @return string
489 */
490 protected function getTagLabel() {
491 return ts('Tag(s)');
492 }
493
494 /**
495 * we allow the controller to set force/reset externally, useful when we are being
496 * driven by the wizard framework
497 *
498 * @throws \CRM_Core_Exception
499 */
500 protected function loadStandardSearchOptionsFromUrl() {
501 $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
502 $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
503 $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
504 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'search');
505 $this->_ssID = CRM_Utils_Request::retrieve('ssID', 'Positive', $this);
506 $this->assign("context", $this->_context);
507 }
508
509 /**
510 * Get user submitted values.
511 *
512 * Get it from controller only if form has been submitted, else preProcess has set this
513 */
514 protected function loadFormValues() {
515 if (!empty($_POST) && !$this->controller->isModal()) {
516 $this->_formValues = $this->controller->exportValues($this->_name);
517 }
518 else {
519 $this->_formValues = $this->get('formValues');
520 }
521
522 if (empty($this->_formValues)) {
523 if (isset($this->_ssID)) {
524 $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
525 }
526 }
527 }
528
529 /**
530 * Get the form values.
531 *
532 * @todo consolidate with loadFormValues()
533 *
534 * @return array
535 *
536 * @throws \CRM_Core_Exception
537 */
538 protected function getFormValues() {
539 if (!empty($_POST) && !$this->_force) {
540 return $this->controller->exportValues($this->_name);
541 }
542 if ($this->_force) {
543 return $this->setDefaultValues();
544 }
545 return (array) $this->get('formValues');
546 }
547
548 /**
549 * Get the string processed to determine sort order.
550 *
551 * This looks like 'sort_name_u' for Sort name ascending.
552 *
553 * @return string|null
554 */
555 protected function getSortID() {
556 if ($this->get(CRM_Utils_Sort::SORT_ID)) {
557 return CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
558 $this->get(CRM_Utils_Sort::SORT_DIRECTION)
559 );
560 }
561 return NULL;
562 }
563
564 /**
565 * Set the metadata for the form.
566 *
567 * @throws \CiviCRM_API3_Exception
568 */
569 protected function setSearchMetadata() {}
570
571 /**
572 * Handle force=1 in the url.
573 *
574 * Search field metadata is normally added in buildForm but we are bypassing that in this flow
575 * (I've always found the flow kinda confusing & perhaps that is the problem but this mitigates)
576 *
577 * @throws \CiviCRM_API3_Exception
578 */
579 protected function handleForcedSearch() {
580 $this->setSearchMetadata();
581 $this->addContactSearchFields();
582 $this->postProcess();
583 $this->set('force', 0);
584 }
585
586 }