3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * Base class for most search forms
31 class CRM_Core_Form_Search
extends CRM_Core_Form
{
34 * Are we forced to run a search
41 * Name of search button
45 protected $_searchButtonName;
48 * Name of action button
52 protected $_actionButtonName;
55 * Form values that we will be using
62 * Have we already done this search
69 * What context are we being invoked from
76 * The list of tasks or actions that a searcher can perform on a result set.
80 protected $_taskList = [];
83 * Declare entity reference fields as they will need to be converted.
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.
90 protected $entityReferenceFields = [];
93 * Builds the list of tasks or actions that a searcher can perform on a result set.
95 * To modify the task list, child classes should alter $this->_taskList,
96 * preferably by extending this method.
100 protected function buildTaskList() {
101 return $this->_taskList
;
105 * Metadata for fields on the search form.
107 * Instantiate with empty array for contact to prevent e-notices.
111 protected $searchFieldMetadata = ['Contact' => []];
116 public function getSearchFieldMetadata() {
117 return $this->searchFieldMetadata
;
121 * @param array $searchFieldMetadata
123 public function addSearchFieldMetadata($searchFieldMetadata) {
124 $this->searchFieldMetadata
= array_merge($this->searchFieldMetadata
, $searchFieldMetadata);
128 * Prepare for search by loading options from the url, handling force searches, retrieving form values.
130 * @throws \CRM_Core_Exception
131 * @throws \CiviCRM_API3_Exception
133 public function preProcess() {
134 $this->loadStandardSearchOptionsFromUrl();
136 $this->handleForcedSearch();
138 $this->_formValues
= $this->getFormValues();
142 * This virtual function is used to set the default values of various form elements.
145 * reference to the array of default values
146 * @throws \CRM_Core_Exception
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);
160 * Set the form values based on input and preliminary processing.
164 protected function setFormValues() {
165 $this->_formValues
= $this->getFormValues();
166 $this->set('formValues', $this->_formValues
);
167 $this->convertTextStringsToUseLikeOperator();
171 * Common buildForm tasks required by all searches.
173 * @throws \CRM_Core_Exception
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');
183 'name' => ts('Search'),
188 $this->addClass('crm-search-form');
190 $tasks = $this->buildTaskList();
191 $this->addTaskMenu($tasks);
195 * Add any fields described in metadata to the form.
197 * The goal is to describe all fields in metadata and handle from metadata rather
198 * than existing ad hoc handling.
200 * @throws \CiviCRM_API3_Exception
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
));
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'];
221 elseif (isset($fields[$fieldName]['title'])) {
222 $props['label'] = $fields[$fieldName]['title'];
224 if (empty($fieldSpec['is_pseudofield'])) {
225 $this->addField($fieldName, $props);
233 * Global validation rules for the form.
235 * @param array $fields
236 * Posted values of the form.
237 * @param array $files
238 * @param object $form
241 * list of errors to be posted back to the form
243 public static function formRule($fields, $files, $form) {
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.
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']]);
265 * Get the validation rule to apply to a function.
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.
270 * @param string $entity
271 * @param string $fieldName
275 protected function getValidationTypeForField($entity, $fieldName) {
276 switch ($this->getSearchFieldMetadata()[$entity][$fieldName]['type']) {
277 case CRM_Utils_Type
::T_BOOLEAN
:
280 case CRM_Utils_Type
::T_INT
:
281 return 'CommaSeparatedIntegers';
283 case CRM_Utils_Type
::T_DATE
:
284 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
288 return 'Alphanumeric';
293 * Get the defaults for the entity for any fields described in metadata.
295 * @param string $entity
299 * @throws \CRM_Core_Exception
301 protected function getEntityDefaults($entity) {
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 $defaults[$fieldName] = $value;
309 if ($fieldSpec['type'] === CRM_Utils_Type
::T_DATE ||
($fieldSpec['type'] === CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
)) {
310 $low = CRM_Utils_Request
::retrieveValue($fieldName . '_low', 'Timestamp', NULL, NULL, 'GET');
311 $high = CRM_Utils_Request
::retrieveValue($fieldName . '_high', 'Timestamp', NULL, NULL, 'GET');
312 if ($low !== NULL ||
$high !== NULL) {
313 $defaults[$fieldName . '_relative'] = 0;
314 $defaults[$fieldName . '_low'] = $low ?
date('Y-m-d H:i:s', strtotime($low)) : NULL;
315 $defaults[$fieldName . '_high'] = $high ?
date('Y-m-d H:i:s', strtotime($high)) : NULL;
318 $relative = CRM_Utils_Request
::retrieveValue($fieldName . '_relative', 'String', NULL, NULL, 'GET');
319 if (!empty($relative) && isset(CRM_Core_OptionGroup
::values('relative_date_filters')[$relative])) {
320 $defaults[$fieldName . '_relative'] = $relative;
330 * Convert any submitted text fields to use 'like' rather than '=' as the operator.
332 * This excludes any with options.
334 * Note this will only pick up fields declared via metadata.
336 protected function convertTextStringsToUseLikeOperator() {
337 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
338 foreach ($fields as $fieldName => $field) {
339 if (!empty($this->_formValues
[$fieldName]) && empty($field['options']) && empty($field['pseudoconstant'])) {
340 if (in_array($field['type'], [CRM_Utils_Type
::T_STRING
, CRM_Utils_Type
::T_TEXT
])) {
341 $this->_formValues
[$fieldName] = ['LIKE' => CRM_Contact_BAO_Query
::getWildCardedValue(TRUE, 'LIKE', trim($this->_formValues
[$fieldName]))];
349 * Add checkboxes for each row plus a master checkbox.
353 public function addRowSelectors($rows) {
354 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
356 foreach ($rows as $row) {
357 if (!empty($row['checkbox'])) {
358 $this->addElement('checkbox', $row['checkbox'], NULL, NULL, ['class' => 'select-row']);
365 * Add actions menu to search results form.
367 * @param array $tasks
369 public function addTaskMenu($tasks) {
371 foreach ($tasks as $key => $task) {
372 $taskMetaData[$key] = ['title' => $task];
374 parent
::addTaskMenu($taskMetaData);
378 * Add the sort-name field to the form.
380 * There is a setting to determine whether email is included in the search & we look this up to determine
381 * which text to choose.
383 * Note that for translation purposes the full string works better than using 'prefix' hence we use override-able functions
384 * to define the string.
386 * @throws \CiviCRM_API3_Exception
388 protected function addSortNameField() {
389 $title = civicrm_api3('setting', 'getvalue', ['name' => 'includeEmailInName', 'group' => 'Search Preferences']) ?
$this->getSortNameLabelWithEmail() : $this->getSortNameLabelWithOutEmail();
394 CRM_Core_DAO
::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')
396 $this->searchFieldMetadata
['Contact']['sort_name'] = ['name' => 'sort_name', 'title' => $title, 'type' => CRM_Utils_Type
::T_STRING
];
400 * Get the label for the sortName field if email searching is on.
402 * (email searching is a setting under search preferences).
406 protected function getSortNameLabelWithEmail() {
407 return ts('Name or Email');
411 * Get the label for the sortName field if email searching is off.
413 * (email searching is a setting under search preferences).
417 protected function getSortNameLabelWithOutEmail() {
422 * Explicitly declare the form context for addField().
424 public function getDefaultContext() {
429 * Add generic fields that specify the contact.
431 * @throws \CiviCRM_API3_Exception
433 protected function addContactSearchFields() {
434 if (!$this->isFormInViewOrEditMode()) {
437 $this->addSortNameField();
439 $this->_group
= CRM_Core_PseudoConstant
::nestedGroup();
441 $this->add('select', 'group', $this->getGroupLabel(), $this->_group
, FALSE,
444 'multiple' => 'multiple',
445 'class' => 'crm-select2',
450 $contactTags = CRM_Core_BAO_Tag
::getTags();
452 $this->add('select', 'contact_tags', $this->getTagLabel(), $contactTags, FALSE,
454 'id' => 'contact_tags',
455 'multiple' => 'multiple',
456 'class' => 'crm-select2',
460 $this->addField('contact_type', ['entity' => 'Contact']);
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)'));
469 * Get the label for the group field.
473 protected function getGroupLabel() {
474 return ts('Group(s)');
478 * Get the label for the tag field.
480 * We do this in a function so the 'ts' wraps the whole string to allow
481 * better translation.
485 protected function getTagLabel() {
490 * we allow the controller to set force/reset externally, useful when we are being
491 * driven by the wizard framework
493 * @throws \CRM_Core_Exception
495 protected function loadStandardSearchOptionsFromUrl() {
496 $this->_reset
= CRM_Utils_Request
::retrieve('reset', 'Boolean');
497 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean', $this, FALSE);
498 $this->_limit
= CRM_Utils_Request
::retrieve('limit', 'Positive', $this);
499 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this, FALSE, 'search');
500 $this->_ssID
= CRM_Utils_Request
::retrieve('ssID', 'Positive', $this);
501 $this->assign("context", $this->_context
);
505 * Get user submitted values.
507 * Get it from controller only if form has been submitted, else preProcess has set this
509 protected function loadFormValues() {
510 if (!empty($_POST) && !$this->controller
->isModal()) {
511 $this->_formValues
= $this->controller
->exportValues($this->_name
);
514 $this->_formValues
= $this->get('formValues');
517 if (empty($this->_formValues
)) {
518 if (isset($this->_ssID
)) {
519 $this->_formValues
= CRM_Contact_BAO_SavedSearch
::getFormValues($this->_ssID
);
525 * Get the form values.
527 * @todo consolidate with loadFormValues()
531 * @throws \CRM_Core_Exception
533 protected function getFormValues() {
534 if (!empty($_POST) && !$this->_force
) {
535 return $this->controller
->exportValues($this->_name
);
538 return $this->setDefaultValues();
540 return (array) $this->get('formValues');
544 * Get the string processed to determine sort order.
546 * This looks like 'sort_name_u' for Sort name ascending.
548 * @return string|null
550 protected function getSortID() {
551 if ($this->get(CRM_Utils_Sort
::SORT_ID
)) {
552 return CRM_Utils_Sort
::sortIDValue($this->get(CRM_Utils_Sort
::SORT_ID
),
553 $this->get(CRM_Utils_Sort
::SORT_DIRECTION
)
560 * Set the metadata for the form.
562 * @throws \CiviCRM_API3_Exception
564 protected function setSearchMetadata() {}
567 * Handle force=1 in the url.
569 * Search field metadata is normally added in buildForm but we are bypassing that in this flow
570 * (I've always found the flow kinda confusing & perhaps that is the problem but this mitigates)
572 * @throws \CiviCRM_API3_Exception
574 protected function handleForcedSearch() {
575 $this->setSearchMetadata();
576 $this->addContactSearchFields();
577 $this->postProcess();
578 $this->set('force', 0);