Merge remote-tracking branch 'upstream/4.6' into 4.6-master-2015-11-23-22-46-27
[civicrm-core.git] / CRM / Core / BAO / CustomQuery.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 *
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2015
33 */
34 class CRM_Core_BAO_CustomQuery {
35 const PREFIX = 'custom_value_';
36
37 /**
38 * The set of custom field ids.
39 *
40 * @var array
41 */
42 protected $_ids;
43
44 /**
45 * The select clause.
46 *
47 * @var array
48 */
49 public $_select;
50
51 /**
52 * The name of the elements that are in the select clause.
53 * used to extract the values
54 *
55 * @var array
56 */
57 public $_element;
58
59 /**
60 * The tables involved in the query.
61 *
62 * @var array
63 */
64 public $_tables;
65 public $_whereTables;
66
67 /**
68 * The where clause.
69 *
70 * @var array
71 */
72 public $_where;
73
74 /**
75 * The english language version of the query.
76 *
77 * @var array
78 */
79 public $_qill;
80
81 /**
82 * The cache to translate the option values into labels.
83 *
84 * @var array
85 */
86 public $_options;
87
88 /**
89 * The custom fields information.
90 *
91 * @var array
92 */
93 public $_fields;
94
95 /**
96 * Searching for contacts?
97 *
98 * @var boolean
99 */
100 protected $_contactSearch;
101
102 protected $_locationSpecificCustomFields;
103
104 /**
105 * This stores custom data group types and tables that it extends.
106 *
107 * @var array
108 */
109 static $extendsMap = array(
110 'Contact' => 'civicrm_contact',
111 'Individual' => 'civicrm_contact',
112 'Household' => 'civicrm_contact',
113 'Organization' => 'civicrm_contact',
114 'Contribution' => 'civicrm_contribution',
115 'Membership' => 'civicrm_membership',
116 'Participant' => 'civicrm_participant',
117 'Group' => 'civicrm_group',
118 'Relationship' => 'civicrm_relationship',
119 'Event' => 'civicrm_event',
120 'Case' => 'civicrm_case',
121 'Activity' => 'civicrm_activity',
122 'Pledge' => 'civicrm_pledge',
123 'Grant' => 'civicrm_grant',
124 'Address' => 'civicrm_address',
125 'Campaign' => 'civicrm_campaign',
126 'Survey' => 'civicrm_survey',
127 );
128
129 /**
130 * Class constructor.
131 *
132 * Takes in a set of custom field ids andsets up the data structures to
133 * generate a query
134 *
135 * @param array $ids
136 * The set of custom field ids.
137 *
138 * @param bool $contactSearch
139 * @param array $locationSpecificFields
140 */
141 public function __construct($ids, $contactSearch = FALSE, $locationSpecificFields = array()) {
142 $this->_ids = &$ids;
143 $this->_locationSpecificCustomFields = $locationSpecificFields;
144
145 $this->_select = array();
146 $this->_element = array();
147 $this->_tables = array();
148 $this->_whereTables = array();
149 $this->_where = array();
150 $this->_qill = array();
151 $this->_options = array();
152
153 $this->_fields = array();
154 $this->_contactSearch = $contactSearch;
155
156 if (empty($this->_ids)) {
157 return;
158 }
159
160 // initialize the field array
161 $tmpArray = array_keys($this->_ids);
162 $idString = implode(',', $tmpArray);
163 $query = "
164 SELECT f.id, f.label, f.data_type,
165 f.html_type, f.is_search_range,
166 f.option_group_id, f.custom_group_id,
167 f.column_name, g.table_name,
168 f.date_format,f.time_format
169 FROM civicrm_custom_field f,
170 civicrm_custom_group g
171 WHERE f.custom_group_id = g.id
172 AND g.is_active = 1
173 AND f.is_active = 1
174 AND f.id IN ( $idString )";
175
176 $dao = CRM_Core_DAO::executeQuery($query);
177 while ($dao->fetch()) {
178 // get the group dao to figure which class this custom field extends
179 $extends = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $dao->custom_group_id, 'extends');
180 if (array_key_exists($extends, self::$extendsMap)) {
181 $extendsTable = self::$extendsMap[$extends];
182 }
183 elseif (in_array($extends, CRM_Contact_BAO_ContactType::subTypes())) {
184 // if $extends is a subtype, refer contact table
185 $extendsTable = self::$extendsMap['Contact'];
186 }
187 $this->_fields[$dao->id] = array(
188 'id' => $dao->id,
189 'label' => $dao->label,
190 'extends' => $extendsTable,
191 'data_type' => $dao->data_type,
192 'html_type' => $dao->html_type,
193 'is_search_range' => $dao->is_search_range,
194 'column_name' => $dao->column_name,
195 'table_name' => $dao->table_name,
196 'option_group_id' => $dao->option_group_id,
197 );
198
199 // store it in the options cache to make things easier
200 // during option lookup
201 $this->_options[$dao->id] = array();
202 $this->_options[$dao->id]['attributes'] = array(
203 'label' => $dao->label,
204 'data_type' => $dao->data_type,
205 'html_type' => $dao->html_type,
206 );
207
208 $optionGroupID = NULL;
209 $htmlTypes = array('CheckBox', 'Radio', 'Select', 'Multi-Select', 'AdvMulti-Select', 'Autocomplete-Select');
210 if (in_array($dao->html_type, $htmlTypes) && $dao->data_type != 'ContactReference') {
211 if ($dao->option_group_id) {
212 $optionGroupID = $dao->option_group_id;
213 }
214 elseif ($dao->data_type != 'Boolean') {
215 $errorMessage = ts("The custom field %1 is corrupt. Please delete and re-build the field",
216 array(1 => $dao->label)
217 );
218 CRM_Core_Error::fatal($errorMessage);
219 }
220 }
221 elseif ($dao->html_type == 'Select Date') {
222 $this->_options[$dao->id]['attributes']['date_format'] = $dao->date_format;
223 $this->_options[$dao->id]['attributes']['time_format'] = $dao->time_format;
224 }
225
226 // build the cache for custom values with options (label => value)
227 if ($optionGroupID != NULL) {
228 $query = "
229 SELECT label, value
230 FROM civicrm_option_value
231 WHERE option_group_id = $optionGroupID
232 ";
233
234 $option = CRM_Core_DAO::executeQuery($query);
235 while ($option->fetch()) {
236 $dataType = $this->_fields[$dao->id]['data_type'];
237 if ($dataType == 'Int' || $dataType == 'Float') {
238 $num = round($option->value, 2);
239 $this->_options[$dao->id]["$num"] = $option->label;
240 }
241 else {
242 $this->_options[$dao->id][$option->value] = $option->label;
243 }
244 }
245 $options = $this->_options[$dao->id];
246 //unset attributes to avoid confussion
247 unset($options['attributes']);
248 CRM_Utils_Hook::customFieldOptions($dao->id, $options, FALSE);
249 }
250 }
251 }
252
253 /**
254 * Generate the select clause and the associated tables.
255 */
256 public function select() {
257 if (empty($this->_fields)) {
258 return;
259 }
260
261 foreach ($this->_fields as $id => $field) {
262 $name = $field['table_name'];
263 $fieldName = 'custom_' . $field['id'];
264 $this->_select["{$name}_id"] = "{$name}.id as {$name}_id";
265 $this->_element["{$name}_id"] = 1;
266 $this->_select[$fieldName] = "{$field['table_name']}.{$field['column_name']} as $fieldName";
267 $this->_element[$fieldName] = 1;
268 $joinTable = NULL;
269 // CRM-14265
270 if ($field['extends'] == 'civicrm_group') {
271 return;
272 }
273 elseif ($field['extends'] == 'civicrm_contact') {
274 $joinTable = 'contact_a';
275 }
276 elseif ($field['extends'] == 'civicrm_contribution') {
277 $joinTable = $field['extends'];
278 }
279 elseif (in_array($field['extends'], self::$extendsMap)) {
280 $joinTable = $field['extends'];
281 }
282 else {
283 return;
284 }
285
286 $this->_tables[$name] = "\nLEFT JOIN $name ON $name.entity_id = $joinTable.id";
287
288 if ($this->_ids[$id]) {
289 $this->_whereTables[$name] = $this->_tables[$name];
290 }
291
292 if ($joinTable) {
293 $joinClause = 1;
294 $joinTableAlias = $joinTable;
295 // Set location-specific query
296 if (isset($this->_locationSpecificCustomFields[$id])) {
297 list($locationType, $locationTypeId) = $this->_locationSpecificCustomFields[$id];
298 $joinTableAlias = "$locationType-address";
299 $joinClause = "\nLEFT JOIN $joinTable `$locationType-address` ON (`$locationType-address`.contact_id = contact_a.id AND `$locationType-address`.location_type_id = $locationTypeId)";
300 }
301 $this->_tables[$name] = "\nLEFT JOIN $name ON $name.entity_id = `$joinTableAlias`.id";
302 if ($this->_ids[$id]) {
303 $this->_whereTables[$name] = $this->_tables[$name];
304 }
305 if ($joinTable != 'contact_a') {
306 $this->_whereTables[$joinTableAlias] = $this->_tables[$joinTableAlias] = $joinClause;
307 }
308 elseif ($this->_contactSearch) {
309 CRM_Contact_BAO_Query::$_openedPanes[ts('Custom Fields')] = TRUE;
310 }
311 }
312 }
313 }
314
315 /**
316 * Generate the where clause and also the english language equivalent.
317 */
318 public function where() {
319 foreach ($this->_ids as $id => $values) {
320
321 // Fixed for Issue CRM 607
322 if (CRM_Utils_Array::value($id, $this->_fields) === NULL ||
323 !$values
324 ) {
325 continue;
326 }
327
328 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
329
330 foreach ($values as $tuple) {
331 list($name, $op, $value, $grouping, $wildcard) = $tuple;
332
333 $field = $this->_fields[$id];
334
335 $fieldName = "{$field['table_name']}.{$field['column_name']}";
336
337 $isSerialized = CRM_Core_BAO_CustomField::isSerialized($field);
338
339 // fix $value here to escape sql injection attacks
340 $qillValue = NULL;
341 if (!is_array($value)) {
342 $value = CRM_Core_DAO::escapeString(trim($value));
343 $qillValue = CRM_Core_BAO_CustomField::getDisplayValue($value, $id, $this->_options);
344 }
345 elseif (count($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
346 $op = key($value);
347 $qillValue = strstr($op, 'NULL') ? NULL : CRM_Core_BAO_CustomField::getDisplayValue($value[$op], $id, $this->_options);
348 }
349 else {
350 $op = strstr($op, 'IN') ? $op : 'IN';
351 $qillValue = CRM_Core_BAO_CustomField::getDisplayValue($value, $id, $this->_options);
352 }
353
354 $qillOp = CRM_Utils_Array::value($op, CRM_Core_SelectValues::getSearchBuilderOperators(), $op);
355
356 switch ($field['data_type']) {
357 case 'String':
358 case 'StateProvince':
359 case 'Country':
360
361 if ($field['is_search_range'] && is_array($value)) {
362 $this->searchRange($field['id'],
363 $field['label'],
364 $field['data_type'],
365 $fieldName,
366 $value,
367 $grouping
368 );
369 }
370 else {
371 // fix $value here to escape sql injection attacks
372 if (!is_array($value)) {
373 if ($field['data_type'] == 'String') {
374 $value = CRM_Utils_Type::escape($strtolower($value), 'String');
375 }
376 else {
377 $value = CRM_Utils_Type::escape($value, 'Integer');
378 }
379 }
380 elseif ($isSerialized) {
381 if (in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
382 $op = key($value);
383 $value = $value[$op];
384 }
385 $value = implode(',', (array) $value);
386 }
387
388 // CRM-14563,CRM-16575 : Special handling of multi-select custom fields
389 if ($isSerialized && !empty($value) && !strstr($op, 'NULL') && !strstr($op, 'LIKE')) {
390 $sp = CRM_Core_DAO::VALUE_SEPARATOR;
391 if (strstr($op, 'IN')) {
392 $value = str_replace(",", "$sp|$sp", $value);
393 $value = str_replace('(', '[[.left-parenthesis.]]', $value);
394 $value = str_replace(')', '[[.right-parenthesis.]]', $value);
395 }
396 $op = (strstr($op, '!') || strstr($op, 'NOT')) ? 'NOT RLIKE' : 'RLIKE';
397 $value = $sp . $value . $sp;
398 if (!$wildcard) {
399 foreach (explode("|", $value) as $val) {
400 $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $val, 'String');
401 }
402 }
403 else {
404 $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
405 }
406 }
407 else {
408 //FIX for custom data query fired against no value(NULL/NOT NULL)
409 $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
410 }
411 $this->_qill[$grouping][] = "$field[label] $qillOp $qillValue";
412 }
413 break;
414
415 case 'ContactReference':
416 $label = $value ? CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name') : '';
417 $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
418 $this->_qill[$grouping][] = $field['label'] . " $qillOp $label";
419 break;
420
421 case 'Int':
422 if ($field['is_search_range'] && is_array($value)) {
423 $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
424 }
425 else {
426 $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Integer');
427 $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));;
428 }
429 break;
430
431 case 'Boolean':
432 if (!is_array($value)) {
433 if (strtolower($value) == 'yes' || strtolower($value) == strtolower(ts('Yes'))) {
434 $value = 1;
435 }
436 else {
437 $value = (int) $value;
438 }
439 $value = ($value == 1) ? 1 : 0;
440 $qillValue = $value ? 'Yes' : 'No';
441 }
442 $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Integer');
443 $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
444 break;
445
446 case 'Link':
447 case 'Memo':
448 $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
449 $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
450 break;
451
452 case 'Money':
453 $value = CRM_Utils_Array::value($op, (array) $value, $value);
454 if (is_array($value)) {
455 foreach ($value as $key => $val) {
456 $value[$key] = CRM_Utils_Rule::cleanMoney($value[$key]);
457 }
458 }
459 else {
460 $value = CRM_Utils_Rule::cleanMoney($value);
461 }
462
463 case 'Float':
464 if ($field['is_search_range']) {
465 $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
466 }
467 else {
468 $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Float');
469 $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
470 }
471 break;
472
473 case 'Date':
474 if (in_array($op, CRM_Core_DAO::acceptedSQLOperators())) {
475 $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
476 list($qillOp, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $field['label'], $value,
477 $op, array(), CRM_Utils_Type::T_DATE);
478 $this->_qill[$grouping][] = "{$field['label']} $qillOp '$qillVal'";
479 break;
480 }
481
482 $fromValue = CRM_Utils_Array::value('from', $value);
483 $toValue = CRM_Utils_Array::value('to', $value);
484 $value = CRM_Utils_Array::value($op, $value, $value);
485
486 if (!$fromValue && !$toValue) {
487 if (!is_array($value) && !CRM_Utils_Date::processDate($value) && !in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
488 continue;
489 }
490
491 // hack to handle yy format during search
492 if (is_numeric($value) && strlen($value) == 4) {
493 $value = "01-01-{$value}";
494 }
495
496 if (is_array($value)) {
497 $date = $qillValue = array();
498 foreach ($value as $key => $val) {
499 $date[$key] = CRM_Utils_Date::processDate($val);
500 $qillValue[$key] = CRM_Utils_Date::customFormat($date[$key]);
501 }
502 }
503 else {
504 $date = CRM_Utils_Date::processDate($value);
505 $qillValue = CRM_Utils_Date::customFormat($date);
506 }
507
508 $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $date, 'String');
509 $this->_qill[$grouping][] = $field['label'] . " {$qillOp} " . implode(', ', (array) $qillValue);
510 }
511 else {
512 if (is_numeric($fromValue) && strlen($fromValue) == 4) {
513 $fromValue = "01-01-{$fromValue}";
514 }
515
516 if (is_numeric($toValue) && strlen($toValue) == 4) {
517 $toValue = "01-01-{$toValue}";
518 }
519
520 // TO DO: add / remove time based on date parts
521 $fromDate = CRM_Utils_Date::processDate($fromValue);
522 $toDate = CRM_Utils_Date::processDate($toValue);
523 if (!$fromDate && !$toDate) {
524 continue;
525 }
526 if ($fromDate) {
527 $this->_where[$grouping][] = "$fieldName >= $fromDate";
528 $this->_qill[$grouping][] = $field['label'] . ' >= ' . CRM_Utils_Date::customFormat($fromDate);
529 }
530 if ($toDate) {
531 $this->_where[$grouping][] = "$fieldName <= $toDate";
532 $this->_qill[$grouping][] = $field['label'] . ' <= ' . CRM_Utils_Date::customFormat($toDate);
533 }
534 }
535 break;
536
537 case 'File':
538 if ($op == 'IS NULL' || $op == 'IS NOT NULL' || $op == 'IS EMPTY' || $op == 'IS NOT EMPTY') {
539 switch ($op) {
540 case 'IS EMPTY':
541 $op = 'IS NULL';
542 break;
543
544 case 'IS NOT EMPTY':
545 $op = 'IS NOT NULL';
546 break;
547 }
548 $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op);
549 $this->_qill[$grouping][] = $field['label'] . " {$qillOp} ";
550 }
551 break;
552 }
553 }
554 }
555 }
556
557 /**
558 * Function that does the actual query generation.
559 * basically ties all the above functions together
560 *
561 * @return array
562 * array of strings
563 */
564 public function query() {
565 $this->select();
566
567 $this->where();
568
569 $whereStr = NULL;
570 if (!empty($this->_where)) {
571 $clauses = array();
572 foreach ($this->_where as $grouping => $values) {
573 if (!empty($values)) {
574 $clauses[] = ' ( ' . implode(' AND ', $values) . ' ) ';
575 }
576 }
577 if (!empty($clauses)) {
578 $whereStr = ' ( ' . implode(' OR ', $clauses) . ' ) ';
579 }
580 }
581
582 return array(
583 implode(' , ', $this->_select),
584 implode(' ', $this->_tables),
585 $whereStr,
586 );
587 }
588
589 /**
590 * @param int $id
591 * @param $label
592 * @param $type
593 * @param string $fieldName
594 * @param $value
595 * @param $grouping
596 */
597 public function searchRange(&$id, &$label, $type, $fieldName, &$value, &$grouping) {
598 $qill = array();
599
600 if (isset($value['from'])) {
601 $val = CRM_Utils_Type::escape($value['from'], $type);
602
603 if ($type == 'String') {
604 $this->_where[$grouping][] = "$fieldName >= '$val'";
605 }
606 else {
607 $this->_where[$grouping][] = "$fieldName >= $val";
608 }
609 $qill[] = ts('greater than or equal to \'%1\'', array(1 => $value['from']));
610 }
611
612 if (isset($value['to'])) {
613 $val = CRM_Utils_Type::escape($value['to'], $type);
614 if ($type == 'String') {
615 $this->_where[$grouping][] = "$fieldName <= '$val'";
616 }
617 else {
618 $this->_where[$grouping][] = "$fieldName <= $val";
619 }
620 $qill[] = ts('less than or equal to \'%1\'', array(1 => $value['to']));
621 }
622
623 if (!empty($qill)) {
624 $this->_qill[$grouping][] = $label . ' - ' . implode(' ' . ts('and') . ' ', $qill);
625 }
626 }
627
628 }