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