Merge pull request #13554 from kewljuice/patch-3
[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 boolean
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 = array();
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 = array();
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 * @var array
108 */
109 protected $searchFieldMetadata = [];
110
111 /**
112 * @return array
113 */
114 public function getSearchFieldMetadata() {
115 return $this->searchFieldMetadata;
116 }
117
118 /**
119 * @param array $searchFieldMetadata
120 */
121 public function addSearchFieldMetadata($searchFieldMetadata) {
122 $this->searchFieldMetadata = array_merge($this->searchFieldMetadata, $searchFieldMetadata);
123 }
124
125 /**
126 * Common buildForm tasks required by all searches.
127 */
128 public function buildQuickform() {
129 CRM_Core_Resources::singleton()
130 ->addScriptFile('civicrm', 'js/crm.searchForm.js', 1, 'html-header')
131 ->addStyleFile('civicrm', 'css/searchForm.css', 1, 'html-header');
132
133 $this->addButtons(array(
134 array(
135 'type' => 'refresh',
136 'name' => ts('Search'),
137 'isDefault' => TRUE,
138 ),
139 ));
140
141 $this->addClass('crm-search-form');
142
143 $tasks = $this->buildTaskList();
144 $this->addTaskMenu($tasks);
145 }
146
147 /**
148 * Add any fields described in metadata to the form.
149 *
150 * The goal is to describe all fields in metadata and handle from metadata rather
151 * than existing ad hoc handling.
152 */
153 public function addFormFieldsFromMetadata() {
154 $this->addFormRule(['CRM_Core_Form_Search', 'formRule'], $this);
155 $this->_action = CRM_Core_Action::ADVANCED;
156 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
157 foreach ($fields as $fieldName => $fieldSpec) {
158 if ($fieldSpec['type'] === CRM_Utils_Type::T_DATE || $fieldSpec['type'] === (CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)) {
159 $this->addDatePickerRange($fieldName, $fieldSpec['title'], ($fieldSpec['type'] === (CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)));
160 }
161 else {
162 $this->addField($fieldName, ['entity' => $entity]);
163 }
164 }
165 }
166 }
167
168 /**
169 * Global validation rules for the form.
170 *
171 * @param array $fields
172 * Posted values of the form.
173 *
174 * @return array
175 * list of errors to be posted back to the form
176 */
177 public static function formRule($fields, $files, $form) {
178 $errors = [];
179 foreach ($form->getSearchFieldMetadata() as $entity => $spec) {
180 foreach ($spec as $fieldName => $fieldSpec) {
181 if ($fieldSpec['type'] === CRM_Utils_Type::T_DATE || $fieldSpec['type'] === (CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)) {
182 if (isset($fields[$fieldName . '_high']) && isset($fields[$fieldName . '_low']) && empty($fields[$fieldName . '_relative'])) {
183 if (strtotime($fields[$fieldName . '_low']) > strtotime($fields[$fieldName . '_high'])) {
184 $errors[$fieldName . '_low'] = ts('%1: Please check that your date range is in correct chronological order.', [1 => $fieldSpec['title']]);
185 }
186 }
187 }
188 }
189 }
190 return $errors;
191 }
192
193 /**
194 * Get the validation rule to apply to a function.
195 *
196 * Alphanumeric is designed to always be safe & for now we just return
197 * that but in future we can use tighter rules for types like int, bool etc.
198 *
199 * @param string $entity
200 * @param string $fieldName
201 *
202 * @return string
203 */
204 protected function getValidationTypeForField($entity, $fieldName) {
205 switch ($this->getSearchFieldMetadata()[$entity][$fieldName]['type']) {
206 case CRM_Utils_Type::T_BOOLEAN:
207 return 'Boolean';
208
209 case CRM_Utils_Type::T_INT:
210 return 'CommaSeparatedIntegers';
211
212 case CRM_Utils_Type::T_DATE:
213 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
214 return 'Timestamp';
215
216 default:
217 return 'Alphanumeric';
218 }
219 }
220
221 /**
222 * Get the defaults for the entity for any fields described in metadata.
223 *
224 * @param string $entity
225 *
226 * @return array
227 */
228 protected function getEntityDefaults($entity) {
229 $defaults = [];
230 foreach ($this->getSearchFieldMetadata()[$entity] as $fieldSpec) {
231 if (empty($_POST[$fieldSpec['name']])) {
232 $value = CRM_Utils_Request::retrieveValue($fieldSpec['name'], $this->getValidationTypeForField($entity, $fieldSpec['name']), FALSE, NULL, 'GET');
233 if ($value !== FALSE) {
234 $defaults[$fieldSpec['name']] = $value;
235 }
236 if ($fieldSpec['type'] === CRM_Utils_Type::T_DATE || ($fieldSpec['type'] === CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME)) {
237 $low = CRM_Utils_Request::retrieveValue($fieldSpec['name'] . '_low', 'Timestamp', FALSE, NULL, 'GET');
238 $high = CRM_Utils_Request::retrieveValue($fieldSpec['name'] . '_high', 'Timestamp', FALSE, NULL, 'GET');
239 if ($low !== FALSE || $high !== FALSE) {
240 $defaults[$fieldSpec['name'] . '_relative'] = 0;
241 $defaults[$fieldSpec['name'] . '_low'] = $low ? date('Y-m-d H:i:s', strtotime($low)) : NULL;
242 $defaults[$fieldSpec['name'] . '_high'] = $high ? date('Y-m-d H:i:s', strtotime($high)) : NULL;
243 }
244 }
245 }
246 }
247 return $defaults;
248 }
249
250 /**
251 * Add checkboxes for each row plus a master checkbox.
252 *
253 * @param array $rows
254 */
255 public function addRowSelectors($rows) {
256 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, array('class' => 'select-rows'));
257 if (!empty($rows)) {
258 foreach ($rows as $row) {
259 if (CRM_Utils_Array::value('checkbox', $row)) {
260 $this->addElement('checkbox', $row['checkbox'], NULL, NULL, array('class' => 'select-row'));
261 }
262 }
263 }
264 }
265
266 /**
267 * Add actions menu to search results form.
268 *
269 * @param array $tasks
270 */
271 public function addTaskMenu($tasks) {
272 $taskMetaData = array();
273 foreach ($tasks as $key => $task) {
274 $taskMetaData[$key] = array('title' => $task);
275 }
276 parent::addTaskMenu($taskMetaData);
277 }
278
279 /**
280 * Add the sort-name field to the form.
281 *
282 * There is a setting to determine whether email is included in the search & we look this up to determine
283 * which text to choose.
284 *
285 * Note that for translation purposes the full string works better than using 'prefix' hence we use override-able functions
286 * to define the string.
287 */
288 protected function addSortNameField() {
289 $this->addElement(
290 'text',
291 'sort_name',
292 civicrm_api3('setting', 'getvalue', array('name' => 'includeEmailInName', 'group' => 'Search Preferences')) ? $this->getSortNameLabelWithEmail() : $this->getSortNameLabelWithOutEmail(),
293 CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')
294 );
295 }
296
297 /**
298 * Get the label for the sortName field if email searching is on.
299 *
300 * (email searching is a setting under search preferences).
301 *
302 * @return string
303 */
304 protected function getSortNameLabelWithEmail() {
305 return ts('Name or Email');
306 }
307
308 /**
309 * Get the label for the sortName field if email searching is off.
310 *
311 * (email searching is a setting under search preferences).
312 *
313 * @return string
314 */
315 protected function getSortNameLabelWithOutEmail() {
316 return ts('Name');
317 }
318
319 /**
320 * Explicitly declare the form context for addField().
321 */
322 public function getDefaultContext() {
323 return 'search';
324 }
325
326 /**
327 * Add generic fields that specify the contact.
328 */
329 protected function addContactSearchFields() {
330 if (!$this->isFormInViewOrEditMode()) {
331 return;
332 }
333 $this->addSortNameField();
334
335 $this->_group = CRM_Core_PseudoConstant::nestedGroup();
336 if ($this->_group) {
337 $this->add('select', 'group', $this->getGroupLabel(), $this->_group, FALSE,
338 array(
339 'id' => 'group',
340 'multiple' => 'multiple',
341 'class' => 'crm-select2',
342 )
343 );
344 }
345
346 $contactTags = CRM_Core_BAO_Tag::getTags();
347 if ($contactTags) {
348 $this->add('select', 'contact_tags', $this->getTagLabel(), $contactTags, FALSE,
349 array(
350 'id' => 'contact_tags',
351 'multiple' => 'multiple',
352 'class' => 'crm-select2',
353 )
354 );
355 }
356 $this->addField('contact_type', array('entity' => 'Contact'));
357
358 if (CRM_Core_Permission::check('access deleted contacts') && Civi::settings()->get('contact_undelete')) {
359 $this->addElement('checkbox', 'deleted_contacts', ts('Search in Trash') . '<br />' . ts('(deleted contacts)'));
360 }
361
362 }
363
364 /**
365 * we allow the controller to set force/reset externally, useful when we are being
366 * driven by the wizard framework
367 */
368 protected function loadStandardSearchOptionsFromUrl() {
369 $this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
370 $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
371 $this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
372 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'search');
373 $this->_ssID = CRM_Utils_Request::retrieve('ssID', 'Positive', $this);
374 $this->assign("context", $this->_context);
375 }
376
377 /**
378 * Get user submitted values.
379 *
380 * Get it from controller only if form has been submitted, else preProcess has set this
381 */
382 protected function loadFormValues() {
383 if (!empty($_POST) && !$this->controller->isModal()) {
384 $this->_formValues = $this->controller->exportValues($this->_name);
385 }
386 else {
387 $this->_formValues = $this->get('formValues');
388 }
389
390 if (empty($this->_formValues)) {
391 if (isset($this->_ssID)) {
392 $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
393 }
394 }
395 }
396
397 }