Swap CRM_Utils_Array::value for empty() or isset() in conditionals
[civicrm-core.git] / CRM / Core / Form / Search.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * Base class for most search forms
30 */
31 class CRM_Core_Form_Search extends CRM_Core_Form {
32
33 /**
34 * Are we forced to run a search
35 *
36 * @var int
37 */
38 protected $_force;
39
40 /**
41 * Name of search button
42 *
43 * @var string
44 */
45 protected $_searchButtonName;
46
47 /**
48 * Name of action button
49 *
50 * @var string
51 */
52 protected $_actionButtonName;
53
54 /**
55 * Form values that we will be using
56 *
57 * @var array
58 */
59 public $_formValues;
60
61 /**
62 * Have we already done this search
63 *
64 * @var bool
65 */
66 protected $_done;
67
68 /**
69 * What context are we being invoked from
70 *
71 * @var string
72 */
73 protected $_context = NULL;
74
75 /**
76 * The list of tasks or actions that a searcher can perform on a result set.
77 *
78 * @var array
79 */
80 protected $_taskList = [];
81
82 /**
83 * Declare entity reference fields as they will need to be converted.
84 *
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.
87 *
88 * @var array
89 */
90 protected $entityReferenceFields = [];
91
92 /**
93 * Builds the list of tasks or actions that a searcher can perform on a result set.
94 *
95 * To modify the task list, child classes should alter $this->_taskList,
96 * preferably by extending this method.
97 *
98 * @return array
99 */
100 protected function buildTaskList() {
101 return $this->_taskList;
102 }
103
104 /**
105 * Metadata for fields on the search form.
106 *
107 * Instantiate with empty array for contact to prevent e-notices.
108 *
109 * @var array
110 */
111 protected $searchFieldMetadata = ['Contact' => []];
112
113 /**
114 * @return array
115 */
116 public function getSearchFieldMetadata() {
117 return $this->searchFieldMetadata;
118 }
119
120 /**
121 * @param array $searchFieldMetadata
122 */
123 public function addSearchFieldMetadata($searchFieldMetadata) {
124 $this->searchFieldMetadata = array_merge($this->searchFieldMetadata, $searchFieldMetadata);
125 }
126
127 /**
128 * This virtual function is used to set the default values of various form elements.
129 *
130 * @return array|NULL
131 * reference to the array of default values
132 * @throws \Exception
133 */
134 public function setDefaultValues() {
135 $defaults = (array) $this->_formValues;
136 foreach (array_keys($this->getSearchFieldMetadata()) as $entity) {
137 $defaults = array_merge($this->getEntityDefaults($entity), $defaults);
138 }
139 return $defaults;
140 }
141
142 /**
143 * Set the form values based on input and preliminary processing.
144 *
145 * @throws \Exception
146 */
147 protected function setFormValues() {
148 if (!empty($_POST) && !$this->_force) {
149 $this->_formValues = $this->controller->exportValues($this->_name);
150 }
151 elseif ($this->_force) {
152 $this->_formValues = $this->setDefaultValues();
153 }
154 $this->convertTextStringsToUseLikeOperator();
155 }
156
157 /**
158 * Common buildForm tasks required by all searches.
159 */
160 public function buildQuickForm() {
161 CRM_Core_Resources::singleton()
162 ->addScriptFile('civicrm', 'js/crm.searchForm.js', 1, 'html-header')
163 ->addStyleFile('civicrm', 'css/searchForm.css', 1, 'html-header');
164
165 $this->addButtons([
166 [
167 'type' => 'refresh',
168 'name' => ts('Search'),
169 'isDefault' => TRUE,
170 ],
171 ]);
172
173 $this->addClass('crm-search-form');
174
175 $tasks = $this->buildTaskList();
176 $this->addTaskMenu($tasks);
177 }
178
179 /**
180 * Add any fields described in metadata to the form.
181 *
182 * The goal is to describe all fields in metadata and handle from metadata rather
183 * than existing ad hoc handling.
184 */
185 public function addFormFieldsFromMetadata() {
186 $this->addFormRule(['CRM_Core_Form_Search', 'formRule'], $this);
187 $this->_action = CRM_Core_Action::ADVANCED;
188 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
189 foreach ($fields as $fieldName => $fieldSpec) {
190 $fieldType = $fieldSpec['type'] ?? '';
191 if ($fieldType === CRM_Utils_Type::T_DATE || $fieldType === (CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)) {
192 $title = empty($fieldSpec['unique_title']) ? $fieldSpec['title'] : $fieldSpec['unique_title'];
193 $this->addDatePickerRange($fieldName, $title, ($fieldType === (CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)));
194 }
195 else {
196 // Not quite sure about moving to a mix of keying by entity vs permitting entity to
197 // be passed in. The challenge of the former is that it doesn't permit ordering.
198 // Perhaps keying was the wrong starting point & we should do a flat array as all
199 // fields eventually need to be unique.
200 $props = ['entity' => $fieldSpec['entity'] ?? $entity];
201 if (isset($fields[$fieldName]['unique_title'])) {
202 $props['label'] = $fields[$fieldName]['unique_title'];
203 }
204 elseif (isset($fields[$fieldName]['title'])) {
205 $props['label'] = $fields[$fieldName]['title'];
206 }
207 if (empty($fieldSpec['is_pseudofield'])) {
208 $this->addField($fieldName, $props);
209 }
210 }
211 }
212 }
213 }
214
215 /**
216 * Global validation rules for the form.
217 *
218 * @param array $fields
219 * Posted values of the form.
220 * @param array $files
221 * @param object $form
222 *
223 * @return array
224 * list of errors to be posted back to the form
225 */
226 public static function formRule($fields, $files, $form) {
227 $errors = [];
228 if (!is_a($form, 'CRM_Core_Form_Search')) {
229 // So this gets hit with a form object when doing an activity date search from
230 // advanced search, but a NULL object when doing a pledge search.
231 return $errors;
232 }
233 foreach ($form->getSearchFieldMetadata() as $entity => $spec) {
234 foreach ($spec as $fieldName => $fieldSpec) {
235 if ($fieldSpec['type'] === CRM_Utils_Type::T_DATE || $fieldSpec['type'] === (CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)) {
236 if (!empty($fields[$fieldName . '_high']) && !empty($fields[$fieldName . '_low']) && empty($fields[$fieldName . '_relative'])) {
237 if (strtotime($fields[$fieldName . '_low']) > strtotime($fields[$fieldName . '_high'])) {
238 $errors[$fieldName . '_low'] = ts('%1: Please check that your date range is in correct chronological order.', [1 => $fieldSpec['title']]);
239 }
240 }
241 }
242 }
243 }
244 return $errors;
245 }
246
247 /**
248 * Get the validation rule to apply to a function.
249 *
250 * Alphanumeric is designed to always be safe & for now we just return
251 * that but in future we can use tighter rules for types like int, bool etc.
252 *
253 * @param string $entity
254 * @param string $fieldName
255 *
256 * @return string
257 */
258 protected function getValidationTypeForField($entity, $fieldName) {
259 switch ($this->getSearchFieldMetadata()[$entity][$fieldName]['type']) {
260 case CRM_Utils_Type::T_BOOLEAN:
261 return 'Boolean';
262
263 case CRM_Utils_Type::T_INT:
264 return 'CommaSeparatedIntegers';
265
266 case CRM_Utils_Type::T_DATE:
267 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
268 return 'Timestamp';
269
270 default:
271 return 'Alphanumeric';
272 }
273 }
274
275 /**
276 * Get the defaults for the entity for any fields described in metadata.
277 *
278 * @param string $entity
279 *
280 * @return array
281 *
282 * @throws \CRM_Core_Exception
283 */
284 protected function getEntityDefaults($entity) {
285 $defaults = [];
286 foreach (CRM_Utils_Array::value($entity, $this->getSearchFieldMetadata(), []) as $fieldName => $fieldSpec) {
287 if (empty($_POST[$fieldName])) {
288 $value = CRM_Utils_Request::retrieveValue($fieldName, $this->getValidationTypeForField($entity, $fieldName), NULL, NULL, 'GET');
289 if ($value !== NULL) {
290 $defaults[$fieldName] = $value;
291 }
292 if ($fieldSpec['type'] === CRM_Utils_Type::T_DATE || ($fieldSpec['type'] === CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)) {
293 $low = CRM_Utils_Request::retrieveValue($fieldName . '_low', 'Timestamp', NULL, NULL, 'GET');
294 $high = CRM_Utils_Request::retrieveValue($fieldName . '_high', 'Timestamp', NULL, NULL, 'GET');
295 if ($low !== NULL || $high !== NULL) {
296 $defaults[$fieldName . '_relative'] = 0;
297 $defaults[$fieldName . '_low'] = $low ? date('Y-m-d H:i:s', strtotime($low)) : NULL;
298 $defaults[$fieldName . '_high'] = $high ? date('Y-m-d H:i:s', strtotime($high)) : NULL;
299 }
300 else {
301 $relative = CRM_Utils_Request::retrieveValue($fieldName . '_relative', 'String', NULL, NULL, 'GET');
302 if (!empty($relative) && isset(CRM_Core_OptionGroup::values('relative_date_filters')[$relative])) {
303 $defaults[$fieldName . '_relative'] = $relative;
304 }
305 }
306 }
307 }
308 }
309 return $defaults;
310 }
311
312 /**
313 * Convert any submitted text fields to use 'like' rather than '=' as the operator.
314 *
315 * This excludes any with options.
316 *
317 * Note this will only pick up fields declared via metadata.
318 */
319 protected function convertTextStringsToUseLikeOperator() {
320 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
321 foreach ($fields as $fieldName => $field) {
322 if (!empty($this->_formValues[$fieldName]) && empty($field['options']) && empty($field['pseudoconstant'])) {
323 if (in_array($field['type'], [CRM_Utils_Type::T_STRING, CRM_Utils_Type::T_TEXT])) {
324 $this->_formValues[$fieldName] = ['LIKE' => CRM_Contact_BAO_Query::getWildCardedValue(TRUE, 'LIKE', $this->_formValues[$fieldName])];
325 }
326 }
327 }
328 }
329 }
330
331 /**
332 * Add checkboxes for each row plus a master checkbox.
333 *
334 * @param array $rows
335 */
336 public function addRowSelectors($rows) {
337 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
338 if (!empty($rows)) {
339 foreach ($rows as $row) {
340 if (!empty($row['checkbox'])) {
341 $this->addElement('checkbox', $row['checkbox'], NULL, NULL, ['class' => 'select-row']);
342 }
343 }
344 }
345 }
346
347 /**
348 * Add actions menu to search results form.
349 *
350 * @param array $tasks
351 */
352 public function addTaskMenu($tasks) {
353 $taskMetaData = [];
354 foreach ($tasks as $key => $task) {
355 $taskMetaData[$key] = ['title' => $task];
356 }
357 parent::addTaskMenu($taskMetaData);
358 }
359
360 /**
361 * Add the sort-name field to the form.
362 *
363 * There is a setting to determine whether email is included in the search & we look this up to determine
364 * which text to choose.
365 *
366 * Note that for translation purposes the full string works better than using 'prefix' hence we use override-able functions
367 * to define the string.
368 */
369 protected function addSortNameField() {
370 $title = civicrm_api3('setting', 'getvalue', ['name' => 'includeEmailInName', 'group' => 'Search Preferences']) ? $this->getSortNameLabelWithEmail() : $this->getSortNameLabelWithOutEmail();
371 $this->addElement(
372 'text',
373 'sort_name',
374 $title,
375 CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')
376 );
377 $this->searchFieldMetadata['Contact']['sort_name'] = ['name' => 'sort_name', 'title' => $title, 'type' => CRM_Utils_Type::T_STRING];
378 }
379
380 /**
381 * Get the label for the sortName field if email searching is on.
382 *
383 * (email searching is a setting under search preferences).
384 *
385 * @return string
386 */
387 protected function getSortNameLabelWithEmail() {
388 return ts('Name or Email');
389 }
390
391 /**
392 * Get the label for the sortName field if email searching is off.
393 *
394 * (email searching is a setting under search preferences).
395 *
396 * @return string
397 */
398 protected function getSortNameLabelWithOutEmail() {
399 return ts('Name');
400 }
401
402 /**
403 * Explicitly declare the form context for addField().
404 */
405 public function getDefaultContext() {
406 return 'search';
407 }
408
409 /**
410 * Add generic fields that specify the contact.
411 */
412 protected function addContactSearchFields() {
413 if (!$this->isFormInViewOrEditMode()) {
414 return;
415 }
416 $this->addSortNameField();
417
418 $this->_group = CRM_Core_PseudoConstant::nestedGroup();
419 if ($this->_group) {
420 $this->add('select', 'group', $this->getGroupLabel(), $this->_group, FALSE,
421 [
422 'id' => 'group',
423 'multiple' => 'multiple',
424 'class' => 'crm-select2',
425 ]
426 );
427 }
428
429 $contactTags = CRM_Core_BAO_Tag::getTags();
430 if ($contactTags) {
431 $this->add('select', 'contact_tags', $this->getTagLabel(), $contactTags, FALSE,
432 [
433 'id' => 'contact_tags',
434 'multiple' => 'multiple',
435 'class' => 'crm-select2',
436 ]
437 );
438 }
439 $this->addField('contact_type', ['entity' => 'Contact']);
440
441 if (CRM_Core_Permission::check('access deleted contacts') && Civi::settings()->get('contact_undelete')) {
442 $this->addElement('checkbox', 'deleted_contacts', ts('Search in Trash') . '<br />' . ts('(deleted contacts)'));
443 }
444
445 }
446
447 /**
448 * we allow the controller to set force/reset externally, useful when we are being
449 * driven by the wizard framework
450 */
451 protected function loadStandardSearchOptionsFromUrl() {
452 $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
453 $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
454 $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
455 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'search');
456 $this->_ssID = CRM_Utils_Request::retrieve('ssID', 'Positive', $this);
457 $this->assign("context", $this->_context);
458 }
459
460 /**
461 * Get user submitted values.
462 *
463 * Get it from controller only if form has been submitted, else preProcess has set this
464 */
465 protected function loadFormValues() {
466 if (!empty($_POST) && !$this->controller->isModal()) {
467 $this->_formValues = $this->controller->exportValues($this->_name);
468 }
469 else {
470 $this->_formValues = $this->get('formValues');
471 }
472
473 if (empty($this->_formValues)) {
474 if (isset($this->_ssID)) {
475 $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
476 }
477 }
478 }
479
480 }