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 return array_merge($this->getEntityDefaults($this->getDefaultEntity()), (array) $this->_formValues
);
139 * Common buildForm tasks required by all searches.
141 public function buildQuickForm() {
142 CRM_Core_Resources
::singleton()
143 ->addScriptFile('civicrm', 'js/crm.searchForm.js', 1, 'html-header')
144 ->addStyleFile('civicrm', 'css/searchForm.css', 1, 'html-header');
149 'name' => ts('Search'),
154 $this->addClass('crm-search-form');
156 $tasks = $this->buildTaskList();
157 $this->addTaskMenu($tasks);
161 * Add any fields described in metadata to the form.
163 * The goal is to describe all fields in metadata and handle from metadata rather
164 * than existing ad hoc handling.
166 public function addFormFieldsFromMetadata() {
167 $this->addFormRule(['CRM_Core_Form_Search', 'formRule'], $this);
168 $this->_action
= CRM_Core_Action
::ADVANCED
;
169 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
170 foreach ($fields as $fieldName => $fieldSpec) {
171 if ($fieldSpec['type'] === CRM_Utils_Type
::T_DATE ||
$fieldSpec['type'] === (CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
)) {
172 $this->addDatePickerRange($fieldName, $fieldSpec['title'], ($fieldSpec['type'] === (CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
)));
175 $props = ['entity' => $entity];
176 if (isset($fields[$fieldName]['title'])) {
177 $props['label'] = $fields[$fieldName]['title'];
179 $this->addField($fieldName, $props);
186 * Global validation rules for the form.
188 * @param array $fields
189 * Posted values of the form.
190 * @param array $files
191 * @param object $form
194 * list of errors to be posted back to the form
196 public static function formRule($fields, $files, $form) {
198 if (!is_a($form, 'CRM_Core_Form_Search')) {
199 // So this gets hit with a form object when doing an activity date search from
200 // advanced search, but a NULL object when doing a pledge search.
203 foreach ($form->getSearchFieldMetadata() as $entity => $spec) {
204 foreach ($spec as $fieldName => $fieldSpec) {
205 if ($fieldSpec['type'] === CRM_Utils_Type
::T_DATE ||
$fieldSpec['type'] === (CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
)) {
206 if (!empty($fields[$fieldName . '_high']) && !empty($fields[$fieldName . '_low']) && empty($fields[$fieldName . '_relative'])) {
207 if (strtotime($fields[$fieldName . '_low']) > strtotime($fields[$fieldName . '_high'])) {
208 $errors[$fieldName . '_low'] = ts('%1: Please check that your date range is in correct chronological order.', [1 => $fieldSpec['title']]);
218 * Get the validation rule to apply to a function.
220 * Alphanumeric is designed to always be safe & for now we just return
221 * that but in future we can use tighter rules for types like int, bool etc.
223 * @param string $entity
224 * @param string $fieldName
228 protected function getValidationTypeForField($entity, $fieldName) {
229 switch ($this->getSearchFieldMetadata()[$entity][$fieldName]['type']) {
230 case CRM_Utils_Type
::T_BOOLEAN
:
233 case CRM_Utils_Type
::T_INT
:
234 return 'CommaSeparatedIntegers';
236 case CRM_Utils_Type
::T_DATE
:
237 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
241 return 'Alphanumeric';
246 * Get the defaults for the entity for any fields described in metadata.
248 * @param string $entity
252 protected function getEntityDefaults($entity) {
254 foreach ($this->getSearchFieldMetadata()[$entity] as $fieldSpec) {
255 if (empty($_POST[$fieldSpec['name']])) {
256 $value = CRM_Utils_Request
::retrieveValue($fieldSpec['name'], $this->getValidationTypeForField($entity, $fieldSpec['name']), FALSE, NULL, 'GET');
257 if ($value !== FALSE) {
258 $defaults[$fieldSpec['name']] = $value;
260 if ($fieldSpec['type'] === CRM_Utils_Type
::T_DATE ||
($fieldSpec['type'] === CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
)) {
261 $low = CRM_Utils_Request
::retrieveValue($fieldSpec['name'] . '_low', 'Timestamp', FALSE, NULL, 'GET');
262 $high = CRM_Utils_Request
::retrieveValue($fieldSpec['name'] . '_high', 'Timestamp', FALSE, NULL, 'GET');
263 if ($low !== FALSE ||
$high !== FALSE) {
264 $defaults[$fieldSpec['name'] . '_relative'] = 0;
265 $defaults[$fieldSpec['name'] . '_low'] = $low ?
date('Y-m-d H:i:s', strtotime($low)) : NULL;
266 $defaults[$fieldSpec['name'] . '_high'] = $high ?
date('Y-m-d H:i:s', strtotime($high)) : NULL;
275 * Convert any submitted text fields to use 'like' rather than '=' as the operator.
277 * This excludes any with options.
279 * Note this will only pick up fields declared via metadata.
281 protected function convertTextStringsToUseLikeOperator() {
282 foreach (CRM_Utils_Array
::value($this->getDefaultEntity(), $this->getSearchFieldMetadata(), []) as $fieldName => $field) {
283 if (!empty($this->_formValues
[$fieldName]) && empty($field['options']) && empty($field['pseudoconstant'])) {
284 if (in_array($field['type'], [CRM_Utils_Type
::T_STRING
, CRM_Utils_Type
::T_TEXT
])) {
285 $this->_formValues
[$fieldName] = ['LIKE' => CRM_Contact_BAO_Query
::getWildCardedValue(TRUE, 'LIKE', $this->_formValues
[$fieldName])];
292 * Add checkboxes for each row plus a master checkbox.
296 public function addRowSelectors($rows) {
297 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
299 foreach ($rows as $row) {
300 if (CRM_Utils_Array
::value('checkbox', $row)) {
301 $this->addElement('checkbox', $row['checkbox'], NULL, NULL, ['class' => 'select-row']);
308 * Add actions menu to search results form.
310 * @param array $tasks
312 public function addTaskMenu($tasks) {
314 foreach ($tasks as $key => $task) {
315 $taskMetaData[$key] = ['title' => $task];
317 parent
::addTaskMenu($taskMetaData);
321 * Add the sort-name field to the form.
323 * There is a setting to determine whether email is included in the search & we look this up to determine
324 * which text to choose.
326 * Note that for translation purposes the full string works better than using 'prefix' hence we use override-able functions
327 * to define the string.
329 protected function addSortNameField() {
333 civicrm_api3('setting', 'getvalue', ['name' => 'includeEmailInName', 'group' => 'Search Preferences']) ?
$this->getSortNameLabelWithEmail() : $this->getSortNameLabelWithOutEmail(),
334 CRM_Core_DAO
::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')
339 * Get the label for the sortName field if email searching is on.
341 * (email searching is a setting under search preferences).
345 protected function getSortNameLabelWithEmail() {
346 return ts('Name or Email');
350 * Get the label for the sortName field if email searching is off.
352 * (email searching is a setting under search preferences).
356 protected function getSortNameLabelWithOutEmail() {
361 * Explicitly declare the form context for addField().
363 public function getDefaultContext() {
368 * Add generic fields that specify the contact.
370 protected function addContactSearchFields() {
371 if (!$this->isFormInViewOrEditMode()) {
374 $this->addSortNameField();
376 $this->_group
= CRM_Core_PseudoConstant
::nestedGroup();
378 $this->add('select', 'group', $this->getGroupLabel(), $this->_group
, FALSE,
381 'multiple' => 'multiple',
382 'class' => 'crm-select2',
387 $contactTags = CRM_Core_BAO_Tag
::getTags();
389 $this->add('select', 'contact_tags', $this->getTagLabel(), $contactTags, FALSE,
391 'id' => 'contact_tags',
392 'multiple' => 'multiple',
393 'class' => 'crm-select2',
397 $this->addField('contact_type', ['entity' => 'Contact']);
399 if (CRM_Core_Permission
::check('access deleted contacts') && Civi
::settings()->get('contact_undelete')) {
400 $this->addElement('checkbox', 'deleted_contacts', ts('Search in Trash') . '<br />' . ts('(deleted contacts)'));
406 * we allow the controller to set force/reset externally, useful when we are being
407 * driven by the wizard framework
409 protected function loadStandardSearchOptionsFromUrl() {
410 $this->_reset
= CRM_Utils_Request
::retrieve('reset', 'Boolean');
411 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean', $this, FALSE);
412 $this->_limit
= CRM_Utils_Request
::retrieve('limit', 'Positive', $this);
413 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this, FALSE, 'search');
414 $this->_ssID
= CRM_Utils_Request
::retrieve('ssID', 'Positive', $this);
415 $this->assign("context", $this->_context
);
419 * Get user submitted values.
421 * Get it from controller only if form has been submitted, else preProcess has set this
423 protected function loadFormValues() {
424 if (!empty($_POST) && !$this->controller
->isModal()) {
425 $this->_formValues
= $this->controller
->exportValues($this->_name
);
428 $this->_formValues
= $this->get('formValues');
431 if (empty($this->_formValues
)) {
432 if (isset($this->_ssID
)) {
433 $this->_formValues
= CRM_Contact_BAO_SavedSearch
::getFormValues($this->_ssID
);