dev/core#41: Search Builder: Not empty with date or integer custom fields gives a...
[civicrm-core.git] / CRM / Contact / Form / Search / Builder.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
32 */
33
34/**
5a409b50 35 * This class is for search builder processing.
6a488035
TO
36 */
37class CRM_Contact_Form_Search_Builder extends CRM_Contact_Form_Search {
38
39 /**
fe482240 40 * Number of columns in where.
6a488035
TO
41 *
42 * @var int
6a488035
TO
43 */
44 public $_columnCount;
45
46 /**
fe482240 47 * Number of blocks to be shown.
6a488035
TO
48 *
49 * @var int
6a488035
TO
50 */
51 public $_blockCount;
52
53 /**
fe482240 54 * Build the form object.
6a488035
TO
55 */
56 public function preProcess() {
57 $this->set('searchFormName', 'Builder');
58
59 $this->set('context', 'builder');
60 parent::preProcess();
61
62 // Get the block count
63 $this->_blockCount = $this->get('blockCount');
64 // Initialize new form
65 if (!$this->_blockCount) {
66 $this->_blockCount = 4;
67 $this->set('newBlock', 1);
68 }
69
70 //get the column count
71 $this->_columnCount = $this->get('columnCount');
72
73 for ($i = 1; $i < $this->_blockCount; $i++) {
74 if (empty($this->_columnCount[$i])) {
75 $this->_columnCount[$i] = 5;
76 }
77 }
78
79 $this->_loadedMappingId = $this->get('savedMapping');
80
81 if ($this->get('showSearchForm')) {
82 $this->assign('showSearchForm', TRUE);
83 }
84 else {
85 $this->assign('showSearchForm', FALSE);
86 }
87 }
88
e8e8f3ad 89 /**
90 * Build quick form.
91 */
6a488035
TO
92 public function buildQuickForm() {
93 $fields = self::fields();
15c80835 94 $searchByLabelFields = array();
80beace7 95 // This array contain list of available fields and their corresponding data type,
96 // later assigned as json string, to be used to filter list of mysql operators
97 $fieldNameTypes = [];
6a488035 98 foreach ($fields as $name => $field) {
80beace7 99 // Assign date type to respective field name, which will be later used to modify operator list
89d4a22f 100 if ($type = CRM_Utils_Array::key(CRM_Utils_Array::value('type', $field), CRM_Utils_Type::getValidTypes())) {
101 $fieldNameTypes[$name] = $type;
759094bd 102 }
15c80835
UP
103 // it's necessary to know which of the fields are searchable by label
104 if (isset($field['searchByLabel']) && $field['searchByLabel']) {
ed56d481 105 $searchByLabelFields[] = $name;
15c80835 106 }
6a488035
TO
107 }
108 // Add javascript
109 CRM_Core_Resources::singleton()
96ed17aa 110 ->addScriptFile('civicrm', 'templates/CRM/Contact/Form/Search/Builder.js', 1, 'html-header')
6a488035
TO
111 ->addSetting(array(
112 'searchBuilder' => array(
113 // Index of newly added/expanded block (1-based index)
114 'newBlock' => $this->get('newBlock'),
6a488035 115 'fieldOptions' => self::fieldOptions(),
15c80835 116 'searchByLabelFields' => $searchByLabelFields,
80beace7 117 'fieldTypes' => $fieldNameTypes,
759094bd 118 'generalOperators' => array('' => ts('-operator-')) + CRM_Core_SelectValues::getSearchBuilderOperators(),
6a488035
TO
119 ),
120 ));
121 //get the saved search mapping id
122 $mappingId = NULL;
123 if ($this->_ssID) {
124 $mappingId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $this->_ssID, 'mapping_id');
125 }
126
127 CRM_Core_BAO_Mapping::buildMappingForm($this, 'Search Builder', $mappingId, $this->_columnCount, $this->_blockCount);
128
129 parent::buildQuickForm();
130 }
131
132 /**
fe482240 133 * Add local and global form rules.
6a488035 134 */
00be9182 135 public function addRules() {
6a488035
TO
136 $this->addFormRule(array('CRM_Contact_Form_Search_Builder', 'formRule'), $this);
137 }
138
139 /**
fe482240 140 * Global validation rules for the form.
6a488035 141 *
5a409b50 142 * @param array $values
143 * @param array $files
144 * @param CRM_Core_Form $self
fd31fa4c 145 *
a6c01b45
CW
146 * @return array
147 * list of errors to be posted back to the form
6a488035 148 */
00be9182 149 public static function formRule($values, $files, $self) {
8cc574cf 150 if (!empty($values['addMore']) || !empty($values['addBlock'])) {
6a488035
TO
151 return TRUE;
152 }
153 $fields = self::fields();
154 $fld = CRM_Core_BAO_Mapping::formattedFields($values, TRUE);
155
156 $errorMsg = array();
157 foreach ($fld as $k => $v) {
158 if (!$v[1]) {
159 $errorMsg["operator[$v[3]][$v[4]]"] = ts("Please enter the operator.");
160 }
161 else {
162 // CRM-10338
163 $v[2] = self::checkArrayKeyEmpty($v[2]);
164
e8e8f3ad 165 if (in_array($v[1], array(
166 'IS NULL',
167 'IS NOT NULL',
168 'IS EMPTY',
169 'IS NOT EMPTY',
170 )) &&
353ffa53
TO
171 !empty($v[2])
172 ) {
6a488035
TO
173 $errorMsg["value[$v[3]][$v[4]]"] = ts('Please clear your value if you want to use %1 operator.', array(1 => $v[1]));
174 }
6a488035
TO
175 elseif (substr($v[0], 0, 7) === 'do_not_' or substr($v[0], 0, 3) === 'is_') {
176 if (isset($v[2])) {
177 $v2 = array($v[2]);
178 if (!isset($v[2])) {
179 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
180 }
181
182 $error = CRM_Utils_Type::validate($v2[0], 'Integer', FALSE);
183 if ($error != $v2[0]) {
184 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a valid value.");
185 }
186 }
187 else {
188 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
189 }
190 }
191 else {
192 if (substr($v[0], 0, 7) == 'custom_') {
442df34b
CW
193 // Get rid of appended location type id
194 list($fieldKey) = explode('-', $v[0]);
195 $type = $fields[$fieldKey]['data_type'];
6a488035
TO
196
197 // hack to handle custom data of type state and country
198 if (in_array($type, array(
353ffa53 199 'Country',
408b79bf 200 'StateProvince',
353ffa53 201 ))) {
6a488035
TO
202 $type = "Integer";
203 }
204 }
205 else {
206 $fldName = $v[0];
207 // FIXME: no idea at this point what to do with this,
208 // FIXME: but definitely needs fixing.
209 if (substr($v[0], 0, 13) == 'contribution_') {
210 $fldName = substr($v[0], 13);
211 }
212
213 $fldValue = CRM_Utils_Array::value($fldName, $fields);
214 $fldType = CRM_Utils_Array::value('type', $fldValue);
215 $type = CRM_Utils_Type::typeToString($fldType);
fbc6a4d4 216
217 if (strstr($v[1], 'IN')) {
218 if (empty($v[2])) {
219 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
220 }
221 }
6a488035 222 // Check Empty values for Integer Or Boolean Or Date type For operators other than IS NULL and IS NOT NULL.
fbc6a4d4 223 elseif (!in_array($v[1],
353ffa53
TO
224 array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))
225 ) {
dbc6f6d6 226 if ((($type == 'Int' || $type == 'Boolean') && !is_array($v[2]) && !trim($v[2])) && $v[2] != '0') {
6a488035
TO
227 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
228 }
229 elseif ($type == 'Date' && !trim($v[2])) {
230 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a value.");
231 }
232 }
233 }
234
235 if ($type && empty($errorMsg)) {
236 // check for valid format while using IN Operator
fbc6a4d4 237 if (strstr($v[1], 'IN')) {
dbc6f6d6 238 if (!is_array($v[2])) {
239 $inVal = trim($v[2]);
240 //checking for format to avoid db errors
241 if ($type == 'Int') {
fccb6a0f 242 if (!preg_match('/^[A-Za-z0-9\,]+$/', $inVal)) {
dbc6f6d6 243 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter correct Data (in valid format).");
244 }
6a488035 245 }
dbc6f6d6 246 else {
fccb6a0f 247 if (!preg_match('/^[A-Za-z0-9åäöÅÄÖüÜœŒæÆøØ()\,\s]+$/', $inVal)) {
dbc6f6d6 248 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter correct Data (in valid format).");
249 }
6a488035
TO
250 }
251 }
252
253 // Validate each value in parenthesis to avoid db errors
254 if (empty($errorMsg)) {
255 $parenValues = array();
efb88612 256 $parenValues = is_array($v[2]) ? (array_key_exists($v[1], $v[2])) ? $v[2][$v[1]] : $v[2] : explode(',', trim($inVal, "(..)"));
6a488035 257 foreach ($parenValues as $val) {
fbc6a4d4 258 if ($type == 'Date' || $type == 'Timestamp') {
259 $val = CRM_Utils_Date::processDate($val);
260 if ($type == 'Date') {
261 $val = substr($val, 0, 8);
262 }
263 }
264 else {
265 $val = trim($val);
266 }
6a488035
TO
267 if (!$val && $val != '0') {
268 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter the values correctly.");
269 }
270 if (empty($errorMsg)) {
271 $error = CRM_Utils_Type::validate($val, $type, FALSE);
272 if ($error != $val) {
273 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a valid value.");
274 }
275 }
276 }
277 }
278 }
279 elseif (trim($v[2])) {
280 //else check value for rest of the Operators
281 $error = CRM_Utils_Type::validate($v[2], $type, FALSE);
282 if ($error != $v[2]) {
283 $errorMsg["value[$v[3]][$v[4]]"] = ts("Please enter a valid value.");
284 }
285 }
286 }
287 }
288 }
289 }
290
291 if (!empty($errorMsg)) {
292 $self->set('showSearchForm', TRUE);
293 $self->assign('rows', NULL);
294 return $errorMsg;
295 }
296
297 return TRUE;
298 }
299
e8e8f3ad 300 /**
301 * Normalise form values.
302 */
6ea503d4
TO
303 public function normalizeFormValues() {
304 }
6a488035 305
86538308 306 /**
e8e8f3ad 307 * Convert form values.
308 *
309 * @param array $formValues
86538308
EM
310 *
311 * @return array
312 */
b9e573d4 313 public function convertFormValues(&$formValues) {
6a488035
TO
314 return CRM_Core_BAO_Mapping::formattedFields($formValues);
315 }
316
86538308 317 /**
e8e8f3ad 318 * Get return properties.
319 *
86538308
EM
320 * @return array
321 */
6a488035
TO
322 public function &returnProperties() {
323 return CRM_Core_BAO_Mapping::returnProperties($this->_formValues);
324 }
325
326 /**
fe482240 327 * Process the uploaded file.
6a488035
TO
328 */
329 public function postProcess() {
330 $this->set('isAdvanced', '2');
331 $this->set('isSearchBuilder', '1');
332 $this->set('showSearchForm', FALSE);
333
334 $params = $this->controller->exportValues($this->_name);
335 if (!empty($params)) {
336 // Add another block
337 if (!empty($params['addBlock'])) {
338 $this->set('newBlock', $this->_blockCount);
339 $this->_blockCount += 3;
340 $this->set('blockCount', $this->_blockCount);
341 $this->set('showSearchForm', TRUE);
342 return;
343 }
344 // Add another field
345 $addMore = CRM_Utils_Array::value('addMore', $params);
346 for ($x = 1; $x <= $this->_blockCount; $x++) {
347 if (!empty($addMore[$x])) {
353ffa53 348 $this->set('newBlock', $x);
6a488035
TO
349 $this->_columnCount[$x] = $this->_columnCount[$x] + 5;
350 $this->set('columnCount', $this->_columnCount);
351 $this->set('showSearchForm', TRUE);
352 return;
353 }
354 }
355 $this->set('newBlock', NULL);
356 $checkEmpty = NULL;
357 foreach ($params['mapper'] as $key => $value) {
358 foreach ($value as $k => $v) {
359 if ($v[0]) {
360 $checkEmpty++;
361 }
362 }
363 }
364
365 if (!$checkEmpty) {
366 $this->set('newBlock', 1);
367 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/search/builder', '_qf_Builder_display=true'));
368 }
369 }
370
371 // get user submitted values
372 // get it from controller only if form has been submitted, else preProcess has set this
373 if (!empty($_POST)) {
374 $this->_formValues = $this->controller->exportValues($this->_name);
375
376 // set the group if group is submitted
a7488080 377 if (!empty($this->_formValues['uf_group_id'])) {
6a488035
TO
378 $this->set('id', $this->_formValues['uf_group_id']);
379 }
380 else {
381 $this->set('id', '');
382 }
383 }
384
385 // we dont want to store the sortByCharacter in the formValue, it is more like
386 // a filter on the result set
387 // this filter is reset if we click on the search button
388 if ($this->_sortByCharacter !== NULL && empty($_POST)) {
389 if (strtolower($this->_sortByCharacter) == 'all') {
390 $this->_formValues['sortByCharacter'] = NULL;
391 }
392 else {
393 $this->_formValues['sortByCharacter'] = $this->_sortByCharacter;
394 }
395 }
e166ff79
CW
396 else {
397 $this->_sortByCharacter = NULL;
398 }
6a488035 399
b9e573d4 400 $this->_params = $this->convertFormValues($this->_formValues);
6a488035
TO
401 $this->_returnProperties = &$this->returnProperties();
402
403 // CRM-10338 check if value is empty array
404 foreach ($this->_params as $k => $v) {
405 $this->_params[$k][2] = self::checkArrayKeyEmpty($v[2]);
406 }
407
408 parent::postProcess();
409 }
410
86538308 411 /**
e8e8f3ad 412 * Get fields.
413 *
86538308
EM
414 * @return array
415 */
00be9182 416 public static function fields() {
e1ab2e91 417 $fields = array_merge(
6a488035
TO
418 CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE),
419 CRM_Core_Component::getQueryFields(),
eb1e3589 420 CRM_Contact_BAO_Query_Hook::singleton()->getFields(),
6a488035
TO
421 CRM_Activity_BAO_Activity::exportableFields()
422 );
e1ab2e91 423 return $fields;
6a488035
TO
424 }
425
426 /**
427 * CRM-9434 Hackish function to fetch fields with options.
e8e8f3ad 428 *
6a488035 429 * FIXME: When our core fields contain reliable metadata this will be much simpler.
a6c01b45
CW
430 * @return array
431 * (string => string) key: field_name value: api entity name
408b79bf 432 * Note: options are fetched via ajax using the api "getoptions" method
6a488035 433 */
00be9182 434 public static function fieldOptions() {
6a488035
TO
435 // Hack to add options not retrieved by getfields
436 // This list could go on and on, but it would be better to fix getfields
437 $options = array(
e354351f 438 'group' => 'group_contact',
439 'tag' => 'entity_tag',
6a488035
TO
440 'on_hold' => 'yesno',
441 'is_bulkmail' => 'yesno',
6a488035
TO
442 'payment_instrument' => 'contribution',
443 'membership_status' => 'membership',
444 'membership_type' => 'membership',
e5d696ef 445 'member_campaign_id' => 'membership',
67744c4e
CW
446 'member_is_test' => 'yesno',
447 'member_is_pay_later' => 'yesno',
448 'is_override' => 'yesno',
6a488035 449 );
353ffa53
TO
450 $entities = array(
451 'contact',
452 'address',
453 'activity',
454 'participant',
455 'pledge',
456 'member',
457 'contribution',
458 'case',
408b79bf 459 'grant',
353ffa53 460 );
6a5f199e 461 CRM_Contact_BAO_Query_Hook::singleton()->alterSearchBuilderOptions($entities, $options);
6a488035 462 foreach ($entities as $entity) {
67744c4e 463 $fields = civicrm_api3($entity, 'getfields');
6a488035 464 foreach ($fields['values'] as $field => $info) {
4b5ff63c 465 if (!empty($info['options']) || !empty($info['pseudoconstant']) || !empty($info['option_group_id'])) {
6a488035 466 $options[$field] = $entity;
e61022d7 467 // Hack for when search field doesn't match db field - e.g. "country" instead of "country_id"
6a488035
TO
468 if (substr($field, -3) == '_id') {
469 $options[substr($field, 0, -3)] = $entity;
470 }
471 }
89d4a22f 472 elseif (!empty($info['data_type'])) {
473 if (in_array($info['data_type'], array('StateProvince', 'Country'))) {
474 $options[$field] = $entity;
475 }
e61022d7 476 }
353ffa53
TO
477 elseif (in_array(substr($field, 0, 3), array(
478 'is_',
408b79bf 479 'do_',
353ffa53
TO
480 )) || CRM_Utils_Array::value('data_type', $info) == 'Boolean'
481 ) {
6a488035
TO
482 $options[$field] = 'yesno';
483 if ($entity != 'contact') {
484 $options[$entity . '_' . $field] = 'yesno';
485 }
486 }
487 elseif (strpos($field, '_is_')) {
488 $options[$field] = 'yesno';
489 }
490 }
491 }
492 return $options;
493 }
494
495 /**
ea3ddccf 496 * CRM-10338 tags and groups use array keys for selection list.
497 *
6a488035 498 * if using IS NULL/NOT NULL, an array with no array key is created
e60f24eb 499 * convert that to simple NULL so processing can proceed
ea3ddccf 500 *
501 * @param string $val
502 *
503 * @return null
6a488035 504 */
00be9182 505 public static function checkArrayKeyEmpty($val) {
6a488035 506 if (is_array($val)) {
4eeb9a5b 507 $v2empty = TRUE;
6a488035
TO
508 foreach ($val as $vk => $vv) {
509 if (!empty($vk)) {
ab8a593e 510 $v2empty = FALSE;
6a488035
TO
511 }
512 }
513 if ($v2empty) {
e60f24eb 514 $val = NULL;
6a488035
TO
515 }
516 }
517 return $val;
518 }
96025800 519
6a488035 520}