3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
13 * Base class for most search forms
15 class CRM_Core_Form_Search
extends CRM_Core_Form
{
18 * Are we forced to run a search
25 * Name of action button
29 protected $_actionButtonName;
32 * Form values that we will be using
39 * Have we already done this search
46 * What context are we being invoked from
53 * The list of tasks or actions that a searcher can perform on a result set.
57 protected $_taskList = [];
60 * Declare entity reference fields as they will need to be converted.
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.
67 protected $entityReferenceFields = [];
70 * Builds the list of tasks or actions that a searcher can perform on a result set.
72 * To modify the task list, child classes should alter $this->_taskList,
73 * preferably by extending this method.
77 protected function buildTaskList() {
78 return $this->_taskList
;
82 * Should we be adding all the metadata for contact search fields or just for the sort name.
86 protected $sortNameOnly = FALSE;
89 * Metadata for fields on the search form.
91 * Instantiate with empty array for contact to prevent e-notices.
95 protected $searchFieldMetadata = ['Contact' => []];
100 public function getSearchFieldMetadata() {
101 return $this->searchFieldMetadata
;
105 * @param array $searchFieldMetadata
107 public function addSearchFieldMetadata($searchFieldMetadata) {
108 $this->searchFieldMetadata
= array_merge($this->searchFieldMetadata
, $searchFieldMetadata);
112 * Prepare for search by loading options from the url, handling force searches, retrieving form values.
114 * @throws \CRM_Core_Exception
115 * @throws \CiviCRM_API3_Exception
117 public function preProcess() {
118 $this->loadStandardSearchOptionsFromUrl();
120 $this->handleForcedSearch();
122 $this->_formValues
= $this->getFormValues();
123 // For searchResultsTasks.tpl.
124 $this->addExpectedSmartyVariables(['savedSearch', 'selectorLabel']);
128 * This virtual function is used to set the default values of various form elements.
131 * reference to the array of default values
132 * @throws \CRM_Core_Exception
134 public function setDefaultValues() {
135 // Use the form values stored to the form. Ideally 'formValues'
136 // would remain 'pure' & another array would be wrangled.
137 // We don't do that - so we want the version of formValues stored early on.
138 $defaults = (array) $this->get('formValues');
139 foreach (array_keys($this->getSearchFieldMetadata()) as $entity) {
140 $defaults = array_merge($this->getEntityDefaults($entity), $defaults);
146 * Set the form values based on input and preliminary processing.
148 * @throws \CRM_Core_Exception
150 protected function setFormValues() {
151 $this->_formValues
= $this->getFormValues();
152 $this->set('formValues', $this->_formValues
);
153 $this->convertTextStringsToUseLikeOperator();
157 * Common buildForm tasks required by all searches.
159 * @throws \CRM_Core_Exception
161 public function buildQuickForm() {
162 CRM_Core_Resources
::singleton()
163 ->addScriptFile('civicrm', 'js/crm.searchForm.js', 1, 'html-header')
164 ->addStyleFile('civicrm', 'css/searchForm.css', 1, 'html-header');
169 'name' => ts('Search'),
174 $this->addClass('crm-search-form');
176 $tasks = $this->buildTaskList();
177 $this->addTaskMenu($tasks);
181 * Add any fields described in metadata to the form.
183 * The goal is to describe all fields in metadata and handle from metadata rather
184 * than existing ad hoc handling.
186 * @throws \CiviCRM_API3_Exception
188 public function addFormFieldsFromMetadata() {
189 $this->addFormRule(['CRM_Core_Form_Search', 'formRule'], $this);
190 $this->_action
= CRM_Core_Action
::ADVANCED
;
191 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
192 foreach ($fields as $fieldName => $fieldSpec) {
193 $fieldType = $fieldSpec['type'] ??
'';
194 if ($fieldType === CRM_Utils_Type
::T_DATE ||
$fieldType === (CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) ||
$fieldType === CRM_Utils_Type
::T_TIMESTAMP
) {
195 $title = empty($fieldSpec['unique_title']) ?
$fieldSpec['title'] : $fieldSpec['unique_title'];
196 $this->addDatePickerRange($fieldName, $title, ($fieldType === (CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) ||
$fieldType === CRM_Utils_Type
::T_TIMESTAMP
));
199 // Not quite sure about moving to a mix of keying by entity vs permitting entity to
200 // be passed in. The challenge of the former is that it doesn't permit ordering.
201 // Perhaps keying was the wrong starting point & we should do a flat array as all
202 // fields eventually need to be unique.
203 $props = ['entity' => $fieldSpec['entity'] ??
$entity];
204 if (isset($fields[$fieldName]['unique_title'])) {
205 $props['label'] = $fields[$fieldName]['unique_title'];
207 elseif (isset($fields[$fieldName]['html']['label'])) {
208 $props['label'] = $fields[$fieldName]['html']['label'];
210 elseif (isset($fields[$fieldName]['title'])) {
211 $props['label'] = $fields[$fieldName]['title'];
213 if (empty($fieldSpec['is_pseudofield'])) {
214 $this->addField($fieldName, $props);
222 * Global validation rules for the form.
224 * @param array $fields
225 * Posted values of the form.
226 * @param array $files
227 * @param object $form
230 * list of errors to be posted back to the form
232 public static function formRule($fields, $files, $form) {
234 if (!is_a($form, 'CRM_Core_Form_Search')) {
235 // So this gets hit with a form object when doing an activity date search from
236 // advanced search, but a NULL object when doing a pledge search.
239 foreach ($form->getSearchFieldMetadata() as $entity => $spec) {
240 foreach ($spec as $fieldName => $fieldSpec) {
241 if ($fieldSpec['type'] === CRM_Utils_Type
::T_DATE ||
$fieldSpec['type'] === (CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
)) {
242 if (!empty($fields[$fieldName . '_high']) && !empty($fields[$fieldName . '_low']) && empty($fields[$fieldName . '_relative'])) {
243 if (strtotime($fields[$fieldName . '_low']) > strtotime($fields[$fieldName . '_high'])) {
244 $errors[$fieldName . '_low'] = ts('%1: Please check that your date range is in correct chronological order.', [1 => $fieldSpec['title']]);
254 * Get the validation rule to apply to a function.
256 * Alphanumeric is designed to always be safe & for now we just return
257 * that but in future we can use tighter rules for types like int, bool etc.
259 * @param string $entity
260 * @param string $fieldName
264 protected function getValidationTypeForField($entity, $fieldName) {
265 switch ($this->getSearchFieldMetadata()[$entity][$fieldName]['type']) {
266 case CRM_Utils_Type
::T_BOOLEAN
:
269 case CRM_Utils_Type
::T_INT
:
270 return 'CommaSeparatedIntegers';
272 case CRM_Utils_Type
::T_DATE
:
273 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
277 return 'Alphanumeric';
282 * Get the defaults for the entity for any fields described in metadata.
284 * @param string $entity
288 * @throws \CRM_Core_Exception
290 protected function getEntityDefaults($entity) {
292 foreach (CRM_Utils_Array
::value($entity, $this->getSearchFieldMetadata(), []) as $fieldName => $fieldSpec) {
293 if (empty($_POST[$fieldName])) {
294 $value = CRM_Utils_Request
::retrieveValue($fieldName, $this->getValidationTypeForField($entity, $fieldName), NULL, NULL, 'GET');
295 if ($value !== NULL) {
296 if ($fieldSpec['html']['type'] === 'Select') {
297 $defaults[$fieldName] = explode(',', $value);
300 $defaults[$fieldName] = $value;
303 if ($fieldSpec['type'] === CRM_Utils_Type
::T_DATE ||
($fieldSpec['type'] === CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
)) {
304 $low = CRM_Utils_Request
::retrieveValue($fieldName . '_low', 'Timestamp', NULL, NULL, 'GET');
305 $high = CRM_Utils_Request
::retrieveValue($fieldName . '_high', 'Timestamp', NULL, NULL, 'GET');
306 if ($low !== NULL ||
$high !== NULL) {
307 $defaults[$fieldName . '_relative'] = 0;
308 $defaults[$fieldName . '_low'] = $low ?
date('Y-m-d H:i:s', strtotime($low)) : NULL;
309 $defaults[$fieldName . '_high'] = $high ?
date('Y-m-d H:i:s', strtotime($high)) : NULL;
312 $relative = CRM_Utils_Request
::retrieveValue($fieldName . '_relative', 'String', NULL, NULL, 'GET');
313 if (!empty($relative) && isset(CRM_Core_OptionGroup
::values('relative_date_filters')[$relative])) {
314 $defaults[$fieldName . '_relative'] = $relative;
324 * Convert any submitted text fields to use 'like' rather than '=' as the operator.
326 * This excludes any with options.
328 * Note this will only pick up fields declared via metadata.
330 protected function convertTextStringsToUseLikeOperator() {
331 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
332 foreach ($fields as $fieldName => $field) {
333 if (!empty($this->_formValues
[$fieldName]) && empty($field['options']) && empty($field['pseudoconstant'])) {
334 if (in_array($field['type'], [CRM_Utils_Type
::T_STRING
, CRM_Utils_Type
::T_TEXT
])) {
335 $this->_formValues
[$fieldName] = ['LIKE' => CRM_Contact_BAO_Query
::getWildCardedValue(TRUE, 'LIKE', trim($this->_formValues
[$fieldName]))];
343 * Add checkboxes for each row plus a master checkbox.
347 public function addRowSelectors($rows) {
348 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
350 foreach ($rows as $row) {
351 if (!empty($row['checkbox'])) {
352 $this->addElement('checkbox', $row['checkbox'], NULL, NULL, ['class' => 'select-row']);
359 * Add actions menu to search results form.
361 * @param array $tasks
363 public function addTaskMenu($tasks) {
365 foreach ($tasks as $key => $task) {
366 $taskMetaData[$key] = ['title' => $task];
368 parent
::addTaskMenu($taskMetaData);
372 * Add the sort-name field to the form.
374 * There is a setting to determine whether email is included in the search & we look this up to determine
375 * which text to choose.
377 * Note that for translation purposes the full string works better than using 'prefix' hence we use override-able functions
378 * to define the string.
380 * @throws \CiviCRM_API3_Exception
382 protected function addSortNameField() {
383 $title = civicrm_api3('setting', 'getvalue', ['name' => 'includeEmailInName', 'group' => 'Search Preferences']) ?
$this->getSortNameLabelWithEmail() : $this->getSortNameLabelWithOutEmail();
388 CRM_Core_DAO
::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')
390 $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
]);
394 * Get the label for the sortName field if email searching is on.
396 * (email searching is a setting under search preferences).
400 protected function getSortNameLabelWithEmail() {
401 return ts('Name or Email');
405 * Get the label for the sortName field if email searching is off.
407 * (email searching is a setting under search preferences).
411 protected function getSortNameLabelWithOutEmail() {
416 * Explicitly declare the form context for addField().
418 public function getDefaultContext() {
423 * Add generic fields that specify the contact.
425 * @throws \CiviCRM_API3_Exception
427 protected function addContactSearchFields() {
428 if (!$this->isFormInViewOrEditMode()) {
431 $this->addSortNameField();
432 if ($this->sortNameOnly
) {
436 $this->_group
= CRM_Core_PseudoConstant
::nestedGroup();
438 $this->add('select', 'group', $this->getGroupLabel(), $this->_group
, FALSE,
441 'multiple' => 'multiple',
442 'class' => 'crm-select2',
445 $this->searchFieldMetadata
['Contact']['group'] = ['name' => 'group', 'type' => CRM_Utils_Type
::T_INT
, 'is_pseudofield' => TRUE, 'html' => ['type' => 'Select']];
448 $contactTags = CRM_Core_BAO_Tag
::getTags();
450 $this->add('select', 'contact_tags', $this->getTagLabel(), $contactTags, FALSE,
452 'id' => 'contact_tags',
453 'multiple' => 'multiple',
454 'class' => 'crm-select2',
458 $this->searchFieldMetadata
['Contact']['contact_tags'] = ['name' => 'contact_tags', 'type' => CRM_Utils_Type
::T_INT
, 'is_pseudofield' => TRUE, 'html' => ['type' => 'Select']];
459 $this->addField('contact_type', ['entity' => 'Contact']);
460 $this->searchFieldMetadata
['Contact']['contact_type'] = CRM_Contact_DAO_Contact
::fields()['contact_type'];
462 if (CRM_Core_Permission
::check('access deleted contacts') && Civi
::settings()->get('contact_undelete')) {
463 $this->addElement('checkbox', 'deleted_contacts', ts('Search in Trash') . '<br />' . ts('(deleted contacts)'));
464 $this->searchFieldMetadata
['Contact']['deleted_contacts'] = ['name' => 'deleted_contacts', 'type' => CRM_Utils_Type
::T_INT
, 'is_pseudofield' => TRUE, 'html' => ['type' => 'Checkbox']];
470 * Get the label for the group field.
474 protected function getGroupLabel() {
475 return ts('Group(s)');
479 * Get the label for the tag field.
481 * We do this in a function so the 'ts' wraps the whole string to allow
482 * better translation.
486 protected function getTagLabel() {
491 * we allow the controller to set force/reset externally, useful when we are being
492 * driven by the wizard framework
494 * @throws \CRM_Core_Exception
496 protected function loadStandardSearchOptionsFromUrl() {
497 $this->_reset
= CRM_Utils_Request
::retrieve('reset', 'Boolean');
498 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean', $this, FALSE);
499 $this->_limit
= CRM_Utils_Request
::retrieve('limit', 'Positive', $this);
500 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this, FALSE, 'search');
501 $this->_ssID
= CRM_Utils_Request
::retrieve('ssID', 'Positive', $this);
502 $this->assign("context", $this->_context
);
506 * Get user submitted values.
508 * Get it from controller only if form has been submitted, else preProcess has set this
510 protected function loadFormValues() {
511 if (!empty($_POST) && !$this->controller
->isModal()) {
512 $this->_formValues
= $this->controller
->exportValues($this->_name
);
515 $this->_formValues
= $this->get('formValues');
518 if (empty($this->_formValues
)) {
519 if (isset($this->_ssID
)) {
520 $this->_formValues
= CRM_Contact_BAO_SavedSearch
::getFormValues($this->_ssID
);
526 * Get the form values.
528 * @todo consolidate with loadFormValues()
532 * @throws \CRM_Core_Exception
534 protected function getFormValues() {
535 if (!empty($_POST) && !$this->_force
) {
536 return $this->controller
->exportValues($this->_name
);
539 return $this->setDefaultValues();
541 return (array) $this->get('formValues');
545 * Get the string processed to determine sort order.
547 * This looks like 'sort_name_u' for Sort name ascending.
549 * @return string|null
551 protected function getSortID() {
552 if ($this->get(CRM_Utils_Sort
::SORT_ID
)) {
553 return CRM_Utils_Sort
::sortIDValue($this->get(CRM_Utils_Sort
::SORT_ID
),
554 $this->get(CRM_Utils_Sort
::SORT_DIRECTION
)
561 * Set the metadata for the form.
563 * @throws \CiviCRM_API3_Exception
565 protected function setSearchMetadata() {}
568 * Handle force=1 in the url.
570 * Search field metadata is normally added in buildForm but we are bypassing that in this flow
571 * (I've always found the flow kinda confusing & perhaps that is the problem but this mitigates)
573 * @throws \CiviCRM_API3_Exception
575 protected function handleForcedSearch() {
576 $this->setSearchMetadata();
577 $this->addContactSearchFields();
578 $this->postProcess();
579 $this->set('force', 0);