[NFC] comment fixes - exceptions & don't declare NULL
[civicrm-core.git] / CRM / Core / Form / Search.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
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;
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 \CRM_Core_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 $this->_formValues = $this->getFormValues();
149 $this->convertTextStringsToUseLikeOperator();
150 }
151
152 /**
153 * Common buildForm tasks required by all searches.
154 *
155 * @throws \CRM_Core_Exception
156 */
157 public function buildQuickForm() {
158 CRM_Core_Resources::singleton()
159 ->addScriptFile('civicrm', 'js/crm.searchForm.js', 1, 'html-header')
160 ->addStyleFile('civicrm', 'css/searchForm.css', 1, 'html-header');
161
162 $this->addButtons([
163 [
164 'type' => 'refresh',
165 'name' => ts('Search'),
166 'isDefault' => TRUE,
167 ],
168 ]);
169
170 $this->addClass('crm-search-form');
171
172 $tasks = $this->buildTaskList();
173 $this->addTaskMenu($tasks);
174 }
175
176 /**
177 * Add any fields described in metadata to the form.
178 *
179 * The goal is to describe all fields in metadata and handle from metadata rather
180 * than existing ad hoc handling.
181 *
182 * @throws \CiviCRM_API3_Exception
183 */
184 public function addFormFieldsFromMetadata() {
185 $this->addFormRule(['CRM_Core_Form_Search', 'formRule'], $this);
186 $this->_action = CRM_Core_Action::ADVANCED;
187 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
188 foreach ($fields as $fieldName => $fieldSpec) {
189 $fieldType = $fieldSpec['type'] ?? '';
190 if ($fieldType === CRM_Utils_Type::T_DATE || $fieldType === (CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) || $fieldType === CRM_Utils_Type::T_TIMESTAMP) {
191 $title = empty($fieldSpec['unique_title']) ? $fieldSpec['title'] : $fieldSpec['unique_title'];
192 $this->addDatePickerRange($fieldName, $title, ($fieldType === (CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) || $fieldType === CRM_Utils_Type::T_TIMESTAMP));
193 }
194 else {
195 // Not quite sure about moving to a mix of keying by entity vs permitting entity to
196 // be passed in. The challenge of the former is that it doesn't permit ordering.
197 // Perhaps keying was the wrong starting point & we should do a flat array as all
198 // fields eventually need to be unique.
199 $props = ['entity' => $fieldSpec['entity'] ?? $entity];
200 if (isset($fields[$fieldName]['unique_title'])) {
201 $props['label'] = $fields[$fieldName]['unique_title'];
202 }
203 elseif (isset($fields[$fieldName]['title'])) {
204 $props['label'] = $fields[$fieldName]['title'];
205 }
206 if (empty($fieldSpec['is_pseudofield'])) {
207 $this->addField($fieldName, $props);
208 }
209 }
210 }
211 }
212 }
213
214 /**
215 * Global validation rules for the form.
216 *
217 * @param array $fields
218 * Posted values of the form.
219 * @param array $files
220 * @param object $form
221 *
222 * @return array
223 * list of errors to be posted back to the form
224 */
225 public static function formRule($fields, $files, $form) {
226 $errors = [];
227 if (!is_a($form, 'CRM_Core_Form_Search')) {
228 // So this gets hit with a form object when doing an activity date search from
229 // advanced search, but a NULL object when doing a pledge search.
230 return $errors;
231 }
232 foreach ($form->getSearchFieldMetadata() as $entity => $spec) {
233 foreach ($spec as $fieldName => $fieldSpec) {
234 if ($fieldSpec['type'] === CRM_Utils_Type::T_DATE || $fieldSpec['type'] === (CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)) {
235 if (!empty($fields[$fieldName . '_high']) && !empty($fields[$fieldName . '_low']) && empty($fields[$fieldName . '_relative'])) {
236 if (strtotime($fields[$fieldName . '_low']) > strtotime($fields[$fieldName . '_high'])) {
237 $errors[$fieldName . '_low'] = ts('%1: Please check that your date range is in correct chronological order.', [1 => $fieldSpec['title']]);
238 }
239 }
240 }
241 }
242 }
243 return $errors;
244 }
245
246 /**
247 * Get the validation rule to apply to a function.
248 *
249 * Alphanumeric is designed to always be safe & for now we just return
250 * that but in future we can use tighter rules for types like int, bool etc.
251 *
252 * @param string $entity
253 * @param string $fieldName
254 *
255 * @return string
256 */
257 protected function getValidationTypeForField($entity, $fieldName) {
258 switch ($this->getSearchFieldMetadata()[$entity][$fieldName]['type']) {
259 case CRM_Utils_Type::T_BOOLEAN:
260 return 'Boolean';
261
262 case CRM_Utils_Type::T_INT:
263 return 'CommaSeparatedIntegers';
264
265 case CRM_Utils_Type::T_DATE:
266 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
267 return 'Timestamp';
268
269 default:
270 return 'Alphanumeric';
271 }
272 }
273
274 /**
275 * Get the defaults for the entity for any fields described in metadata.
276 *
277 * @param string $entity
278 *
279 * @return array
280 *
281 * @throws \CRM_Core_Exception
282 */
283 protected function getEntityDefaults($entity) {
284 $defaults = [];
285 foreach (CRM_Utils_Array::value($entity, $this->getSearchFieldMetadata(), []) as $fieldName => $fieldSpec) {
286 if (empty($_POST[$fieldName])) {
287 $value = CRM_Utils_Request::retrieveValue($fieldName, $this->getValidationTypeForField($entity, $fieldName), NULL, NULL, 'GET');
288 if ($value !== NULL) {
289 $defaults[$fieldName] = $value;
290 }
291 if ($fieldSpec['type'] === CRM_Utils_Type::T_DATE || ($fieldSpec['type'] === CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)) {
292 $low = CRM_Utils_Request::retrieveValue($fieldName . '_low', 'Timestamp', NULL, NULL, 'GET');
293 $high = CRM_Utils_Request::retrieveValue($fieldName . '_high', 'Timestamp', NULL, NULL, 'GET');
294 if ($low !== NULL || $high !== NULL) {
295 $defaults[$fieldName . '_relative'] = 0;
296 $defaults[$fieldName . '_low'] = $low ? date('Y-m-d H:i:s', strtotime($low)) : NULL;
297 $defaults[$fieldName . '_high'] = $high ? date('Y-m-d H:i:s', strtotime($high)) : NULL;
298 }
299 else {
300 $relative = CRM_Utils_Request::retrieveValue($fieldName . '_relative', 'String', NULL, NULL, 'GET');
301 if (!empty($relative) && isset(CRM_Core_OptionGroup::values('relative_date_filters')[$relative])) {
302 $defaults[$fieldName . '_relative'] = $relative;
303 }
304 }
305 }
306 }
307 }
308 return $defaults;
309 }
310
311 /**
312 * Convert any submitted text fields to use 'like' rather than '=' as the operator.
313 *
314 * This excludes any with options.
315 *
316 * Note this will only pick up fields declared via metadata.
317 */
318 protected function convertTextStringsToUseLikeOperator() {
319 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
320 foreach ($fields as $fieldName => $field) {
321 if (!empty($this->_formValues[$fieldName]) && empty($field['options']) && empty($field['pseudoconstant'])) {
322 if (in_array($field['type'], [CRM_Utils_Type::T_STRING, CRM_Utils_Type::T_TEXT])) {
323 $this->_formValues[$fieldName] = ['LIKE' => CRM_Contact_BAO_Query::getWildCardedValue(TRUE, 'LIKE', trim($this->_formValues[$fieldName]))];
324 }
325 }
326 }
327 }
328 }
329
330 /**
331 * Add checkboxes for each row plus a master checkbox.
332 *
333 * @param array $rows
334 */
335 public function addRowSelectors($rows) {
336 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
337 if (!empty($rows)) {
338 foreach ($rows as $row) {
339 if (!empty($row['checkbox'])) {
340 $this->addElement('checkbox', $row['checkbox'], NULL, NULL, ['class' => 'select-row']);
341 }
342 }
343 }
344 }
345
346 /**
347 * Add actions menu to search results form.
348 *
349 * @param array $tasks
350 */
351 public function addTaskMenu($tasks) {
352 $taskMetaData = [];
353 foreach ($tasks as $key => $task) {
354 $taskMetaData[$key] = ['title' => $task];
355 }
356 parent::addTaskMenu($taskMetaData);
357 }
358
359 /**
360 * Add the sort-name field to the form.
361 *
362 * There is a setting to determine whether email is included in the search & we look this up to determine
363 * which text to choose.
364 *
365 * Note that for translation purposes the full string works better than using 'prefix' hence we use override-able functions
366 * to define the string.
367 *
368 * @throws \CiviCRM_API3_Exception
369 */
370 protected function addSortNameField() {
371 $title = civicrm_api3('setting', 'getvalue', ['name' => 'includeEmailInName', 'group' => 'Search Preferences']) ? $this->getSortNameLabelWithEmail() : $this->getSortNameLabelWithOutEmail();
372 $this->addElement(
373 'text',
374 'sort_name',
375 $title,
376 CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')
377 );
378 $this->searchFieldMetadata['Contact']['sort_name'] = ['name' => 'sort_name', 'title' => $title, 'type' => CRM_Utils_Type::T_STRING];
379 }
380
381 /**
382 * Get the label for the sortName field if email searching is on.
383 *
384 * (email searching is a setting under search preferences).
385 *
386 * @return string
387 */
388 protected function getSortNameLabelWithEmail() {
389 return ts('Name or Email');
390 }
391
392 /**
393 * Get the label for the sortName field if email searching is off.
394 *
395 * (email searching is a setting under search preferences).
396 *
397 * @return string
398 */
399 protected function getSortNameLabelWithOutEmail() {
400 return ts('Name');
401 }
402
403 /**
404 * Explicitly declare the form context for addField().
405 */
406 public function getDefaultContext() {
407 return 'search';
408 }
409
410 /**
411 * Add generic fields that specify the contact.
412 *
413 * @throws \CiviCRM_API3_Exception
414 */
415 protected function addContactSearchFields() {
416 if (!$this->isFormInViewOrEditMode()) {
417 return;
418 }
419 $this->addSortNameField();
420
421 $this->_group = CRM_Core_PseudoConstant::nestedGroup();
422 if ($this->_group) {
423 $this->add('select', 'group', $this->getGroupLabel(), $this->_group, FALSE,
424 [
425 'id' => 'group',
426 'multiple' => 'multiple',
427 'class' => 'crm-select2',
428 ]
429 );
430 }
431
432 $contactTags = CRM_Core_BAO_Tag::getTags();
433 if ($contactTags) {
434 $this->add('select', 'contact_tags', $this->getTagLabel(), $contactTags, FALSE,
435 [
436 'id' => 'contact_tags',
437 'multiple' => 'multiple',
438 'class' => 'crm-select2',
439 ]
440 );
441 }
442 $this->addField('contact_type', ['entity' => 'Contact']);
443
444 if (CRM_Core_Permission::check('access deleted contacts') && Civi::settings()->get('contact_undelete')) {
445 $this->addElement('checkbox', 'deleted_contacts', ts('Search in Trash') . '<br />' . ts('(deleted contacts)'));
446 }
447
448 }
449
450 /**
451 * we allow the controller to set force/reset externally, useful when we are being
452 * driven by the wizard framework
453 *
454 * @throws \CRM_Core_Exception
455 */
456 protected function loadStandardSearchOptionsFromUrl() {
457 $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
458 $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
459 $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
460 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'search');
461 $this->_ssID = CRM_Utils_Request::retrieve('ssID', 'Positive', $this);
462 $this->assign("context", $this->_context);
463 }
464
465 /**
466 * Get user submitted values.
467 *
468 * Get it from controller only if form has been submitted, else preProcess has set this
469 */
470 protected function loadFormValues() {
471 if (!empty($_POST) && !$this->controller->isModal()) {
472 $this->_formValues = $this->controller->exportValues($this->_name);
473 }
474 else {
475 $this->_formValues = $this->get('formValues');
476 }
477
478 if (empty($this->_formValues)) {
479 if (isset($this->_ssID)) {
480 $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
481 }
482 }
483 }
484
485 /**
486 * Get the form values.
487 *
488 * @todo consolidate with loadFormValues()
489 *
490 * @return array
491 *
492 * @throws \CRM_Core_Exception
493 */
494 protected function getFormValues() {
495 if (!empty($_POST) && !$this->_force) {
496 return $this->controller->exportValues($this->_name);
497 }
498 if ($this->_force) {
499 return $this->setDefaultValues();
500 }
501 return (array) $this->get('formValues');
502 }
503
504 /**
505 * Set the metadata for the form.
506 *
507 * @throws \CiviCRM_API3_Exception
508 */
509 protected function setSearchMetadata() {}
510
511 /**
512 * Handle force=1 in the url.
513 *
514 * Search field metadata is normally added in buildForm but we are bypassing that in this flow
515 * (I've always found the flow kinda confusing & perhaps that is the problem but this mitigates)
516 *
517 * @throws \CiviCRM_API3_Exception
518 */
519 protected function handleForcedSearch() {
520 $this->setSearchMetadata();
521 $this->postProcess();
522 $this->set('force', 0);
523 }
524
525 }