3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
32 * @copyright CiviCRM LLC (c) 2004-2015
34 class CRM_Core_BAO_CustomQuery
{
35 const PREFIX
= 'custom_value_';
38 * The set of custom field ids.
52 * The name of the elements that are in the select clause.
53 * used to extract the values
60 * The tables involved in the query.
75 * The english language version of the query.
82 * The cache to translate the option values into labels.
89 * The custom fields information.
96 * Searching for contacts?
100 protected $_contactSearch;
102 protected $_locationSpecificCustomFields;
105 * This stores custom data group types and tables that it extends.
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',
132 * Takes in a set of custom field ids andsets up the data structures to
136 * The set of custom field ids.
138 * @param bool $contactSearch
139 * @param array $locationSpecificFields
141 public function __construct($ids, $contactSearch = FALSE, $locationSpecificFields = array()) {
143 $this->_locationSpecificCustomFields
= $locationSpecificFields;
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();
153 $this->_fields
= array();
154 $this->_contactSearch
= $contactSearch;
156 if (empty($this->_ids
)) {
160 // initialize the field array
161 $tmpArray = array_keys($this->_ids
);
162 $idString = implode(',', $tmpArray);
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
174 AND f.id IN ( $idString )";
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];
183 elseif (in_array($extends, CRM_Contact_BAO_ContactType
::subTypes())) {
184 // if $extends is a subtype, refer contact table
185 $extendsTable = self
::$extendsMap['Contact'];
187 $this->_fields
[$dao->id
] = array(
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
,
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
,
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
;
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
)
218 CRM_Core_Error
::fatal($errorMessage);
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
;
226 // build the cache for custom values with options (label => value)
227 if ($optionGroupID != NULL) {
230 FROM civicrm_option_value
231 WHERE option_group_id = $optionGroupID
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
;
242 $this->_options
[$dao->id
][$option->value
] = $option->label
;
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);
254 * Generate the select clause and the associated tables.
256 public function select() {
257 if (empty($this->_fields
)) {
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;
270 if ($field['extends'] == 'civicrm_group') {
273 elseif ($field['extends'] == 'civicrm_contact') {
274 $joinTable = 'contact_a';
276 elseif ($field['extends'] == 'civicrm_contribution') {
277 $joinTable = $field['extends'];
279 elseif (in_array($field['extends'], self
::$extendsMap)) {
280 $joinTable = $field['extends'];
286 $this->_tables
[$name] = "\nLEFT JOIN $name ON $name.entity_id = $joinTable.id";
288 if ($this->_ids
[$id]) {
289 $this->_whereTables
[$name] = $this->_tables
[$name];
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)";
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];
305 if ($joinTable != 'contact_a') {
306 $this->_whereTables
[$joinTableAlias] = $this->_tables
[$joinTableAlias] = $joinClause;
308 elseif ($this->_contactSearch
) {
309 CRM_Contact_BAO_Query
::$_openedPanes[ts('Custom Fields')] = TRUE;
316 * Generate the where clause and also the english language equivalent.
318 public function where() {
319 foreach ($this->_ids
as $id => $values) {
321 // Fixed for Issue CRM 607
322 if (CRM_Utils_Array
::value($id, $this->_fields
) === NULL ||
328 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
330 foreach ($values as $tuple) {
331 list($name, $op, $value, $grouping, $wildcard) = $tuple;
333 $field = $this->_fields
[$id];
335 $fieldName = "{$field['table_name']}.{$field['column_name']}";
337 $isSerialized = CRM_Core_BAO_CustomField
::isSerialized($field);
339 // fix $value here to escape sql injection attacks
341 if (!is_array($value)) {
342 $value = CRM_Core_DAO
::escapeString(trim($value));
343 $qillValue = CRM_Core_BAO_CustomField
::getDisplayValue($value, $id, $this->_options
);
345 elseif (count($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
347 $qillValue = strstr($op, 'NULL') ?
NULL : CRM_Core_BAO_CustomField
::getDisplayValue($value[$op], $id, $this->_options
);
350 $op = strstr($op, 'IN') ?
$op : 'IN';
351 $qillValue = CRM_Core_BAO_CustomField
::getDisplayValue($value, $id, $this->_options
);
354 $qillOp = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
356 switch ($field['data_type']) {
358 case 'StateProvince':
361 if ($field['is_search_range'] && is_array($value)) {
362 $this->searchRange($field['id'],
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');
377 $value = CRM_Utils_Type
::escape($value, 'Integer');
380 elseif ($isSerialized) {
381 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
383 $value = $value[$op];
385 $value = implode(',', (array) $value);
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);
396 $op = (strstr($op, '!') ||
strstr($op, 'NOT')) ?
'NOT RLIKE' : 'RLIKE';
397 $value = $sp . $value . $sp;
399 foreach (explode("|", $value) as $val) {
400 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldName, $op, $val, 'String');
404 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldName, $op, $value, 'String');
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');
411 $this->_qill
[$grouping][] = "$field[label] $qillOp $qillValue";
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";
422 if ($field['is_search_range'] && is_array($value)) {
423 $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
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));;
432 if (!is_array($value)) {
433 if (strtolower($value) == 'yes' ||
strtolower($value) == strtolower(ts('Yes'))) {
437 $value = (int) $value;
439 $value = ($value == 1) ?
1 : 0;
440 $qillValue = $value ?
'Yes' : 'No';
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));
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));
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]);
460 $value = CRM_Utils_Rule
::cleanMoney($value);
464 if ($field['is_search_range']) {
465 $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
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));
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'";
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);
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'))) {
491 // hack to handle yy format during search
492 if (is_numeric($value) && strlen($value) == 4) {
493 $value = "01-01-{$value}";
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]);
504 $date = CRM_Utils_Date
::processDate($value);
505 $qillValue = CRM_Utils_Date
::customFormat($date);
508 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldName, $op, $date, 'String');
509 $this->_qill
[$grouping][] = $field['label'] . " {$qillOp} " . implode(', ', (array) $qillValue);
512 if (is_numeric($fromValue) && strlen($fromValue) == 4) {
513 $fromValue = "01-01-{$fromValue}";
516 if (is_numeric($toValue) && strlen($toValue) == 4) {
517 $toValue = "01-01-{$toValue}";
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) {
527 $this->_where
[$grouping][] = "$fieldName >= $fromDate";
528 $this->_qill
[$grouping][] = $field['label'] . ' >= ' . CRM_Utils_Date
::customFormat($fromDate);
531 $this->_where
[$grouping][] = "$fieldName <= $toDate";
532 $this->_qill
[$grouping][] = $field['label'] . ' <= ' . CRM_Utils_Date
::customFormat($toDate);
538 if ($op == 'IS NULL' ||
$op == 'IS NOT NULL' ||
$op == 'IS EMPTY' ||
$op == 'IS NOT EMPTY') {
548 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldName, $op);
549 $this->_qill
[$grouping][] = $field['label'] . " {$qillOp} ";
558 * Function that does the actual query generation.
559 * basically ties all the above functions together
564 public function query() {
570 if (!empty($this->_where
)) {
572 foreach ($this->_where
as $grouping => $values) {
573 if (!empty($values)) {
574 $clauses[] = ' ( ' . implode(' AND ', $values) . ' ) ';
577 if (!empty($clauses)) {
578 $whereStr = ' ( ' . implode(' OR ', $clauses) . ' ) ';
583 implode(' , ', $this->_select
),
584 implode(' ', $this->_tables
),
593 * @param string $fieldName
597 public function searchRange(&$id, &$label, $type, $fieldName, &$value, &$grouping) {
600 if (isset($value['from'])) {
601 $val = CRM_Utils_Type
::escape($value['from'], $type);
603 if ($type == 'String') {
604 $this->_where
[$grouping][] = "$fieldName >= '$val'";
607 $this->_where
[$grouping][] = "$fieldName >= $val";
609 $qill[] = ts('greater than or equal to \'%1\'', array(1 => $value['from']));
612 if (isset($value['to'])) {
613 $val = CRM_Utils_Type
::escape($value['to'], $type);
614 if ($type == 'String') {
615 $this->_where
[$grouping][] = "$fieldName <= '$val'";
618 $this->_where
[$grouping][] = "$fieldName <= $val";
620 $qill[] = ts('less than or equal to \'%1\'', array(1 => $value['to']));
624 $this->_qill
[$grouping][] = $label . ' - ' . implode(' ' . ts('and') . ' ', $qill);