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