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();
126 * This virtual function is used to set the default values of various form elements.
129 * reference to the array of default values
130 * @throws \CRM_Core_Exception
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);
144 * Set the form values based on input and preliminary processing.
146 * @throws \CRM_Core_Exception
148 protected function setFormValues() {
149 $this->_formValues
= $this->getFormValues();
150 $this->set('formValues', $this->_formValues
);
151 $this->convertTextStringsToUseLikeOperator();
155 * Common buildForm tasks required by all searches.
157 * @throws \CRM_Core_Exception
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');
167 'name' => ts('Search'),
172 $this->addClass('crm-search-form');
174 $tasks = $this->buildTaskList();
175 $this->addTaskMenu($tasks);
179 * Add any fields described in metadata to the form.
181 * The goal is to describe all fields in metadata and handle from metadata rather
182 * than existing ad hoc handling.
184 * @throws \CiviCRM_API3_Exception
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
));
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'];
205 elseif (isset($fields[$fieldName]['title'])) {
206 $props['label'] = $fields[$fieldName]['title'];
208 if (empty($fieldSpec['is_pseudofield'])) {
209 $this->addField($fieldName, $props);
217 * Global validation rules for the form.
219 * @param array $fields
220 * Posted values of the form.
221 * @param array $files
222 * @param object $form
225 * list of errors to be posted back to the form
227 public static function formRule($fields, $files, $form) {
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.
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']]);
249 * Get the validation rule to apply to a function.
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.
254 * @param string $entity
255 * @param string $fieldName
259 protected function getValidationTypeForField($entity, $fieldName) {
260 switch ($this->getSearchFieldMetadata()[$entity][$fieldName]['type']) {
261 case CRM_Utils_Type
::T_BOOLEAN
:
264 case CRM_Utils_Type
::T_INT
:
265 return 'CommaSeparatedIntegers';
267 case CRM_Utils_Type
::T_DATE
:
268 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
272 return 'Alphanumeric';
277 * Get the defaults for the entity for any fields described in metadata.
279 * @param string $entity
283 * @throws \CRM_Core_Exception
285 protected function getEntityDefaults($entity) {
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);
295 $defaults[$fieldName] = $value;
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;
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;
319 * Convert any submitted text fields to use 'like' rather than '=' as the operator.
321 * This excludes any with options.
323 * Note this will only pick up fields declared via metadata.
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]))];
338 * Add checkboxes for each row plus a master checkbox.
342 public function addRowSelectors($rows) {
343 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
345 foreach ($rows as $row) {
346 if (!empty($row['checkbox'])) {
347 $this->addElement('checkbox', $row['checkbox'], NULL, NULL, ['class' => 'select-row']);
354 * Add actions menu to search results form.
356 * @param array $tasks
358 public function addTaskMenu($tasks) {
360 foreach ($tasks as $key => $task) {
361 $taskMetaData[$key] = ['title' => $task];
363 parent
::addTaskMenu($taskMetaData);
367 * Add the sort-name field to the form.
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.
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.
375 * @throws \CiviCRM_API3_Exception
377 protected function addSortNameField() {
378 $title = civicrm_api3('setting', 'getvalue', ['name' => 'includeEmailInName', 'group' => 'Search Preferences']) ?
$this->getSortNameLabelWithEmail() : $this->getSortNameLabelWithOutEmail();
383 CRM_Core_DAO
::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')
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
]);
389 * Get the label for the sortName field if email searching is on.
391 * (email searching is a setting under search preferences).
395 protected function getSortNameLabelWithEmail() {
396 return ts('Name or Email');
400 * Get the label for the sortName field if email searching is off.
402 * (email searching is a setting under search preferences).
406 protected function getSortNameLabelWithOutEmail() {
411 * Explicitly declare the form context for addField().
413 public function getDefaultContext() {
418 * Add generic fields that specify the contact.
420 * @throws \CiviCRM_API3_Exception
422 protected function addContactSearchFields() {
423 if (!$this->isFormInViewOrEditMode()) {
426 $this->addSortNameField();
427 if ($this->sortNameOnly
) {
431 $this->_group
= CRM_Core_PseudoConstant
::nestedGroup();
433 $this->add('select', 'group', $this->getGroupLabel(), $this->_group
, FALSE,
436 'multiple' => 'multiple',
437 'class' => 'crm-select2',
440 $this->searchFieldMetadata
['Contact']['group'] = ['name' => 'group', 'type' => CRM_Utils_Type
::T_INT
, 'is_pseudofield' => TRUE, 'html' => ['type' => 'Select']];
443 $contactTags = CRM_Core_BAO_Tag
::getTags();
445 $this->add('select', 'contact_tags', $this->getTagLabel(), $contactTags, FALSE,
447 'id' => 'contact_tags',
448 'multiple' => 'multiple',
449 'class' => 'crm-select2',
453 $this->searchFieldMetadata
['Contact']['contact_tags'] = ['name' => 'contact_tags', 'type' => CRM_Utils_Type
::T_INT
, 'is_pseudofield' => TRUE, 'html' => ['type' => 'Select']];
454 $this->addField('contact_type', ['entity' => 'Contact']);
455 $this->searchFieldMetadata
['Contact']['contact_type'] = CRM_Contact_DAO_Contact
::fields()['contact_type'];
457 if (CRM_Core_Permission
::check('access deleted contacts') && Civi
::settings()->get('contact_undelete')) {
458 $this->addElement('checkbox', 'deleted_contacts', ts('Search in Trash') . '<br />' . ts('(deleted contacts)'));
459 $this->searchFieldMetadata
['Contact']['deleted_contacts'] = ['name' => 'deleted_contacts', 'type' => CRM_Utils_Type
::T_INT
, 'is_pseudofield' => TRUE, 'html' => ['type' => 'Checkbox']];
465 * Get the label for the group field.
469 protected function getGroupLabel() {
470 return ts('Group(s)');
474 * Get the label for the tag field.
476 * We do this in a function so the 'ts' wraps the whole string to allow
477 * better translation.
481 protected function getTagLabel() {
486 * we allow the controller to set force/reset externally, useful when we are being
487 * driven by the wizard framework
489 * @throws \CRM_Core_Exception
491 protected function loadStandardSearchOptionsFromUrl() {
492 $this->_reset
= CRM_Utils_Request
::retrieve('reset', 'Boolean');
493 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean', $this, FALSE);
494 $this->_limit
= CRM_Utils_Request
::retrieve('limit', 'Positive', $this);
495 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this, FALSE, 'search');
496 $this->_ssID
= CRM_Utils_Request
::retrieve('ssID', 'Positive', $this);
497 $this->assign("context", $this->_context
);
501 * Get user submitted values.
503 * Get it from controller only if form has been submitted, else preProcess has set this
505 protected function loadFormValues() {
506 if (!empty($_POST) && !$this->controller
->isModal()) {
507 $this->_formValues
= $this->controller
->exportValues($this->_name
);
510 $this->_formValues
= $this->get('formValues');
513 if (empty($this->_formValues
)) {
514 if (isset($this->_ssID
)) {
515 $this->_formValues
= CRM_Contact_BAO_SavedSearch
::getFormValues($this->_ssID
);
521 * Get the form values.
523 * @todo consolidate with loadFormValues()
527 * @throws \CRM_Core_Exception
529 protected function getFormValues() {
530 if (!empty($_POST) && !$this->_force
) {
531 return $this->controller
->exportValues($this->_name
);
534 return $this->setDefaultValues();
536 return (array) $this->get('formValues');
540 * Get the string processed to determine sort order.
542 * This looks like 'sort_name_u' for Sort name ascending.
544 * @return string|null
546 protected function getSortID() {
547 if ($this->get(CRM_Utils_Sort
::SORT_ID
)) {
548 return CRM_Utils_Sort
::sortIDValue($this->get(CRM_Utils_Sort
::SORT_ID
),
549 $this->get(CRM_Utils_Sort
::SORT_DIRECTION
)
556 * Set the metadata for the form.
558 * @throws \CiviCRM_API3_Exception
560 protected function setSearchMetadata() {}
563 * Handle force=1 in the url.
565 * Search field metadata is normally added in buildForm but we are bypassing that in this flow
566 * (I've always found the flow kinda confusing & perhaps that is the problem but this mitigates)
568 * @throws \CiviCRM_API3_Exception
570 protected function handleForcedSearch() {
571 $this->setSearchMetadata();
572 $this->addContactSearchFields();
573 $this->postProcess();
574 $this->set('force', 0);