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 'ContributionRecur' => 'civicrm_contribution_recur',
116 'Membership' => 'civicrm_membership',
117 'Participant' => 'civicrm_participant',
118 'Group' => 'civicrm_group',
119 'Relationship' => 'civicrm_relationship',
120 'Event' => 'civicrm_event',
121 'Case' => 'civicrm_case',
122 'Activity' => 'civicrm_activity',
123 'Pledge' => 'civicrm_pledge',
124 'Grant' => 'civicrm_grant',
125 'Address' => 'civicrm_address',
126 'Campaign' => 'civicrm_campaign',
127 'Survey' => 'civicrm_survey',
133 * Takes in a set of custom field ids andsets up the data structures to
137 * The set of custom field ids.
139 * @param bool $contactSearch
140 * @param array $locationSpecificFields
142 public function __construct($ids, $contactSearch = FALSE, $locationSpecificFields = array()) {
144 $this->_locationSpecificCustomFields
= $locationSpecificFields;
146 $this->_select
= array();
147 $this->_element
= array();
148 $this->_tables
= array();
149 $this->_whereTables
= array();
150 $this->_where
= array();
151 $this->_qill
= array();
152 $this->_options
= array();
154 $this->_fields
= array();
155 $this->_contactSearch
= $contactSearch;
157 if (empty($this->_ids
)) {
161 // initialize the field array
162 $tmpArray = array_keys($this->_ids
);
163 $idString = implode(',', $tmpArray);
165 SELECT f.id, f.label, f.data_type,
166 f.html_type, f.is_search_range,
167 f.option_group_id, f.custom_group_id,
168 f.column_name, g.table_name,
169 f.date_format,f.time_format
170 FROM civicrm_custom_field f,
171 civicrm_custom_group g
172 WHERE f.custom_group_id = g.id
175 AND f.id IN ( $idString )";
177 $dao = CRM_Core_DAO
::executeQuery($query);
178 while ($dao->fetch()) {
179 // get the group dao to figure which class this custom field extends
180 $extends = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $dao->custom_group_id
, 'extends');
181 if (array_key_exists($extends, self
::$extendsMap)) {
182 $extendsTable = self
::$extendsMap[$extends];
184 elseif (in_array($extends, CRM_Contact_BAO_ContactType
::subTypes())) {
185 // if $extends is a subtype, refer contact table
186 $extendsTable = self
::$extendsMap['Contact'];
188 $this->_fields
[$dao->id
] = array(
190 'label' => $dao->label
,
191 'extends' => $extendsTable,
192 'data_type' => $dao->data_type
,
193 'html_type' => $dao->html_type
,
194 'is_search_range' => $dao->is_search_range
,
195 'column_name' => $dao->column_name
,
196 'table_name' => $dao->table_name
,
197 'option_group_id' => $dao->option_group_id
,
200 // store it in the options cache to make things easier
201 // during option lookup
202 $this->_options
[$dao->id
] = array();
203 $this->_options
[$dao->id
]['attributes'] = array(
204 'label' => $dao->label
,
205 'data_type' => $dao->data_type
,
206 'html_type' => $dao->html_type
,
209 $optionGroupID = NULL;
210 $htmlTypes = array('CheckBox', 'Radio', 'Select', 'Multi-Select', 'AdvMulti-Select', 'Autocomplete-Select');
211 if (in_array($dao->html_type
, $htmlTypes) && $dao->data_type
!= 'ContactReference') {
212 if ($dao->option_group_id
) {
213 $optionGroupID = $dao->option_group_id
;
215 elseif ($dao->data_type
!= 'Boolean') {
216 $errorMessage = ts("The custom field %1 is corrupt. Please delete and re-build the field",
217 array(1 => $dao->label
)
219 CRM_Core_Error
::fatal($errorMessage);
222 elseif ($dao->html_type
== 'Select Date') {
223 $this->_options
[$dao->id
]['attributes']['date_format'] = $dao->date_format
;
224 $this->_options
[$dao->id
]['attributes']['time_format'] = $dao->time_format
;
227 // build the cache for custom values with options (label => value)
228 if ($optionGroupID != NULL) {
231 FROM civicrm_option_value
232 WHERE option_group_id = $optionGroupID
235 $option = CRM_Core_DAO
::executeQuery($query);
236 while ($option->fetch()) {
237 $dataType = $this->_fields
[$dao->id
]['data_type'];
238 if ($dataType == 'Int' ||
$dataType == 'Float') {
239 $num = round($option->value
, 2);
240 $this->_options
[$dao->id
]["$num"] = $option->label
;
243 $this->_options
[$dao->id
][$option->value
] = $option->label
;
246 $options = $this->_options
[$dao->id
];
247 //unset attributes to avoid confussion
248 unset($options['attributes']);
249 CRM_Utils_Hook
::customFieldOptions($dao->id
, $options, FALSE);
255 * Generate the select clause and the associated tables.
257 public function select() {
258 if (empty($this->_fields
)) {
262 foreach ($this->_fields
as $id => $field) {
263 $name = $field['table_name'];
264 $fieldName = 'custom_' . $field['id'];
265 $this->_select
["{$name}_id"] = "{$name}.id as {$name}_id";
266 $this->_element
["{$name}_id"] = 1;
267 $this->_select
[$fieldName] = "{$field['table_name']}.{$field['column_name']} as $fieldName";
268 $this->_element
[$fieldName] = 1;
271 if ($field['extends'] == 'civicrm_group') {
274 elseif ($field['extends'] == 'civicrm_contact') {
275 $joinTable = 'contact_a';
277 elseif ($field['extends'] == 'civicrm_contribution') {
278 $joinTable = $field['extends'];
280 elseif (in_array($field['extends'], self
::$extendsMap)) {
281 $joinTable = $field['extends'];
287 $this->_tables
[$name] = "\nLEFT JOIN $name ON $name.entity_id = $joinTable.id";
289 if ($this->_ids
[$id]) {
290 $this->_whereTables
[$name] = $this->_tables
[$name];
295 $joinTableAlias = $joinTable;
296 // Set location-specific query
297 if (isset($this->_locationSpecificCustomFields
[$id])) {
298 list($locationType, $locationTypeId) = $this->_locationSpecificCustomFields
[$id];
299 $joinTableAlias = "$locationType-address";
300 $joinClause = "\nLEFT JOIN $joinTable `$locationType-address` ON (`$locationType-address`.contact_id = contact_a.id AND `$locationType-address`.location_type_id = $locationTypeId)";
302 $this->_tables
[$name] = "\nLEFT JOIN $name ON $name.entity_id = `$joinTableAlias`.id";
303 if ($this->_ids
[$id]) {
304 $this->_whereTables
[$name] = $this->_tables
[$name];
306 if ($joinTable != 'contact_a') {
307 $this->_whereTables
[$joinTableAlias] = $this->_tables
[$joinTableAlias] = $joinClause;
309 elseif ($this->_contactSearch
) {
310 CRM_Contact_BAO_Query
::$_openedPanes[ts('Custom Fields')] = TRUE;
317 * Generate the where clause and also the english language equivalent.
319 public function where() {
320 foreach ($this->_ids
as $id => $values) {
322 // Fixed for Issue CRM 607
323 if (CRM_Utils_Array
::value($id, $this->_fields
) === NULL ||
329 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
331 foreach ($values as $tuple) {
332 list($name, $op, $value, $grouping, $wildcard) = $tuple;
334 $field = $this->_fields
[$id];
336 $fieldName = "{$field['table_name']}.{$field['column_name']}";
338 $isSerialized = CRM_Core_BAO_CustomField
::isSerialized($field);
340 // fix $value here to escape sql injection attacks
342 if (!is_array($value)) {
343 $value = CRM_Core_DAO
::escapeString(trim($value));
344 $qillValue = CRM_Core_BAO_CustomField
::getDisplayValue($value, $id, $this->_options
);
346 elseif (count($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
348 $qillValue = strstr($op, 'NULL') ?
NULL : CRM_Core_BAO_CustomField
::getDisplayValue($value[$op], $id, $this->_options
);
351 $op = strstr($op, 'IN') ?
$op : 'IN';
352 $qillValue = CRM_Core_BAO_CustomField
::getDisplayValue($value, $id, $this->_options
);
355 $qillOp = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
357 switch ($field['data_type']) {
359 case 'StateProvince':
362 if ($field['is_search_range'] && is_array($value)) {
363 $this->searchRange($field['id'],
372 // fix $value here to escape sql injection attacks
373 if (!is_array($value)) {
374 if ($field['data_type'] == 'String') {
375 $value = CRM_Utils_Type
::escape($strtolower($value), 'String');
378 $value = CRM_Utils_Type
::escape($value, 'Integer');
381 elseif ($isSerialized) {
382 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
384 $value = $value[$op];
386 $value = implode(',', (array) $value);
389 // CRM-14563,CRM-16575 : Special handling of multi-select custom fields
390 if ($isSerialized && !empty($value) && !strstr($op, 'NULL') && !strstr($op, 'LIKE')) {
391 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
392 if (strstr($op, 'IN')) {
393 $value = str_replace(",", "$sp|$sp", $value);
394 $value = str_replace('(', '[[.left-parenthesis.]]', $value);
395 $value = str_replace(')', '[[.right-parenthesis.]]', $value);
397 $op = (strstr($op, '!') ||
strstr($op, 'NOT')) ?
'NOT RLIKE' : 'RLIKE';
398 $value = $sp . $value . $sp;
400 foreach (explode("|", $value) as $val) {
401 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldName, $op, $val, 'String');
405 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldName, $op, $value, 'String');
409 //FIX for custom data query fired against no value(NULL/NOT NULL)
410 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldName, $op, $value, 'String');
412 $this->_qill
[$grouping][] = "$field[label] $qillOp $qillValue";
416 case 'ContactReference':
417 $label = $value ? CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name') : '';
418 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldName, $op, $value, 'String');
419 $this->_qill
[$grouping][] = $field['label'] . " $qillOp $label";
423 if ($field['is_search_range'] && is_array($value)) {
424 $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
427 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldName, $op, $value, 'Integer');
428 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));;
433 if (!is_array($value)) {
434 if (strtolower($value) == 'yes' ||
strtolower($value) == strtolower(ts('Yes'))) {
438 $value = (int) $value;
440 $value = ($value == 1) ?
1 : 0;
441 $qillValue = $value ?
'Yes' : 'No';
443 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldName, $op, $value, 'Integer');
444 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
449 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldName, $op, $value, 'String');
450 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
454 $value = CRM_Utils_Array
::value($op, (array) $value, $value);
455 if (is_array($value)) {
456 foreach ($value as $key => $val) {
457 $value[$key] = CRM_Utils_Rule
::cleanMoney($value[$key]);
461 $value = CRM_Utils_Rule
::cleanMoney($value);
465 if ($field['is_search_range']) {
466 $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
469 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldName, $op, $value, 'Float');
470 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
475 if (in_array($op, CRM_Core_DAO
::acceptedSQLOperators())) {
476 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldName, $op, $value, 'String');
477 list($qillOp, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $field['label'], $value,
478 $op, array(), CRM_Utils_Type
::T_DATE
);
479 $this->_qill
[$grouping][] = "{$field['label']} $qillOp '$qillVal'";
483 $fromValue = CRM_Utils_Array
::value('from', $value);
484 $toValue = CRM_Utils_Array
::value('to', $value);
485 $value = CRM_Utils_Array
::value($op, $value, $value);
487 if (!$fromValue && !$toValue) {
488 if (!is_array($value) && !CRM_Utils_Date
::processDate($value) && !in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
492 // hack to handle yy format during search
493 if (is_numeric($value) && strlen($value) == 4) {
494 $value = "01-01-{$value}";
497 if (is_array($value)) {
498 $date = $qillValue = array();
499 foreach ($value as $key => $val) {
500 $date[$key] = CRM_Utils_Date
::processDate($val);
501 $qillValue[$key] = CRM_Utils_Date
::customFormat($date[$key]);
505 $date = CRM_Utils_Date
::processDate($value);
506 $qillValue = CRM_Utils_Date
::customFormat($date);
509 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldName, $op, $date, 'String');
510 $this->_qill
[$grouping][] = $field['label'] . " {$qillOp} " . implode(', ', (array) $qillValue);
513 if (is_numeric($fromValue) && strlen($fromValue) == 4) {
514 $fromValue = "01-01-{$fromValue}";
517 if (is_numeric($toValue) && strlen($toValue) == 4) {
518 $toValue = "01-01-{$toValue}";
521 // TO DO: add / remove time based on date parts
522 $fromDate = CRM_Utils_Date
::processDate($fromValue);
523 $toDate = CRM_Utils_Date
::processDate($toValue);
524 if (!$fromDate && !$toDate) {
528 $this->_where
[$grouping][] = "$fieldName >= $fromDate";
529 $this->_qill
[$grouping][] = $field['label'] . ' >= ' . CRM_Utils_Date
::customFormat($fromDate);
532 $this->_where
[$grouping][] = "$fieldName <= $toDate";
533 $this->_qill
[$grouping][] = $field['label'] . ' <= ' . CRM_Utils_Date
::customFormat($toDate);
539 if ($op == 'IS NULL' ||
$op == 'IS NOT NULL' ||
$op == 'IS EMPTY' ||
$op == 'IS NOT EMPTY') {
549 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldName, $op);
550 $this->_qill
[$grouping][] = $field['label'] . " {$qillOp} ";
559 * Function that does the actual query generation.
560 * basically ties all the above functions together
565 public function query() {
571 if (!empty($this->_where
)) {
573 foreach ($this->_where
as $grouping => $values) {
574 if (!empty($values)) {
575 $clauses[] = ' ( ' . implode(' AND ', $values) . ' ) ';
578 if (!empty($clauses)) {
579 $whereStr = ' ( ' . implode(' OR ', $clauses) . ' ) ';
584 implode(' , ', $this->_select
),
585 implode(' ', $this->_tables
),
594 * @param string $fieldName
598 public function searchRange(&$id, &$label, $type, $fieldName, &$value, &$grouping) {
601 if (isset($value['from'])) {
602 $val = CRM_Utils_Type
::escape($value['from'], $type);
604 if ($type == 'String') {
605 $this->_where
[$grouping][] = "$fieldName >= '$val'";
608 $this->_where
[$grouping][] = "$fieldName >= $val";
610 $qill[] = ts('greater than or equal to \'%1\'', array(1 => $value['from']));
613 if (isset($value['to'])) {
614 $val = CRM_Utils_Type
::escape($value['to'], $type);
615 if ($type == 'String') {
616 $this->_where
[$grouping][] = "$fieldName <= '$val'";
619 $this->_where
[$grouping][] = "$fieldName <= $val";
621 $qill[] = ts('less than or equal to \'%1\'', array(1 => $value['to']));
625 $this->_qill
[$grouping][] = $label . ' - ' . implode(' ' . ts('and') . ' ', $qill);