Merge pull request #14443 from eileenmcnaughton/export
[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 return array_merge($this->getEntityDefaults($this->getDefaultEntity()), (array) $this->_formValues);
136 }
137
138 /**
139 * Common buildForm tasks required by all searches.
140 */
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');
145
146 $this->addButtons([
147 [
148 'type' => 'refresh',
149 'name' => ts('Search'),
150 'isDefault' => TRUE,
151 ],
152 ]);
153
154 $this->addClass('crm-search-form');
155
156 $tasks = $this->buildTaskList();
157 $this->addTaskMenu($tasks);
158 }
159
160 /**
161 * Add any fields described in metadata to the form.
162 *
163 * The goal is to describe all fields in metadata and handle from metadata rather
164 * than existing ad hoc handling.
165 */
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)));
173 }
174 else {
175 $props = ['entity' => $entity];
176 if (isset($fields[$fieldName]['title'])) {
177 $props['label'] = $fields[$fieldName]['title'];
178 }
179 $this->addField($fieldName, $props);
180 }
181 }
182 }
183 }
184
185 /**
186 * Global validation rules for the form.
187 *
188 * @param array $fields
189 * Posted values of the form.
190 * @param array $files
191 * @param object $form
192 *
193 * @return array
194 * list of errors to be posted back to the form
195 */
196 public static function formRule($fields, $files, $form) {
197 $errors = [];
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.
201 return $errors;
202 }
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']]);
209 }
210 }
211 }
212 }
213 }
214 return $errors;
215 }
216
217 /**
218 * Get the validation rule to apply to a function.
219 *
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.
222 *
223 * @param string $entity
224 * @param string $fieldName
225 *
226 * @return string
227 */
228 protected function getValidationTypeForField($entity, $fieldName) {
229 switch ($this->getSearchFieldMetadata()[$entity][$fieldName]['type']) {
230 case CRM_Utils_Type::T_BOOLEAN:
231 return 'Boolean';
232
233 case CRM_Utils_Type::T_INT:
234 return 'CommaSeparatedIntegers';
235
236 case CRM_Utils_Type::T_DATE:
237 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
238 return 'Timestamp';
239
240 default:
241 return 'Alphanumeric';
242 }
243 }
244
245 /**
246 * Get the defaults for the entity for any fields described in metadata.
247 *
248 * @param string $entity
249 *
250 * @return array
251 */
252 protected function getEntityDefaults($entity) {
253 $defaults = [];
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;
259 }
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;
267 }
268 }
269 }
270 }
271 return $defaults;
272 }
273
274 /**
275 * Convert any submitted text fields to use 'like' rather than '=' as the operator.
276 *
277 * This excludes any with options.
278 *
279 * Note this will only pick up fields declared via metadata.
280 */
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])];
286 }
287 }
288 }
289 }
290
291 /**
292 * Add checkboxes for each row plus a master checkbox.
293 *
294 * @param array $rows
295 */
296 public function addRowSelectors($rows) {
297 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
298 if (!empty($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']);
302 }
303 }
304 }
305 }
306
307 /**
308 * Add actions menu to search results form.
309 *
310 * @param array $tasks
311 */
312 public function addTaskMenu($tasks) {
313 $taskMetaData = [];
314 foreach ($tasks as $key => $task) {
315 $taskMetaData[$key] = ['title' => $task];
316 }
317 parent::addTaskMenu($taskMetaData);
318 }
319
320 /**
321 * Add the sort-name field to the form.
322 *
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.
325 *
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.
328 */
329 protected function addSortNameField() {
330 $this->addElement(
331 'text',
332 'sort_name',
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')
335 );
336 }
337
338 /**
339 * Get the label for the sortName field if email searching is on.
340 *
341 * (email searching is a setting under search preferences).
342 *
343 * @return string
344 */
345 protected function getSortNameLabelWithEmail() {
346 return ts('Name or Email');
347 }
348
349 /**
350 * Get the label for the sortName field if email searching is off.
351 *
352 * (email searching is a setting under search preferences).
353 *
354 * @return string
355 */
356 protected function getSortNameLabelWithOutEmail() {
357 return ts('Name');
358 }
359
360 /**
361 * Explicitly declare the form context for addField().
362 */
363 public function getDefaultContext() {
364 return 'search';
365 }
366
367 /**
368 * Add generic fields that specify the contact.
369 */
370 protected function addContactSearchFields() {
371 if (!$this->isFormInViewOrEditMode()) {
372 return;
373 }
374 $this->addSortNameField();
375
376 $this->_group = CRM_Core_PseudoConstant::nestedGroup();
377 if ($this->_group) {
378 $this->add('select', 'group', $this->getGroupLabel(), $this->_group, FALSE,
379 [
380 'id' => 'group',
381 'multiple' => 'multiple',
382 'class' => 'crm-select2',
383 ]
384 );
385 }
386
387 $contactTags = CRM_Core_BAO_Tag::getTags();
388 if ($contactTags) {
389 $this->add('select', 'contact_tags', $this->getTagLabel(), $contactTags, FALSE,
390 [
391 'id' => 'contact_tags',
392 'multiple' => 'multiple',
393 'class' => 'crm-select2',
394 ]
395 );
396 }
397 $this->addField('contact_type', ['entity' => 'Contact']);
398
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)'));
401 }
402
403 }
404
405 /**
406 * we allow the controller to set force/reset externally, useful when we are being
407 * driven by the wizard framework
408 */
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);
416 }
417
418 /**
419 * Get user submitted values.
420 *
421 * Get it from controller only if form has been submitted, else preProcess has set this
422 */
423 protected function loadFormValues() {
424 if (!empty($_POST) && !$this->controller->isModal()) {
425 $this->_formValues = $this->controller->exportValues($this->_name);
426 }
427 else {
428 $this->_formValues = $this->get('formValues');
429 }
430
431 if (empty($this->_formValues)) {
432 if (isset($this->_ssID)) {
433 $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
434 }
435 }
436 }
437
438 }