3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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
73 protected $_context = NULL;
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 * This virtual function is used to set the default values of various form elements.
131 * reference to the array of default values
134 public function setDefaultValues() {
135 $defaults = (array) $this->_formValues
;
136 foreach (['Contact', $this->getDefaultEntity()] as $entity) {
137 $defaults = array_merge($this->getEntityDefaults($entity), $defaults);
143 * Set the form values based on input and preliminary processing.
145 protected function setFormValues() {
146 if (!empty($_POST) && !$this->_force
) {
147 $this->_formValues
= $this->controller
->exportValues($this->_name
);
149 $this->convertTextStringsToUseLikeOperator();
153 * Common buildForm tasks required by all searches.
155 public function buildQuickForm() {
156 CRM_Core_Resources
::singleton()
157 ->addScriptFile('civicrm', 'js/crm.searchForm.js', 1, 'html-header')
158 ->addStyleFile('civicrm', 'css/searchForm.css', 1, 'html-header');
163 'name' => ts('Search'),
168 $this->addClass('crm-search-form');
170 $tasks = $this->buildTaskList();
171 $this->addTaskMenu($tasks);
175 * Add any fields described in metadata to the form.
177 * The goal is to describe all fields in metadata and handle from metadata rather
178 * than existing ad hoc handling.
180 public function addFormFieldsFromMetadata() {
181 $this->addFormRule(['CRM_Core_Form_Search', 'formRule'], $this);
182 $this->_action
= CRM_Core_Action
::ADVANCED
;
183 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
184 foreach ($fields as $fieldName => $fieldSpec) {
185 if ($fieldSpec['type'] === CRM_Utils_Type
::T_DATE ||
$fieldSpec['type'] === (CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
)) {
186 $title = empty($fieldSpec['unique_title']) ?
$fieldSpec['title'] : $fieldSpec['unique_title'];
187 $this->addDatePickerRange($fieldName, $title, ($fieldSpec['type'] === (CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
)));
190 $props = ['entity' => $entity];
191 if (isset($fields[$fieldName]['unique_title'])) {
192 $props['label'] = $fields[$fieldName]['unique_title'];
194 elseif (isset($fields[$fieldName]['title'])) {
195 $props['label'] = $fields[$fieldName]['title'];
197 if (empty($fieldSpec['is_pseudofield'])) {
198 $this->addField($fieldName, $props);
206 * Global validation rules for the form.
208 * @param array $fields
209 * Posted values of the form.
210 * @param array $files
211 * @param object $form
214 * list of errors to be posted back to the form
216 public static function formRule($fields, $files, $form) {
218 if (!is_a($form, 'CRM_Core_Form_Search')) {
219 // So this gets hit with a form object when doing an activity date search from
220 // advanced search, but a NULL object when doing a pledge search.
223 foreach ($form->getSearchFieldMetadata() as $entity => $spec) {
224 foreach ($spec as $fieldName => $fieldSpec) {
225 if ($fieldSpec['type'] === CRM_Utils_Type
::T_DATE ||
$fieldSpec['type'] === (CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
)) {
226 if (!empty($fields[$fieldName . '_high']) && !empty($fields[$fieldName . '_low']) && empty($fields[$fieldName . '_relative'])) {
227 if (strtotime($fields[$fieldName . '_low']) > strtotime($fields[$fieldName . '_high'])) {
228 $errors[$fieldName . '_low'] = ts('%1: Please check that your date range is in correct chronological order.', [1 => $fieldSpec['title']]);
238 * Get the validation rule to apply to a function.
240 * Alphanumeric is designed to always be safe & for now we just return
241 * that but in future we can use tighter rules for types like int, bool etc.
243 * @param string $entity
244 * @param string $fieldName
248 protected function getValidationTypeForField($entity, $fieldName) {
249 switch ($this->getSearchFieldMetadata()[$entity][$fieldName]['type']) {
250 case CRM_Utils_Type
::T_BOOLEAN
:
253 case CRM_Utils_Type
::T_INT
:
254 return 'CommaSeparatedIntegers';
256 case CRM_Utils_Type
::T_DATE
:
257 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
261 return 'Alphanumeric';
266 * Get the defaults for the entity for any fields described in metadata.
268 * @param string $entity
272 protected function getEntityDefaults($entity) {
274 foreach (CRM_Utils_Array
::value($entity, $this->getSearchFieldMetadata(), []) as $fieldName => $fieldSpec) {
275 if (empty($_POST[$fieldName])) {
276 $value = CRM_Utils_Request
::retrieveValue($fieldName, $this->getValidationTypeForField($entity, $fieldName), NULL, NULL, 'GET');
277 if ($value !== NULL) {
278 $defaults[$fieldName] = $value;
280 if ($fieldSpec['type'] === CRM_Utils_Type
::T_DATE ||
($fieldSpec['type'] === CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
)) {
281 $low = CRM_Utils_Request
::retrieveValue($fieldName . '_low', 'Timestamp', NULL, NULL, 'GET');
282 $high = CRM_Utils_Request
::retrieveValue($fieldName . '_high', 'Timestamp', NULL, NULL, 'GET');
283 if ($low !== NULL ||
$high !== NULL) {
284 $defaults[$fieldName . '_relative'] = 0;
285 $defaults[$fieldName . '_low'] = $low ?
date('Y-m-d H:i:s', strtotime($low)) : NULL;
286 $defaults[$fieldName . '_high'] = $high ?
date('Y-m-d H:i:s', strtotime($high)) : NULL;
295 * Convert any submitted text fields to use 'like' rather than '=' as the operator.
297 * This excludes any with options.
299 * Note this will only pick up fields declared via metadata.
301 protected function convertTextStringsToUseLikeOperator() {
302 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
303 foreach ($fields as $fieldName => $field) {
304 if (!empty($this->_formValues
[$fieldName]) && empty($field['options']) && empty($field['pseudoconstant'])) {
305 if (in_array($field['type'], [CRM_Utils_Type
::T_STRING
, CRM_Utils_Type
::T_TEXT
])) {
306 $this->_formValues
[$fieldName] = ['LIKE' => CRM_Contact_BAO_Query
::getWildCardedValue(TRUE, 'LIKE', $this->_formValues
[$fieldName])];
314 * Add checkboxes for each row plus a master checkbox.
318 public function addRowSelectors($rows) {
319 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
321 foreach ($rows as $row) {
322 if (CRM_Utils_Array
::value('checkbox', $row)) {
323 $this->addElement('checkbox', $row['checkbox'], NULL, NULL, ['class' => 'select-row']);
330 * Add actions menu to search results form.
332 * @param array $tasks
334 public function addTaskMenu($tasks) {
336 foreach ($tasks as $key => $task) {
337 $taskMetaData[$key] = ['title' => $task];
339 parent
::addTaskMenu($taskMetaData);
343 * Add the sort-name field to the form.
345 * There is a setting to determine whether email is included in the search & we look this up to determine
346 * which text to choose.
348 * Note that for translation purposes the full string works better than using 'prefix' hence we use override-able functions
349 * to define the string.
351 protected function addSortNameField() {
352 $title = civicrm_api3('setting', 'getvalue', ['name' => 'includeEmailInName', 'group' => 'Search Preferences']) ?
$this->getSortNameLabelWithEmail() : $this->getSortNameLabelWithOutEmail();
357 CRM_Core_DAO
::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')
359 $this->searchFieldMetadata
['Contact']['sort_name'] = ['name' => 'sort_name', 'title' => $title, 'type' => CRM_Utils_Type
::T_STRING
];
363 * Get the label for the sortName field if email searching is on.
365 * (email searching is a setting under search preferences).
369 protected function getSortNameLabelWithEmail() {
370 return ts('Name or Email');
374 * Get the label for the sortName field if email searching is off.
376 * (email searching is a setting under search preferences).
380 protected function getSortNameLabelWithOutEmail() {
385 * Explicitly declare the form context for addField().
387 public function getDefaultContext() {
392 * Add generic fields that specify the contact.
394 protected function addContactSearchFields() {
395 if (!$this->isFormInViewOrEditMode()) {
398 $this->addSortNameField();
400 $this->_group
= CRM_Core_PseudoConstant
::nestedGroup();
402 $this->add('select', 'group', $this->getGroupLabel(), $this->_group
, FALSE,
405 'multiple' => 'multiple',
406 'class' => 'crm-select2',
411 $contactTags = CRM_Core_BAO_Tag
::getTags();
413 $this->add('select', 'contact_tags', $this->getTagLabel(), $contactTags, FALSE,
415 'id' => 'contact_tags',
416 'multiple' => 'multiple',
417 'class' => 'crm-select2',
421 $this->addField('contact_type', ['entity' => 'Contact']);
423 if (CRM_Core_Permission
::check('access deleted contacts') && Civi
::settings()->get('contact_undelete')) {
424 $this->addElement('checkbox', 'deleted_contacts', ts('Search in Trash') . '<br />' . ts('(deleted contacts)'));
430 * we allow the controller to set force/reset externally, useful when we are being
431 * driven by the wizard framework
433 protected function loadStandardSearchOptionsFromUrl() {
434 $this->_reset
= CRM_Utils_Request
::retrieve('reset', 'Boolean');
435 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean', $this, FALSE);
436 $this->_limit
= CRM_Utils_Request
::retrieve('limit', 'Positive', $this);
437 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this, FALSE, 'search');
438 $this->_ssID
= CRM_Utils_Request
::retrieve('ssID', 'Positive', $this);
439 $this->assign("context", $this->_context
);
443 * Get user submitted values.
445 * Get it from controller only if form has been submitted, else preProcess has set this
447 protected function loadFormValues() {
448 if (!empty($_POST) && !$this->controller
->isModal()) {
449 $this->_formValues
= $this->controller
->exportValues($this->_name
);
452 $this->_formValues
= $this->get('formValues');
455 if (empty($this->_formValues
)) {
456 if (isset($this->_ssID
)) {
457 $this->_formValues
= CRM_Contact_BAO_SavedSearch
::getFormValues($this->_ssID
);