3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
37 * This is the heart of the search query building mechanism.
39 class CRM_Contact_BAO_Query
{
42 * The various search modes.
52 MODE_PLEDGEBANK
= 256,
61 * The default set of return properties.
65 static $_defaultReturnProperties = NULL;
68 * The default set of hier return properties.
72 static $_defaultHierReturnProperties;
75 * The set of input params.
87 * The set of output params
91 public $_returnProperties;
101 * The name of the elements that are in the select clause
102 * used to extract the values
109 * The tables involved in the query
116 * The table involved in the where clause
120 public $_whereTables;
134 public $_whereClause;
137 * Additional permission Where Clause
141 public $_permissionWhereClause;
151 * Additional permission from clause
155 public $_permissionFromClause;
158 * The from clause for the simple select and alphabetical
163 public $_simpleFromClause;
173 * The english language version of the query
180 * All the fields that could potentially be involved in
188 * The cache to translate the option values into labels.
195 * Are we in search mode.
199 public $_search = TRUE;
202 * Should we skip permission checking.
206 public $_skipPermission = FALSE;
209 * Should we skip adding of delete clause.
213 public $_skipDeleteClause = FALSE;
216 * Are we in strict mode (use equality over LIKE)
220 public $_strict = FALSE;
223 * What operator to use to group the clauses.
227 public $_operator = 'AND';
232 * Should we only search on primary location.
236 public $_primaryLocation = TRUE;
239 * Are contact ids part of the query.
243 public $_includeContactIds = FALSE;
246 * Should we use the smart group cache.
250 public $_smartGroupCache = TRUE;
253 * Should we display contacts with a specific relationship type.
257 public $_displayRelationshipType = NULL;
260 * Reference to the query object for custom values.
264 public $_customQuery;
267 * Should we enable the distinct clause, used if we are including
268 * more than one group
272 public $_useDistinct = FALSE;
275 * Should we just display one contact record
277 public $_useGroupBy = FALSE;
280 * The relationship type direction
291 static $_activityRole;
294 * Consider the component activity type
295 * during activity search.
299 static $_considerCompActivities;
302 * Consider with contact activities only,
303 * during activity search.
307 static $_withContactActivitiesOnly;
310 * Use distinct component clause for component searches
314 public $_distinctComponentClause;
316 public $_rowCountClause;
319 * Use groupBy component clause for component searches
323 public $_groupByComponentClause;
326 * Track open panes, useful in advance search
330 public static $_openedPanes = array();
333 * For search builder - which custom fields are location-dependent
336 public $_locationSpecificCustomFields = array();
339 * The tables which have a dependency on location and/or address
343 static $_dependencies = array(
344 'civicrm_state_province' => 1,
345 'civicrm_country' => 1,
346 'civicrm_county' => 1,
347 'civicrm_address' => 1,
348 'civicrm_location_type' => 1,
352 * List of location specific fields.
354 static $_locationSpecificFields = array(
359 'supplemental_address_1',
360 'supplemental_address_2',
363 'postal_code_suffix',
376 * Remember if we handle either end of a number or date range
377 * so we can skip the other
379 protected $_rangeCache = array();
381 * Set to true when $this->relationship is run to avoid adding twice
384 protected $_relationshipValuesAdded = FALSE;
387 * Set to the name of the temp table if one has been created
390 static $_relationshipTempTable = NULL;
392 public $_pseudoConstantsSelect = array();
395 * Class constructor which also does all the work.
397 * @param array $params
398 * @param array $returnProperties
399 * @param array $fields
400 * @param bool $includeContactIds
401 * @param bool $strict
402 * @param bool|int $mode - mode the search is operating on
404 * @param bool $skipPermission
405 * @param bool $searchDescendentGroups
406 * @param bool $smartGroupCache
407 * @param null $displayRelationshipType
408 * @param string $operator
410 * @return \CRM_Contact_BAO_Query
412 public function __construct(
413 $params = NULL, $returnProperties = NULL, $fields = NULL,
414 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
415 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
416 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
419 $this->_params
= &$params;
420 if ($this->_params
== NULL) {
421 $this->_params
= array();
424 if (empty($returnProperties)) {
425 $this->_returnProperties
= self
::defaultReturnProperties($mode);
428 $this->_returnProperties
= &$returnProperties;
431 $this->_includeContactIds
= $includeContactIds;
432 $this->_strict
= $strict;
433 $this->_mode
= $mode;
434 $this->_skipPermission
= $skipPermission;
435 $this->_smartGroupCache
= $smartGroupCache;
436 $this->_displayRelationshipType
= $displayRelationshipType;
437 $this->setOperator($operator);
440 $this->_fields
= &$fields;
441 $this->_search
= FALSE;
442 $this->_skipPermission
= TRUE;
445 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE);
447 $fields = CRM_Core_Component
::getQueryFields();
448 unset($fields['note']);
449 $this->_fields
= array_merge($this->_fields
, $fields);
451 // add activity fields
452 $fields = CRM_Activity_BAO_Activity
::exportableFields();
453 $this->_fields
= array_merge($this->_fields
, $fields);
455 // add any fields provided by hook implementers
456 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
457 $this->_fields
= array_merge($this->_fields
, $extFields);
460 // basically do all the work once, and then reuse it
465 * Function which actually does all the work for the constructor.
469 public function initialize() {
470 $this->_select
= array();
471 $this->_element
= array();
472 $this->_tables
= array();
473 $this->_whereTables
= array();
474 $this->_where
= array();
475 $this->_qill
= array();
476 $this->_options
= array();
477 $this->_cfIDs
= array();
478 $this->_paramLookup
= array();
479 $this->_having
= array();
481 $this->_customQuery
= NULL;
483 // reset cached static variables - CRM-5803
484 self
::$_activityRole = NULL;
485 self
::$_considerCompActivities = NULL;
486 self
::$_withContactActivitiesOnly = NULL;
488 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
489 $this->_element
['contact_id'] = 1;
490 $this->_tables
['civicrm_contact'] = 1;
492 if (!empty($this->_params
)) {
493 $this->buildParamsLookup();
496 $this->_whereTables
= $this->_tables
;
498 $this->selectClause();
499 $this->_whereClause
= $this->whereClause();
501 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
502 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
504 $this->openedSearchPanes(TRUE);
507 public function buildParamsLookup() {
508 // first fix and handle contact deletion nicely
509 // this code is primarily for search builder use case
510 // where different clauses can specify if they want deleted
513 $trashParamExists = FALSE;
514 $paramByGroup = array();
515 foreach ($this->_params
as $k => $param) {
516 if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
517 $trashParamExists = TRUE;
519 if (!empty($param[3])) {
520 $paramByGroup[$param[3]][$k] = $param;
524 if ($trashParamExists) {
525 $this->_skipDeleteClause
= TRUE;
527 //cycle through group sets and explicitly add trash param if not set
528 foreach ($paramByGroup as $setID => $set) {
530 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params
) &&
531 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params
)
533 $this->_params
[] = array(
534 'contact_is_deleted',
544 foreach ($this->_params
as $value) {
545 if (empty($value[0])) {
548 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
550 if (!array_key_exists($cfID, $this->_cfIDs
)) {
551 $this->_cfIDs
[$cfID] = array();
553 // Set wildcard value based on "and/or" selection
554 foreach ($this->_params
as $key => $param) {
555 if ($param[0] == $value[0] . '_operator') {
556 $value[4] = $param[2] == 'or';
560 $this->_cfIDs
[$cfID][] = $value;
563 if (!array_key_exists($value[0], $this->_paramLookup
)) {
564 $this->_paramLookup
[$value[0]] = array();
566 $this->_paramLookup
[$value[0]][] = $value;
571 * Some composite fields do not appear in the fields array
572 * hack to make them part of the query
576 public function addSpecialFields() {
577 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
578 foreach ($special as $name) {
579 if (!empty($this->_returnProperties
[$name])) {
580 $this->_select
[$name] = "contact_a.{$name} as $name";
581 $this->_element
[$name] = 1;
587 * Given a list of conditions in params and a list of desired
588 * return Properties generate the required select and from
589 * clauses. Note that since the where clause introduces new
590 * tables, the initial attempt also retrieves all variables used
595 public function selectClause() {
597 $this->addSpecialFields();
599 foreach ($this->_fields
as $name => $field) {
600 // skip component fields
601 // there are done by the alter query below
602 // and need not be done on every field
604 (substr($name, 0, 12) == 'participant_') ||
605 (substr($name, 0, 7) == 'pledge_') ||
606 (substr($name, 0, 5) == 'case_') ||
607 (substr($name, 0, 13) == 'contribution_' &&
608 (strpos($name, 'source') !== FALSE && strpos($name, 'recur') !== FALSE)) ||
609 (substr($name, 0, 8) == 'payment_')
614 // redirect to activity select clause
616 (substr($name, 0, 9) == 'activity_') ||
617 ($name == 'parent_id')
619 CRM_Activity_BAO_Query
::select($this);
623 // if this is a hierarchical name, we ignore it
624 $names = explode('-', $name);
625 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
629 // make an exception for special cases, to add the field in select clause
630 $makeException = FALSE;
632 //special handling for groups/tags
633 if (in_array($name, array('groups', 'tags', 'notes'))
634 && isset($this->_returnProperties
[substr($name, 0, -1)])
636 $makeException = TRUE;
639 // since note has 3 different options we need special handling
640 // note / note_subject / note_body
641 if ($name == 'notes') {
642 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
643 if (isset($this->_returnProperties
[$noteField])) {
644 $makeException = TRUE;
650 if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id', 'communication_style_id'))) {
651 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
652 $makeException = TRUE;
656 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
657 if (!empty($this->_paramLookup
[$name]) ||
!empty($this->_returnProperties
[$name]) ||
661 // add to cfIDs array if not present
662 if (!array_key_exists($cfID, $this->_cfIDs
)) {
663 $this->_cfIDs
[$cfID] = array();
666 elseif (isset($field['where'])) {
667 list($tableName, $fieldName) = explode('.', $field['where'], 2);
668 if (isset($tableName)) {
669 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
670 $this->_tables
['civicrm_address'] = 1;
671 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
672 $this->_element
['address_id'] = 1;
675 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
676 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
678 if ($tableName == 'im_provider') {
679 CRM_Core_OptionValue
::select($this);
682 if (in_array($tableName,
683 array('email_greeting', 'postal_greeting', 'addressee'))) {
684 $this->_element
["{$name}_id"] = 1;
685 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
686 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
687 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
688 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
690 if ($tableName == 'email_greeting') {
691 $this->_pseudoConstantsSelect
[$name]['join']
692 = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
693 $this->_pseudoConstantsSelect
[$name]['join'] .=
694 " LEFT JOIN civicrm_option_value email_greeting ON (contact_a.email_greeting_id = email_greeting.value AND option_group_email_greeting.id = email_greeting.option_group_id ) ";
696 elseif ($tableName == 'postal_greeting') {
697 $this->_pseudoConstantsSelect
[$name]['join']
698 = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
699 $this->_pseudoConstantsSelect
[$name]['join'] .=
700 " LEFT JOIN civicrm_option_value postal_greeting ON (contact_a.postal_greeting_id = postal_greeting.value AND option_group_postal_greeting.id = postal_greeting.option_group_id ) ";
702 elseif ($tableName == 'addressee') {
703 $this->_pseudoConstantsSelect
[$name]['join']
704 = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
705 $this->_pseudoConstantsSelect
[$name]['join'] .=
706 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
708 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
711 $greetField = "{$name}_display";
712 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
713 $this->_element
[$greetField] = 1;
715 $greetField = "{$name}_custom";
716 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
717 $this->_element
[$greetField] = 1;
721 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
722 $this->_tables
[$tableName] = 1;
725 // also get the id of the tableName
726 $tName = substr($tableName, 8);
727 if (in_array($tName, array('country', 'state_province', 'county'))) {
728 if ($tName == 'state_province') {
729 $this->_pseudoConstantsSelect
['state_province_name'] = array(
730 'pseudoField' => "{$tName}",
731 'idCol' => "{$tName}_id",
732 'bao' => 'CRM_Core_BAO_Address',
733 'table' => "civicrm_{$tName}",
734 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
737 $this->_pseudoConstantsSelect
[$tName] = array(
738 'pseudoField' => 'state_province_abbreviation',
739 'idCol' => "{$tName}_id",
740 'table' => "civicrm_{$tName}",
741 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
745 $this->_pseudoConstantsSelect
[$name] = array(
746 'pseudoField' => "{$tName}_id",
747 'idCol' => "{$tName}_id",
748 'bao' => 'CRM_Core_BAO_Address',
749 'table' => "civicrm_{$tName}",
750 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
754 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
755 $this->_element
["{$tName}_id"] = 1;
757 elseif ($tName != 'contact') {
758 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
759 $this->_element
["{$tName}_id"] = 1;
762 //special case for phone
763 if ($name == 'phone') {
764 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
765 $this->_element
['phone_type_id'] = 1;
768 // if IM then select provider_id also
769 // to get "IM Service Provider" in a file to be exported, CRM-3140
771 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
772 $this->_element
['provider_id'] = 1;
775 if ($tName == 'contact') {
776 // special case, when current employer is set for Individual contact
777 if ($fieldName == 'organization_name') {
778 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
780 elseif ($fieldName != 'id') {
781 if ($fieldName == 'prefix_id') {
782 $this->_pseudoConstantsSelect
['individual_prefix'] = array(
783 'pseudoField' => 'prefix_id',
784 'idCol' => "prefix_id",
785 'bao' => 'CRM_Contact_BAO_Contact',
788 if ($fieldName == 'suffix_id') {
789 $this->_pseudoConstantsSelect
['individual_suffix'] = array(
790 'pseudoField' => 'suffix_id',
791 'idCol' => "suffix_id",
792 'bao' => 'CRM_Contact_BAO_Contact',
795 if ($fieldName == 'gender_id') {
796 $this->_pseudoConstantsSelect
['gender'] = array(
797 'pseudoField' => 'gender_id',
798 'idCol' => "gender_id",
799 'bao' => 'CRM_Contact_BAO_Contact',
802 if ($name == 'communication_style_id') {
803 $this->_pseudoConstantsSelect
['communication_style'] = array(
804 'pseudoField' => 'communication_style_id',
805 'idCol' => "communication_style_id",
806 'bao' => 'CRM_Contact_BAO_Contact',
809 $this->_select
[$name] = "contact_a.{$fieldName} as `$name`";
812 elseif (in_array($tName, array('country', 'county'))) {
813 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
814 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
816 elseif ($tName == 'state_province') {
817 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
818 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
821 $this->_select
[$name] = "{$field['where']} as `$name`";
823 if (!in_array($tName, array('state_province', 'country', 'county'))) {
824 $this->_element
[$name] = 1;
829 elseif ($name === 'tags') {
830 $this->_useGroupBy
= TRUE;
831 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
832 $this->_element
[$name] = 1;
833 $this->_tables
['civicrm_tag'] = 1;
834 $this->_tables
['civicrm_entity_tag'] = 1;
836 elseif ($name === 'groups') {
837 $this->_useGroupBy
= TRUE;
838 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
839 $this->_element
[$name] = 1;
840 $this->_tables
['civicrm_group'] = 1;
842 elseif ($name === 'notes') {
843 // if note field is subject then return subject else body of the note
844 $noteColumn = 'note';
845 if (isset($noteField) && $noteField == 'note_subject') {
846 $noteColumn = 'subject';
849 $this->_useGroupBy
= TRUE;
850 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
851 $this->_element
[$name] = 1;
852 $this->_tables
['civicrm_note'] = 1;
854 elseif ($name === 'current_employer') {
855 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
856 $this->_element
[$name] = 1;
860 if ($cfID && !empty($field['is_search_range'])) {
861 // this is a custom field with range search enabled, so we better check for two/from values
862 if (!empty($this->_paramLookup
[$name . '_from'])) {
863 if (!array_key_exists($cfID, $this->_cfIDs
)) {
864 $this->_cfIDs
[$cfID] = array();
866 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
867 // search in the cdID array for the same grouping
869 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
870 if ($c[3] == $p[3]) {
871 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
876 $p[2] = array('from' => $p[2]);
877 $this->_cfIDs
[$cfID][] = $p;
881 if (!empty($this->_paramLookup
[$name . '_to'])) {
882 if (!array_key_exists($cfID, $this->_cfIDs
)) {
883 $this->_cfIDs
[$cfID] = array();
885 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
886 // search in the cdID array for the same grouping
888 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
889 if ($c[4] == $p[4]) {
890 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
895 $p[2] = array('to' => $p[2]);
896 $this->_cfIDs
[$cfID][] = $p;
903 // add location as hierarchical elements
904 $this->addHierarchicalElements();
906 // add multiple field like website
907 $this->addMultipleElements();
910 CRM_Core_Component
::alterQuery($this, 'select');
912 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
914 if (!empty($this->_cfIDs
)) {
915 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
916 $this->_customQuery
->query();
917 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
918 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
919 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
920 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
921 $this->_options
= $this->_customQuery
->_options
;
926 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
931 public function addHierarchicalElements() {
932 if (empty($this->_returnProperties
['location'])) {
935 if (!is_array($this->_returnProperties
['location'])) {
939 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
940 $processed = array();
943 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
944 $addressCustomFieldIds = array();
946 foreach ($this->_returnProperties
['location'] as $name => $elements) {
947 $lCond = self
::getPrimaryCondition($name);
950 $locationTypeId = array_search($name, $locationTypes);
951 if ($locationTypeId === FALSE) {
954 $lCond = "location_type_id = $locationTypeId";
955 $this->_useDistinct
= TRUE;
957 //commented for CRM-3256
958 $this->_useGroupBy
= TRUE;
961 $name = str_replace(' ', '_', $name);
963 $tName = "$name-location_type";
964 $ltName = "`$name-location_type`";
965 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
966 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
967 $this->_element
["{$tName}_id"] = 1;
968 $this->_element
["{$tName}"] = 1;
970 $locationTypeName = $tName;
971 $locationTypeJoin = array();
975 foreach ($elements as $elementFullName => $dontCare) {
977 $elementName = $elementCmpName = $elementFullName;
979 if (substr($elementCmpName, 0, 5) == 'phone') {
980 $elementCmpName = 'phone';
983 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
984 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
985 $addressCustomFieldIds[$cfID][$name] = 1;
988 //add address table only once
989 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
991 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
993 $tName = "$name-address";
994 $aName = "`$name-address`";
995 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
996 $this->_element
["{$tName}_id"] = 1;
997 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
998 $this->_tables
[$tName] = $addressJoin;
999 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1000 $processed[$aName] = 1;
1004 $cond = $elementType = '';
1005 if (strpos($elementName, '-') !== FALSE) {
1006 // this is either phone, email or IM
1007 list($elementName, $elementType) = explode('-', $elementName);
1009 if (($elementName != 'phone') && ($elementName != 'im')) {
1010 $cond = self
::getPrimaryCondition($elementType);
1012 // CRM-13011 : If location type is primary, do not restrict search to the phone
1013 // type id - we want the primary phone, regardless of what type it is.
1014 // Otherwise, restrict to the specified phone type for the given field.
1015 if ((!$cond) && ($elementName == 'phone')) {
1016 $cond = "phone_type_id = '$elementType'";
1018 elseif ((!$cond) && ($elementName == 'im')) {
1019 // IM service provider id, CRM-3140
1020 $cond = "provider_id = '$elementType'";
1022 $elementType = '-' . $elementType;
1025 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
1027 // hack for profile, add location id
1030 // fix for CRM-882( to handle phone types )
1031 !is_numeric($elementType)
1033 if (is_numeric($name)) {
1034 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1037 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1040 elseif (is_numeric($name)) {
1041 //this for phone type to work
1042 if (in_array($elementName, array('phone', 'phone_ext'))) {
1043 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1046 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1050 //this is for phone type to work for profile edit
1051 if (in_array($elementName, array('phone', 'phone_ext'))) {
1052 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1055 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1060 // Check if there is a value, if so also add to where Clause
1062 if ($this->_params
) {
1064 if (isset($locationTypeId)) {
1065 $nm .= "-$locationTypeId";
1067 if (!is_numeric($elementType)) {
1068 $nm .= "$elementType";
1071 foreach ($this->_params
as $id => $values) {
1072 if ((is_array($values) && $values[0] == $nm) ||
1073 (in_array($elementName, array('phone', 'im'))
1074 && (strpos($values[0], $nm) !== FALSE)
1084 if ($field && isset($field['where'])) {
1085 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1086 $pf = substr($tableName, 8);
1087 $tName = $name . '-' . $pf . $elementType;
1088 if (isset($tableName)) {
1089 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1090 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1093 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1096 $this->_element
["{$tName}_id"] = 1;
1097 if (substr($tName, -15) == '-state_province') {
1098 // FIXME: hack to fix CRM-1900
1099 $a = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1103 if (substr_count($a, 'state_province_name') > 0) {
1104 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1105 'pseudoField' => "{$pf}_id",
1106 'idCol' => "{$tName}_id",
1107 'bao' => 'CRM_Core_BAO_Address',
1109 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1112 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1113 'pseudoField' => 'state_province_abbreviation',
1114 'idCol' => "{$tName}_id",
1116 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1120 if (substr($elementFullName, 0, 2) == 'im') {
1121 $provider = "{$name}-{$elementFullName}-provider_id";
1122 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1123 $this->_element
[$provider] = 1;
1125 if ($pf == 'country' ||
$pf == 'county') {
1126 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1127 'pseudoField' => "{$pf}_id",
1128 'idCol' => "{$tName}_id",
1129 'bao' => 'CRM_Core_BAO_Address',
1131 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1134 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1138 if (in_array($pf, array('state_province', 'country', 'county'))) {
1139 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1142 $this->_element
["{$name}-{$elementFullName}"] = 1;
1145 if (empty($processed["`$tName`"])) {
1146 $processed["`$tName`"] = 1;
1147 $newName = $tableName . '_' . $index;
1148 switch ($tableName) {
1149 case 'civicrm_phone':
1150 case 'civicrm_email':
1152 case 'civicrm_openid':
1154 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1155 if ($tableName != 'civicrm_phone') {
1156 $this->_tables
[$tName] .= " AND `$tName`.$lCond";
1158 elseif (is_numeric($name)) {
1159 $this->_select
[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1162 // this special case to add phone type
1164 $phoneTypeCondition = " AND `$tName`.$cond ";
1165 //gross hack to pickup corrupted data also, CRM-7603
1166 if (strpos($cond, 'phone_type_id') !== FALSE) {
1167 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1168 if (!empty($lCond)) {
1169 $phoneTypeCondition .= " AND ( `$tName`.$lCond ) ";
1172 $this->_tables
[$tName] .= $phoneTypeCondition;
1175 //build locationType join
1176 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1179 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1183 case 'civicrm_state_province':
1184 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1185 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1186 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1188 $this->_whereTables
["{$name}-address"] = $addressJoin;
1192 case 'civicrm_country':
1193 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1194 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1195 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1197 $this->_whereTables
["{$name}-address"] = $addressJoin;
1201 case 'civicrm_county':
1202 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1203 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1204 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1206 $this->_whereTables
["{$name}-address"] = $addressJoin;
1212 $this->_whereTables
["{$name}-address"] = $addressJoin;
1221 // add location type join
1222 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1223 $this->_tables
[$locationTypeName] = $ltypeJoin;
1225 // table should be present in $this->_whereTables,
1226 // to add its condition in location type join, CRM-3939.
1227 if ($addWhereCount) {
1228 $locClause = array();
1229 foreach ($this->_whereTables
as $tableName => $clause) {
1230 if (!empty($locationTypeJoin[$tableName])) {
1231 $locClause[] = $locationTypeJoin[$tableName];
1235 if (!empty($locClause)) {
1236 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1241 if (!empty($addressCustomFieldIds)) {
1242 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1243 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1244 foreach ($locTypeName as $name => $dnc) {
1245 $this->_locationSpecificCustomFields
[$cfID] = array($name, array_search($name, $locationTypes));
1246 $fieldName = "$name-custom_{$cfID}";
1247 $tName = "$name-address-custom-{$cfID}";
1248 $aName = "`$name-address-custom-{$cfID}`";
1249 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1250 $this->_element
["{$tName}_id"] = 1;
1251 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1252 $this->_element
[$fieldName] = 1;
1253 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1260 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
1265 public function addMultipleElements() {
1266 if (empty($this->_returnProperties
['website'])) {
1269 if (!is_array($this->_returnProperties
['website'])) {
1273 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1274 foreach ($elements as $elementFullName => $dontCare) {
1275 $tName = "website-{$key}-{$elementFullName}";
1276 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1277 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1278 $this->_element
["{$tName}_id"] = 1;
1279 $this->_element
["{$tName}"] = 1;
1281 $type = "website-{$key}-website_type_id";
1282 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1283 $this->_element
[$type] = 1;
1284 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1290 * Generate the query based on what type of query we need.
1292 * @param bool $count
1293 * @param bool $sortByChar
1294 * @param bool $groupContacts
1295 * @param bool $onlyDeleted
1298 * sql query parts as an array
1300 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1301 // build permission clause
1302 $this->generatePermissionClause($onlyDeleted, $count);
1305 if (isset($this->_rowCountClause
)) {
1306 $select = "SELECT {$this->_rowCountClause}";
1308 elseif (isset($this->_distinctComponentClause
)) {
1309 // we add distinct to get the right count for components
1310 // for the more complex result set, we use GROUP BY the same id
1312 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1315 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1317 $from = $this->_simpleFromClause
;
1318 if ($this->_useDistinct
) {
1319 $this->_useGroupBy
= TRUE;
1322 elseif ($sortByChar) {
1323 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1324 $from = $this->_simpleFromClause
;
1326 elseif ($groupContacts) {
1327 $select = 'SELECT contact_a.id as id';
1328 if ($this->_useDistinct
) {
1329 $this->_useGroupBy
= TRUE;
1331 $from = $this->_simpleFromClause
;
1334 if (!empty($this->_paramLookup
['group'])) {
1335 // make sure there is only one element
1336 // this is used when we are running under smog and need to know
1337 // how the contact was added (CRM-1203)
1338 if ((count($this->_paramLookup
['group']) == 1) &&
1339 (count($this->_paramLookup
['group'][0][2]) == 1)
1341 $groups = array_keys($this->_paramLookup
['group'][0][2]);
1342 $groupId = $groups[0];
1344 //check if group is saved search
1345 $group = new CRM_Contact_BAO_Group();
1346 $group->id
= $groupId;
1349 if (!isset($group->saved_search_id
)) {
1350 $tbName = "`civicrm_group_contact-{$groupId}`";
1351 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1352 $this->_element
['group_contact_id'] = 1;
1353 $this->_select
['status'] = "$tbName.status as status";
1354 $this->_element
['status'] = 1;
1357 $this->_useGroupBy
= TRUE;
1359 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1360 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1362 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1363 $this->_useDistinct
= FALSE;
1364 $this->_useGroupBy
= TRUE;
1368 $select = "SELECT ";
1369 if (isset($this->_distinctComponentClause
)) {
1370 $select .= "{$this->_distinctComponentClause}, ";
1372 $select .= implode(', ', $this->_select
);
1373 $from = $this->_fromClause
;
1377 if (!empty($this->_whereClause
)) {
1378 $where = "WHERE {$this->_whereClause}";
1381 if (!empty($this->_permissionWhereClause
) && empty($this->_displayRelationshipType
)) {
1382 if (empty($where)) {
1383 $where = "WHERE $this->_permissionWhereClause";
1386 $where = "$where AND $this->_permissionWhereClause";
1391 if (!empty($this->_having
)) {
1392 foreach ($this->_having
as $havingSets) {
1393 foreach ($havingSets as $havingSet) {
1394 $havingValue[] = $havingSet;
1397 $having = ' HAVING ' . implode(' AND ', $havingValue);
1400 // if we are doing a transform, do it here
1401 // use the $from, $where and $having to get the contact ID
1402 if ($this->_displayRelationshipType
) {
1403 $this->filterRelatedContacts($from, $where, $having);
1406 return array($select, $from, $where, $having);
1410 * @param string $name
1415 public function &getWhereValues($name, $grouping) {
1417 foreach ($this->_params
as $values) {
1418 if ($values[0] == $name && $values[3] == $grouping) {
1431 public static function fixDateValues($relative, &$from, &$to) {
1433 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1438 * @param $formValues
1439 * @param int $wildcard
1440 * @param bool $useEquals
1442 * @param string $apiEntity
1446 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1448 if (empty($formValues)) {
1452 foreach ($formValues as $id => $values) {
1453 if ($id == 'privacy') {
1454 if (is_array($formValues['privacy'])) {
1455 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1456 foreach ($formValues['privacy'] as $key => $value) {
1458 $params[] = array($key, $op, $value, 0, 0);
1463 elseif ($id == 'email_on_hold') {
1464 if ($formValues['email_on_hold']['on_hold']) {
1465 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1468 elseif (preg_match('/_date_relative$/', $id) ||
1469 $id == 'event_relative' ||
1470 $id == 'case_from_relative' ||
1471 $id == 'case_to_relative'
1473 if ($id == 'event_relative') {
1474 $fromRange = 'event_start_date_low';
1475 $toRange = 'event_end_date_high';
1477 elseif ($id == 'case_from_relative') {
1478 $fromRange = 'case_from_start_date_low';
1479 $toRange = 'case_from_start_date_high';
1481 elseif ($id == 'case_to_relative') {
1482 $fromRange = 'case_to_end_date_low';
1483 $toRange = 'case_to_end_date_high';
1486 $dateComponent = explode('_date_relative', $id);
1487 $fromRange = "{$dateComponent[0]}_date_low";
1488 $toRange = "{$dateComponent[0]}_date_high";
1491 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1492 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1497 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
1502 $params[] = $values;
1511 * @param int $wildcard
1512 * @param bool $useEquals
1514 * @param string $apiEntity
1516 * @return array|null
1518 public static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1519 // skip a few search variables
1520 static $skipWhere = NULL;
1521 static $likeNames = NULL;
1523 // Change camelCase EntityName to lowercase with underscores
1524 $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity);
1526 if (CRM_Utils_System
::isNull($values)) {
1538 'display_relationship_type',
1542 if (in_array($id, $skipWhere) ||
1543 substr($id, 0, 4) == '_qf_' ||
1544 substr($id, 0, 7) == 'hidden_'
1550 (substr($id, 0, strlen($apiEntity)) != $apiEntity) &&
1551 (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_')
1553 $id = $apiEntity . '_' . $id;
1557 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1560 // email comes in via advanced search
1561 // so use wildcard always
1562 if ($id == 'email') {
1566 if (!$useEquals && in_array($id, $likeNames)) {
1567 $result = array($id, 'LIKE', $values, 0, 1);
1569 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1570 $result = array($id, 'LIKE', $values, 0, 0);
1572 elseif ($id == 'group') {
1573 if (is_array($values)) {
1574 foreach ($values as $groupIds => $val) {
1576 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1577 if (strlen($matches[1]) > 0) {
1578 $values[$matches[1]] = 1;
1579 unset($values[$groupIds]);
1585 $groupIds = explode(',', $values);
1587 foreach ($groupIds as $groupId) {
1588 $values[$groupId] = 1;
1592 $result = array($id, 'IN', $values, 0, 0);
1594 elseif ($id == 'contact_tags' ||
$id == 'tag') {
1595 if (!is_array($values)) {
1596 $tagIds = explode(',', $values);
1598 foreach ($tagIds as $tagId) {
1599 $values[$tagId] = 1;
1602 $result = array($id, 'IN', $values, 0, 0);
1604 elseif ($id == 'contact_type') {
1605 $result = array($id, 'IN', $values, 0, $wildcard);
1608 $result = array($id, '=', $values, 0, $wildcard);
1617 public function whereClauseSingle(&$values) {
1618 // do not process custom fields or prefixed contact ids or component params
1619 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1620 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1621 (substr($values[0], 0, 13) == 'contribution_') ||
1622 (substr($values[0], 0, 6) == 'event_') ||
1623 (substr($values[0], 0, 12) == 'participant_') ||
1624 (substr($values[0], 0, 7) == 'member_') ||
1625 (substr($values[0], 0, 6) == 'grant_') ||
1626 (substr($values[0], 0, 7) == 'pledge_') ||
1627 (substr($values[0], 0, 5) == 'case_') ||
1628 (substr($values[0], 0, 10) == 'financial_') ||
1629 (substr($values[0], 0, 8) == 'payment_') ||
1630 (substr($values[0], 0, 11) == 'membership_')
1635 // skip for hook injected fields / params
1636 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1637 if (array_key_exists($values[0], $extFields)) {
1641 switch ($values[0]) {
1642 case 'deleted_contacts':
1643 $this->deletedContacts($values);
1646 case 'contact_type':
1647 $this->contactType($values);
1650 case 'contact_sub_type':
1651 $this->contactSubType($values);
1655 $this->group($values);
1659 // so we resolve this into a list of groups & proceed as if they had been
1661 list($name, $op, $value, $grouping, $wildcard) = $values;
1662 $values[0] = 'group';
1664 $this->_paramLookup
['group'][0][0] = 'group';
1665 $this->_paramLookup
['group'][0][1] = 'IN';
1666 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1667 $this->group($values);
1670 // case tag comes from find contacts
1672 $this->tagSearch($values);
1676 case 'contact_tags':
1677 $this->tag($values);
1682 case 'note_subject':
1683 $this->notes($values);
1687 $this->ufUser($values);
1691 case 'display_name':
1692 $this->sortName($values);
1696 case 'postal_greeting':
1697 case 'email_greeting':
1698 $this->greetings($values);
1702 $this->email($values);
1705 case 'phone_numeric':
1706 $this->phone_numeric($values);
1709 case 'phone_phone_type_id':
1710 case 'phone_location_type_id':
1711 $this->phone_option_group($values);
1714 case 'street_address':
1715 $this->street_address($values);
1718 case 'street_number':
1719 $this->street_number($values);
1722 case 'sortByCharacter':
1723 $this->sortByCharacter($values);
1726 case 'location_type':
1727 $this->locationType($values);
1731 $this->county($values);
1734 case 'state_province':
1735 $this->stateProvince($values);
1739 $this->country($values, FALSE);
1743 case 'postal_code_low':
1744 case 'postal_code_high':
1745 $this->postalCode($values);
1748 case 'activity_date':
1749 case 'activity_date_low':
1750 case 'activity_date_high':
1751 case 'activity_role':
1752 case 'activity_status_id':
1753 case 'activity_status':
1754 case 'followup_parent_id':
1756 case 'source_contact_id':
1757 case 'activity_subject':
1758 case 'test_activities':
1759 case 'activity_type_id':
1760 case 'activity_type':
1761 case 'activity_survey_id':
1762 case 'activity_tags':
1763 case 'activity_taglist':
1764 case 'activity_test':
1765 case 'activity_campaign_id':
1766 case 'activity_engagement_level':
1768 case 'activity_result':
1769 case 'source_contact':
1770 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1775 case 'birth_date_low':
1776 case 'birth_date_high':
1777 case 'deceased_date_low':
1778 case 'deceased_date_high':
1779 $this->demographics($values);
1782 case 'age_asof_date':
1783 // handled by demographics
1786 case 'log_date_low':
1787 case 'log_date_high':
1788 $this->modifiedDates($values);
1792 $this->changeLog($values);
1795 case 'do_not_phone':
1796 case 'do_not_email':
1799 case 'do_not_trade':
1801 $this->privacy($values);
1804 case 'privacy_options':
1805 $this->privacyOptions($values);
1808 case 'privacy_operator':
1809 case 'privacy_toggle':
1810 // these are handled by privacy options
1813 case 'preferred_communication_method':
1814 $this->preferredCommunication($values);
1817 case 'relation_type_id':
1818 case 'relation_start_date_high':
1819 case 'relation_start_date_low':
1820 case 'relation_end_date_high':
1821 case 'relation_end_date_low':
1822 case 'relation_target_name':
1823 case 'relation_status':
1824 case 'relation_date_low':
1825 case 'relation_date_high':
1826 $this->relationship($values);
1827 $this->_relationshipValuesAdded
= TRUE;
1830 case 'task_status_id':
1831 $this->task($values);
1835 // since this case is handled with the above
1838 case 'prox_distance':
1839 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1842 case 'prox_street_address':
1844 case 'prox_postal_code':
1845 case 'prox_state_province_id':
1846 case 'prox_country_id':
1847 // handled by the proximity_distance clause
1851 $this->restWhere($values);
1857 * Given a list of conditions in params generate the required.
1862 public function whereClause() {
1863 $this->_where
[0] = array();
1864 $this->_qill
[0] = array();
1866 $this->includeContactIds();
1867 if (!empty($this->_params
)) {
1868 foreach (array_keys($this->_params
) as $id) {
1869 if (empty($this->_params
[$id][0])) {
1872 // check for both id and contact_id
1873 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
1875 $this->_params
[$id][1] == 'IS NULL' ||
1876 $this->_params
[$id][1] == 'IS NOT NULL'
1878 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]}";
1880 elseif (is_array($this->_params
[$id][2])) {
1881 $idList = implode("','", $this->_params
[$id][2]);
1882 //why on earth do they put ' in the middle & not on the outside? We have to assume it's
1883 //to support 'something' so lets add them conditionally to support the api (which is a tested flow
1884 // so if you are looking to alter this check api test results
1885 if (strpos(trim($idList), "'") > 0) {
1886 $idList = "'" . $idList . "'";
1889 $this->_where
[0][] = "contact_a.id IN ({$idList})";
1892 $this->_where
[0][] = self
::buildClause("contact_a.id", "{$this->_params[$id][1]}", "{$this->_params[$id][2]}");
1896 $this->whereClauseSingle($this->_params
[$id]);
1900 CRM_Core_Component
::alterQuery($this, 'where');
1902 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
1905 if ($this->_customQuery
) {
1906 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1907 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1908 if (!empty($this->_customQuery
->_where
)) {
1909 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
1912 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
1916 $andClauses = array();
1919 if (!empty($this->_where
)) {
1920 foreach ($this->_where
as $grouping => $values) {
1921 if ($grouping > 0 && !empty($values)) {
1922 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1927 if (!empty($this->_where
[0])) {
1928 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
1930 if (!empty($clauses)) {
1931 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1934 if ($validClauses > 1) {
1935 $this->_useDistinct
= TRUE;
1939 return implode(' AND ', $andClauses);
1947 public function restWhere(&$values) {
1948 $name = CRM_Utils_Array
::value(0, $values);
1949 $op = CRM_Utils_Array
::value(1, $values);
1950 $value = CRM_Utils_Array
::value(2, $values);
1951 $grouping = CRM_Utils_Array
::value(3, $values);
1952 $wildcard = CRM_Utils_Array
::value(4, $values);
1954 if (isset($grouping) && empty($this->_where
[$grouping])) {
1955 $this->_where
[$grouping] = array();
1958 $multipleFields = array('url');
1960 //check if the location type exits for fields
1962 $locType = explode('-', $name);
1964 if (!in_array($locType[0], $multipleFields)) {
1965 //add phone type if exists
1966 if (isset($locType[2]) && $locType[2]) {
1967 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
1971 $field = CRM_Utils_Array
::value($name, $this->_fields
);
1974 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
1983 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
1984 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1986 if (substr($name, 0, 14) === 'state_province') {
1987 if (isset($locType[1]) && is_numeric($locType[1])) {
1989 $aName = "{$locationType[$locType[1]]}-address";
1990 $where = "`$aName`.state_province_id";
1993 $where = "civicrm_address.state_province_id";
1996 $states = CRM_Core_PseudoConstant
::stateProvince();
1997 if (is_numeric($value)) {
1998 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1999 $value = $states[(int ) $value];
2002 $intVal = CRM_Utils_Array
::key($value, $states);
2003 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
2006 $this->_qill
[$grouping][] = ts('State') . " $op '$value'";
2009 $this->_qill
[$grouping][] = ts('State') . " ($lType) $op '$value'";
2012 elseif (!empty($field['pseudoconstant'])) {
2013 $this->optionValueQuery(
2014 $name, $op, $value, $grouping,
2015 CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', $field['name']),
2021 if ($name == 'gender_id') {
2022 self
::$_openedPanes[ts('Demographics')] = TRUE;
2025 elseif (substr($name, 0, 7) === 'country') {
2026 if (isset($locType[1]) && is_numeric($locType[1])) {
2028 $aName = "{$locationType[$locType[1]]}-address";
2029 $where = "`$aName`.country_id";
2032 $where = "civicrm_address.country_id";
2035 $countries = CRM_Core_PseudoConstant
::country();
2036 if (is_numeric($value)) {
2037 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2038 $value = $countries[(int ) $value];
2041 $intVal = CRM_Utils_Array
::key($value, $countries);
2042 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
2046 $this->_qill
[$grouping][] = ts('Country') . " $op '$value'";
2049 $this->_qill
[$grouping][] = ts('Country') . " ($lType) $op '$value'";
2052 elseif (substr($name, 0, 6) === 'county') {
2053 if (isset($locType[1]) && is_numeric($locType[1])) {
2055 $aName = "{$locationType[$locType[1]]}-address";
2056 $where = "`$aName`.county_id";
2059 $where = "civicrm_address.county_id";
2062 $counties = CRM_Core_PseudoConstant
::county();
2063 if (is_numeric($value)) {
2064 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2065 $value = $counties[(int ) $value];
2068 $intVal = CRM_Utils_Array
::key($value, $counties);
2069 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
2073 $this->_qill
[$grouping][] = ts('County') . " $op '$value'";
2076 $this->_qill
[$grouping][] = ts('County') . " ($lType) $op '$value'";
2079 elseif ($name === 'world_region') {
2080 $field['where'] = 'civicrm_worldregion.id';
2081 $this->optionValueQuery(
2082 $name, $op, $value, $grouping,
2083 CRM_Core_PseudoConstant
::worldRegion(),
2090 elseif ($name === 'is_deceased') {
2091 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
2092 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2093 self
::$_openedPanes[ts('Demographics')] = TRUE;
2095 elseif ($name === 'created_date' ||
$name === 'modified_date' ||
$name === 'deceased_date' ||
$name === 'birth_date') {
2096 $appendDateTime = TRUE;
2097 if ($name === 'deceased_date' ||
$name === 'birth_date') {
2098 $appendDateTime = FALSE;
2099 self
::$_openedPanes[ts('Demographics')] = TRUE;
2101 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2103 elseif ($name === 'contact_id') {
2104 if (is_int($value)) {
2105 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2106 $this->_qill
[$grouping][] = "$field[title] $op $value";
2109 elseif ($name === 'name') {
2110 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2112 $value = "%$value%";
2115 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2116 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2117 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2119 elseif ($name === 'current_employer') {
2120 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2122 $value = "%$value%";
2125 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
2126 $ceWhereClause = self
::buildClause($wc, $op,
2129 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2130 $this->_where
[$grouping][] = $ceWhereClause;
2131 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2133 elseif ($name === 'email_greeting') {
2134 $filterCondition = array('greeting_type' => 'email_greeting');
2135 $this->optionValueQuery(
2136 $name, $op, $value, $grouping,
2137 CRM_Core_PseudoConstant
::greeting($filterCondition),
2139 ts('Email Greeting')
2142 elseif ($name === 'postal_greeting') {
2143 $filterCondition = array('greeting_type' => 'postal_greeting');
2144 $this->optionValueQuery(
2145 $name, $op, $value, $grouping,
2146 CRM_Core_PseudoConstant
::greeting($filterCondition),
2148 ts('Postal Greeting')
2151 elseif ($name === 'addressee') {
2152 $filterCondition = array('greeting_type' => 'addressee');
2153 $this->optionValueQuery(
2154 $name, $op, $value, $grouping,
2155 CRM_Core_PseudoConstant
::greeting($filterCondition),
2160 elseif (substr($name, 0, 4) === 'url-') {
2161 $tName = 'civicrm_website';
2162 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2163 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2165 $value = "%$value%";
2169 $wc = 'civicrm_website.url';
2170 $this->_where
[$grouping][] = $d = self
::buildClause($wc, $op, $value);
2171 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2173 elseif ($name === 'contact_is_deleted') {
2174 $this->_where
[$grouping][] = self
::buildClause("contact_a.is_deleted", $op, $value);
2175 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2177 elseif (!empty($field['where'])) {
2179 if (!empty($field['type'])) {
2180 $type = CRM_Utils_Type
::typeToString($field['type']);
2183 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2185 if (isset($locType[1]) &&
2186 is_numeric($locType[1])
2190 //get the location name
2191 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2193 $fieldName = "LOWER(`$tName`.$fldName)";
2195 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2196 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2200 if ($tableName == 'civicrm_contact') {
2201 $fieldName = "LOWER(contact_a.{$fieldName})";
2204 if ($op != 'IN' && !is_numeric($value)) {
2205 $fieldName = "LOWER({$field['where']})";
2208 $fieldName = "{$field['where']}";
2213 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2214 $this->_qill
[$grouping][] = "$field[title] $qillop '$qillVal'";
2216 if (is_array($value)) {
2217 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2218 // for api style operators for functions that hit this point without worrying about regression
2219 // (the previous comments indicated the condition for hitting this point were unknown
2220 // per CRM-14743 we are adding modified_date & created_date operator support
2221 $operations = array_keys($value);
2222 foreach ($operations as $operator) {
2223 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2224 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2225 //so this condition will satisfy the search for now
2226 if (strpos($op, 'IN') !== FALSE) {
2227 $value = array($op => $value);
2229 // we don't know when this might happen
2231 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $operator)));
2235 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($fieldName, $value, $type);
2239 $value = $strtolower($value);
2242 $value = "%$value%";
2246 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2250 if ($setTables && isset($field['where'])) {
2251 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2252 if (isset($tableName)) {
2253 $this->_tables
[$tableName] = 1;
2254 $this->_whereTables
[$tableName] = 1;
2267 public static function getLocationTableName(&$where, &$locType) {
2268 if (isset($locType[1]) && is_numeric($locType[1])) {
2269 list($tbName, $fldName) = explode(".", $where);
2271 //get the location name
2272 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2273 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2274 if (in_array($locType[0], $specialFields)) {
2275 //hack to fix / special handing for phone_ext
2276 if ($locType[0] == 'phone_ext') {
2277 $locType[0] = 'phone';
2279 if (isset($locType[2]) && $locType[2]) {
2280 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2283 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2286 elseif (in_array($locType[0],
2290 'supplemental_address_1',
2291 'supplemental_address_2',
2294 'postal_code_suffix',
2299 //fix for search by profile with address fields.
2300 $tName = "{$locationType[$locType[1]]}-address";
2302 elseif ($locType[0] == 'on_hold') {
2303 $tName = "{$locationType[$locType[1]]}-email";
2306 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2308 $tName = str_replace(' ', '_', $tName);
2309 return array($tName, $fldName);
2311 CRM_Core_Error
::fatal();
2315 * Given a result dao, extract the values and return that array
2317 * @param CRM_Core_DAO $dao
2320 * values for this query
2322 public function store($dao) {
2325 foreach ($this->_element
as $key => $dontCare) {
2326 if (property_exists($dao, $key)) {
2327 if (strpos($key, '-') !== FALSE) {
2328 $values = explode('-', $key);
2329 $lastElement = array_pop($values);
2331 $cnt = count($values);
2333 foreach ($values as $v) {
2334 if (!array_key_exists($v, $current)) {
2335 $current[$v] = array();
2337 //bad hack for im_provider
2338 if ($lastElement == 'provider_id') {
2339 if ($count < $cnt) {
2340 $current = &$current[$v];
2343 $lastElement = "{$v}_{$lastElement}";
2347 $current = &$current[$v];
2352 $current[$lastElement] = $dao->$key;
2355 $value[$key] = $dao->$key;
2363 * Getter for tables array.
2367 public function tables() {
2368 return $this->_tables
;
2372 * Where tables is sometimes used to create the from clause, but, not reliably, set this AND set tables
2373 * It's unclear the intent - there is a 'simpleFrom' clause which takes whereTables into account & a fromClause which doesn't
2374 * logic may have eroded
2377 public function whereTables() {
2378 return $this->_whereTables
;
2382 * Generate the where clause (used in match contacts and permissions)
2384 * @param array $params
2385 * @param array $fields
2386 * @param array $tables
2387 * @param $whereTables
2388 * @param bool $strict
2392 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2393 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2397 $tables = array_merge($query->tables(), $tables);
2398 $whereTables = array_merge($query->whereTables(), $whereTables);
2400 return $query->_whereClause
;
2404 * Create the from clause.
2406 * @param array $tables
2407 * Tables that need to be included in this from clause.
2408 * if null, return mimimal from clause (i.e. civicrm_contact)
2409 * @param array $inner
2410 * Tables that should be inner-joined.
2411 * @param array $right
2412 * Tables that should be right-joined.
2414 * @param bool $primaryLocation
2420 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2422 $from = ' FROM civicrm_contact contact_a';
2423 if (empty($tables)) {
2427 if (!empty($tables['civicrm_worldregion'])) {
2428 $tables = array_merge(array('civicrm_country' => 1), $tables);
2431 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2432 CRM_Utils_Array
::value('civicrm_county', $tables)
2433 ) && empty($tables['civicrm_address'])
2435 $tables = array_merge(array('civicrm_address' => 1),
2440 // add group_contact and group_contact_cache table if group table is present
2441 if (!empty($tables['civicrm_group'])) {
2442 if (empty($tables['civicrm_group_contact'])) {
2443 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added' ";
2445 if (empty($tables['civicrm_group_contact_cache'])) {
2446 $tables['civicrm_group_contact_cache'] = " LEFT JOIN civicrm_group_contact_cache ON civicrm_group_contact_cache.contact_id = contact_a.id ";
2450 // add group_contact and group table is subscription history is present
2451 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2452 $tables = array_merge(array(
2453 'civicrm_group' => 1,
2454 'civicrm_group_contact' => 1,
2460 // to handle table dependencies of components
2461 CRM_Core_Component
::tableNames($tables);
2462 // to handle table dependencies of hook injected tables
2463 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2465 //format the table list according to the weight
2466 $info = CRM_Core_TableHierarchy
::info();
2468 foreach ($tables as $key => $value) {
2470 if (strpos($key, '-') !== FALSE) {
2471 $keyArray = explode('-', $key);
2472 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2474 elseif (strpos($key, '_') !== FALSE) {
2475 $keyArray = explode('_', $key);
2476 if (is_numeric(array_pop($keyArray))) {
2477 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2480 $k = CRM_Utils_Array
::value($key, $info, 99);
2484 $k = CRM_Utils_Array
::value($key, $info, 99);
2486 $tempTable[$k . ".$key"] = $key;
2489 $newTables = array();
2490 foreach ($tempTable as $key) {
2491 $newTables[$key] = $tables[$key];
2494 $tables = $newTables;
2496 foreach ($tables as $name => $value) {
2501 if (!empty($inner[$name])) {
2504 elseif (!empty($right[$name])) {
2512 // if there is already a join statement in value, use value itself
2513 if (strpos($value, 'JOIN')) {
2514 $from .= " $value ";
2517 $from .= " $side JOIN $name ON ( $value ) ";
2522 case 'civicrm_address':
2523 if ($primaryLocation) {
2524 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2527 //CRM-14263 further handling of address joins further down...
2528 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2532 case 'civicrm_phone':
2533 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2536 case 'civicrm_email':
2537 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2541 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2545 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2546 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2547 $from .= " $side JOIN civicrm_option_value im_provider ON (civicrm_im.provider_id = im_provider.value AND option_group_imProvider.id = im_provider.option_group_id)";
2550 case 'civicrm_openid':
2551 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2554 case 'civicrm_worldregion':
2555 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2556 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2559 case 'civicrm_location_type':
2560 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2563 case 'civicrm_group':
2564 $from .= " $side JOIN civicrm_group ON (civicrm_group.id = civicrm_group_contact.group_id OR civicrm_group.id = civicrm_group_contact_cache.group_id) ";
2567 case 'civicrm_group_contact':
2568 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2571 case 'civicrm_group_contact_cache':
2572 $from .= " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
2575 case 'civicrm_activity':
2576 case 'civicrm_activity_tag':
2577 case 'activity_type':
2578 case 'activity_status':
2580 case 'civicrm_activity_contact':
2581 case 'source_contact':
2582 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2585 case 'civicrm_entity_tag':
2586 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2587 civicrm_entity_tag.entity_id = contact_a.id ) ";
2590 case 'civicrm_note':
2591 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2592 contact_a.id = civicrm_note.entity_id ) ";
2595 case 'civicrm_subscription_history':
2596 $from .= " $side JOIN civicrm_subscription_history
2597 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2598 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2601 case 'civicrm_relationship':
2602 if (self
::$_relType == 'reciprocal') {
2603 if (self
::$_relationshipTempTable) {
2604 // we have a temptable to join on
2605 $tbl = self
::$_relationshipTempTable;
2606 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2609 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2610 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id OR civicrm_relationship.contact_id_b = contact_b.id)";
2613 elseif (self
::$_relType == 'b') {
2614 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2615 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2618 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2619 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2624 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2625 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2629 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2632 case 'civicrm_grant':
2633 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2636 case 'civicrm_website':
2637 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2641 $locationTypeName = '';
2642 if (strpos($name, '-address') != 0) {
2643 $locationTypeName = 'address';
2645 elseif (strpos($name, '-phone') != 0) {
2646 $locationTypeName = 'phone';
2648 elseif (strpos($name, '-email') != 0) {
2649 $locationTypeName = 'email';
2651 if ($locationTypeName) {
2652 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2653 $parts = explode('-', $name);
2654 $locationID = array_search($parts[0], CRM_Core_BAO_Address
::buildOptions('location_type_id', 'get', array('name' => $parts[0])));
2655 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2658 $from .= CRM_Core_Component
::from($name, $mode, $side);
2660 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2669 * WHERE / QILL clause for deleted_contacts
2675 public function deletedContacts($values) {
2676 list($_, $_, $value, $grouping, $_) = $values;
2678 // *prepend* to the relevant grouping as this is quite an important factor
2679 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2684 * Where / qill clause for contact_type
2690 public function contactType(&$values) {
2691 list($name, $op, $value, $grouping, $wildcard) = $values;
2693 $subTypes = array();
2696 // account for search builder mapping multiple values
2697 if (!is_array($value)) {
2698 $values = self
::parseSearchBuilderString($value, 'String');
2699 if (is_array($values)) {
2700 $value = array_flip($values);
2704 if (is_array($value)) {
2705 foreach ($value as $k => $v) {
2710 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2711 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2714 if (!empty($subType)) {
2715 $subTypes[$subType] = 1;
2717 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2722 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2723 $contactType = $contactTypeANDSubType[0];
2724 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2725 if (!empty($subType)) {
2726 $subTypes[$subType] = 1;
2728 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2732 if (!empty($clause)) {
2734 if ($op == 'IN' ||
$op == 'NOT IN') {
2735 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2738 $type = array_pop($clause);
2739 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2742 $this->_qill
[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2744 if (!empty($subTypes)) {
2745 $this->includeContactSubTypes($subTypes, $grouping);
2751 * Where / qill clause for contact_sub_type
2757 public function contactSubType(&$values) {
2758 list($name, $op, $value, $grouping, $wildcard) = $values;
2759 $this->includeContactSubTypes($value, $grouping, $op);
2767 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2770 $alias = "contact_a.contact_sub_type";
2771 $qillOperators = array('NOT LIKE' => ts('Not Like')) + CRM_Core_SelectValues
::getSearchBuilderOperators();
2773 $op = str_replace('IN', 'LIKE', $op);
2774 $op = str_replace('=', 'LIKE', $op);
2775 $op = str_replace('!', 'NOT ', $op);
2777 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2778 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
2780 elseif (is_array($value)) {
2781 foreach ($value as $k => $v) {
2783 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($k, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2788 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2791 if (!empty($clause)) {
2792 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2794 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', array(1 => $qillOperators[$op])) . implode(' ' . ts('or') . ' ', array_keys($clause));
2798 * Where / qill clause for groups
2804 public function group(&$values) {
2805 list($name, $op, $value, $grouping, $wildcard) = $values;
2807 // Replace pseudo operators from search builder
2808 $op = str_replace('EMPTY', 'NULL', $op);
2810 if (count($value) > 1) {
2811 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
2812 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $op)));
2814 $this->_useDistinct
= TRUE;
2820 $isNotOp = ($op == 'NOT IN' ||
$op == '!=');
2823 if (strpos($op, 'IN') === FALSE) {
2824 $value = key($value);
2827 $value = array_keys($value);
2832 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2834 is_array($gcsValues[2])
2836 foreach ($gcsValues[2] as $k => $v) {
2838 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2843 $statii[] = '"Added"';
2847 if (!is_array($value) &&
2848 count($statii) == 1 &&
2849 $statii[0] == '"Added"' &&
2852 if (!empty($value) && CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $value, 'saved_search_id')) {
2857 $ssClause = $this->addGroupContactCache($value, NULL, "contact_a", $op);
2858 $isSmart = (!$ssClause) ?
FALSE : $isSmart;
2859 $groupClause = NULL;
2862 $groupIds = implode(',', (array) $value);
2863 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2864 $joinClause = array("contact_a.id = {$gcTable}.contact_id");
2866 $joinClause[] = "{$gcTable}.status IN (" . implode(', ', $statii) . ")";
2868 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
2869 $groupClause = "{$gcTable}.group_id $op $groupIds";
2870 if (strpos($op, 'IN') !== FALSE) {
2871 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2876 $and = ($op == 'IS NULL') ?
'AND' : 'OR';
2878 $groupClause = "( ( $groupClause ) $and ( $ssClause ) )";
2881 $groupClause = $ssClause;
2885 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
2886 $this->_qill
[$grouping][] = ts("Group(s) %1 %2", array(1 => $qillop, 2 => $qillVal));
2887 if (strpos($op, 'NULL') === FALSE) {
2888 $this->_qill
[$grouping][] = ts("Group Status %1", array(1 => implode(' ' . ts('or') . ' ', $statii)));
2891 $this->_where
[$grouping][] = $groupClause;
2896 * Function translates selection of group type into a list of groups.
2901 public function getGroupsFromTypeCriteria($value) {
2902 $groupIds = array();
2903 foreach ((array) $value as $groupTypeValue) {
2904 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2905 $groupIds = ($groupIds +
$groupList);
2911 * @param array $groups
2912 * @param string $tableAlias
2913 * @param string $joinTable
2916 * @return null|string
2918 public function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a", $op) {
2919 $isNullOp = (strpos($op, 'NULL') !== FALSE);
2920 $groupsIds = $groups;
2921 if (!$isNullOp && !$groups) {
2924 elseif (strpos($op, 'IN') !== FALSE) {
2925 $groups = array($op => $groups);
2928 // Find all the groups that are part of a saved search.
2929 $smartGroupClause = self
::buildClause("id", $op, $groups, 'Int');
2931 SELECT id, cache_date, saved_search_id, children
2933 WHERE $smartGroupClause
2934 AND ( saved_search_id != 0
2935 OR saved_search_id IS NOT NULL
2936 OR children IS NOT NULL )
2939 $group = CRM_Core_DAO
::executeQuery($sql);
2941 while ($group->fetch()) {
2942 $this->_useDistinct
= TRUE;
2943 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
2944 CRM_Contact_BAO_GroupContactCache
::load($group);
2949 $tableAlias = "`civicrm_group_contact_cache_";
2950 $tableAlias .= ($isNullOp) ?
"a`" : implode(',', (array) $groupsIds) . "`";
2953 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.id = {$tableAlias}.contact_id ";
2954 return self
::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
2958 * Where / qill clause for cms users
2964 public function ufUser(&$values) {
2965 list($name, $op, $value, $grouping, $wildcard) = $values;
2968 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2970 $this->_qill
[$grouping][] = ts('CMS User');
2972 elseif ($value == 0) {
2973 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2975 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2976 $this->_qill
[$grouping][] = ts('Not a CMS User');
2981 * All tag search specific.
2987 public function tagSearch(&$values) {
2988 list($name, $op, $value, $grouping, $wildcard) = $values;
2991 $value = "%{$value}%";
2993 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2994 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2996 $etTable = "`civicrm_entity_tag-" . $value . "`";
2997 $tTable = "`civicrm_tag-" . $value . "`";
2999 if ($useAllTagTypes[2]) {
3000 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3001 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3002 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3004 // search tag in cases
3005 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3006 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
3007 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3008 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3009 LEFT JOIN civicrm_case
3010 ON (civicrm_case_contact.case_id = civicrm_case.id
3011 AND civicrm_case.is_deleted = 0 )
3012 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3013 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3014 // search tag in activities
3015 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3016 $tActTable = "`civicrm_act_tag-" . $value . "`";
3017 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3018 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3020 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3021 = " LEFT JOIN civicrm_activity_contact
3022 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3023 LEFT JOIN civicrm_activity
3024 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3025 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3026 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3027 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3029 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $value . "' OR {$tCaseTable}.name $op '" . $value . "' OR {$tActTable}.name $op '" . $value . "')";
3030 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
3033 $etTable = "`civicrm_entity_tag-" . $value . "`";
3034 $tTable = "`civicrm_tag-" . $value . "`";
3035 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3036 {$etTable}.entity_table = 'civicrm_contact' )
3037 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3039 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3040 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
3045 * Where / qill clause for tag
3051 public function tag(&$values) {
3052 list($name, $op, $value, $grouping, $wildcard) = $values;
3054 $tagNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
3055 if (is_array($value)) {
3056 if (count($value) > 1) {
3057 $this->_useDistinct
= TRUE;
3059 foreach ($value as $id => $dontCare) {
3060 $names[] = CRM_Utils_Array
::value($id, $tagNames);
3062 $names = implode(' ' . ts('or') . ' ', $names);
3063 $value = implode(',', array_keys($value));
3066 $names = CRM_Utils_Array
::value($value, $tagNames);
3069 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3070 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3072 $etTable = "`civicrm_entity_tag-" . $value . "`";
3074 if ($useAllTagTypes[2]) {
3075 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3076 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3078 // search tag in cases
3079 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3080 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3081 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3083 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3084 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3085 LEFT JOIN civicrm_case
3086 ON (civicrm_case_contact.case_id = civicrm_case.id
3087 AND civicrm_case.is_deleted = 0 )
3088 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3089 // search tag in activities
3090 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3091 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3092 = " LEFT JOIN civicrm_activity_contact
3093 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3094 LEFT JOIN civicrm_activity
3095 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3096 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3097 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3100 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3101 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3104 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3106 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
3109 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3110 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3113 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3114 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3115 $op = str_replace('EMPTY', 'NULL', $op);
3116 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3119 $this->_where
[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
3121 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $names;
3127 * Where/qill clause for notes
3133 public function notes(&$values) {
3134 list($name, $op, $value, $grouping, $wildcard) = $values;
3136 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3137 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3138 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3140 $this->_useDistinct
= TRUE;
3142 $this->_tables
['civicrm_note'] = $this->_whereTables
['civicrm_note']
3143 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3145 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3147 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3148 if ($wildcard ||
$op == 'LIKE') {
3149 if (strpos($value, '%') === FALSE) {
3150 $value = "%$value%";
3154 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3160 if ($noteOption %
2 == 0) {
3161 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3162 $label = ts('Note: Body Only');
3164 if ($noteOption %
3 == 0) {
3165 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3166 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3168 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3169 $this->_qill
[$grouping][] = $label . " $op - '$n'";
3173 * @param string $name
3179 public function nameNullOrEmptyOp($name, $op, $grouping) {
3183 $this->_where
[$grouping][] = "contact_a.$name $op";
3184 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3188 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3189 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3192 case 'IS NOT EMPTY':
3193 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3194 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3203 * Where / qill clause for sort_name
3209 public function sortName(&$values) {
3210 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3212 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3213 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3217 $input = $value = trim($value);
3219 if (!strlen($value)) {
3223 $config = CRM_Core_Config
::singleton();
3227 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3230 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3232 $firstChar = substr($value, 0, 1);
3233 $lastChar = substr($value, -1, 1);
3234 $quotes = array("'", '"');
3235 // If string is quoted, strip quotes and otherwise don't alter it
3236 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3237 $value = trim($value, implode('', $quotes));
3239 // Replace spaces with wildcards for a LIKE operation
3240 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3241 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3242 $value = str_replace(' ', '%', $value);
3244 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($value)));
3245 if (strlen($value)) {
3246 $fieldsub = array();
3247 if ($wildcard && $op == 'LIKE') {
3248 if ($config->includeWildCardInName
) {
3249 $value = "'%$value%'";
3252 $value = "'$value%'";
3257 $value = "'$value'";
3259 if ($fieldName == 'sort_name') {
3260 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3263 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3265 $fieldsub[] = " ( $wc $op $value )";
3266 if ($config->includeNickNameInName
) {
3267 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3268 $fieldsub[] = " ( $wc $op $value )";
3270 if ($config->includeEmailInName
) {
3271 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3273 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3276 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3278 $this->_where
[$grouping][] = $sub;
3279 if ($config->includeEmailInName
) {
3280 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3281 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3284 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3289 * Where/qill clause for greeting fields.
3291 * @param array $values
3293 public function greetings(&$values) {
3294 list($name, $op, $value, $grouping, $wildcard) = $values;
3295 $name .= '_display';
3297 $this->_qill
[$grouping][] = ts('Greeting %1 %2', array(1 => $op, 2 => $value));
3298 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", 'LIKE', "$value", 'String');
3302 * Where / qill clause for email
3308 public function email(&$values) {
3309 list($name, $op, $value, $grouping, $wildcard) = $values;
3313 $config = CRM_Core_Config
::singleton();
3315 if (substr($n, 0, 1) == '"' &&
3316 substr($n, -1, 1) == '"'
3318 $n = substr($n, 1, -1);
3319 $value = strtolower(CRM_Core_DAO
::escapeString($n));
3320 $value = "'$value'";
3324 $value = strtolower($n);
3326 if (strpos($value, '%') === FALSE) {
3327 $value = "%{$value}%";
3332 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3333 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3336 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3337 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3340 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3344 * Where / qill clause for phone number
3350 public function phone_numeric(&$values) {
3351 list($name, $op, $value, $grouping, $wildcard) = $values;
3352 // Strip non-numeric characters; allow wildcards
3353 $number = preg_replace('/[^\d%]/', '', $value);
3355 if (strpos($number, '%') === FALSE) {
3356 $number = "%$number%";
3359 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3360 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3361 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3366 * Where / qill clause for phone type/location
3372 public function phone_option_group($values) {
3373 list($name, $op, $value, $grouping, $wildcard) = $values;
3374 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3375 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3376 $optionName = $options[$value];
3377 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3378 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3379 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3383 * Where / qill clause for street_address
3389 public function street_address(&$values) {
3390 list($name, $op, $value, $grouping, $wildcard) = $values;
3399 $value = strtolower($n);
3400 if (strpos($value, '%') === FALSE) {
3401 // only add wild card if not there
3402 $value = "%{$value}%";
3405 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3406 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3409 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3410 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3413 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3417 * Where / qill clause for street_unit
3423 public function street_number(&$values) {
3424 list($name, $op, $value, $grouping, $wildcard) = $values;
3432 if (strtolower($n) == 'odd') {
3433 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3434 $this->_qill
[$grouping][] = ts('Street Number is odd');
3436 elseif (strtolower($n) == 'even') {
3437 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3438 $this->_qill
[$grouping][] = ts('Street Number is even');
3441 $value = strtolower($n);
3443 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3444 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3447 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3451 * Where / qill clause for sorting by character
3457 public function sortByCharacter(&$values) {
3458 list($name, $op, $value, $grouping, $wildcard) = $values;
3460 $name = trim($value);
3461 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3462 $this->_where
[$grouping][] = $cond;
3463 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3467 * Where / qill clause for including contact ids
3471 public function includeContactIDs() {
3472 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3476 $contactIds = array();
3477 foreach ($this->_params
as $id => $values) {
3478 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3479 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3482 if (!empty($contactIds)) {
3483 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3488 * Where / qill clause for postal code
3494 public function postalCode(&$values) {
3495 // skip if the fields dont have anything to do with postal_code
3496 if (empty($this->_fields
['postal_code'])) {
3500 list($name, $op, $value, $grouping, $wildcard) = $values;
3502 // Handle numeric postal code range searches properly by casting the column as numeric
3503 if (is_numeric($value)) {
3504 $field = 'ROUND(civicrm_address.postal_code)';
3505 $val = CRM_Utils_Type
::escape($value, 'Integer');
3508 $field = 'civicrm_address.postal_code';
3509 $val = CRM_Utils_Type
::escape($value, 'String');
3512 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3514 if ($name == 'postal_code') {
3515 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3516 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3518 elseif ($name == 'postal_code_low') {
3519 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3520 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3522 elseif ($name == 'postal_code_high') {
3523 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3524 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3529 * Where / qill clause for location type
3532 * @param null $status
3536 public function locationType(&$values, $status = NULL) {
3537 list($name, $op, $value, $grouping, $wildcard) = $values;
3539 if (is_array($value)) {
3540 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3541 $this->_tables
['civicrm_address'] = 1;
3542 $this->_whereTables
['civicrm_address'] = 1;
3544 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3546 foreach ($value as $id) {
3547 $names[] = $locationType[$id];
3550 $this->_primaryLocation
= FALSE;
3553 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3556 return implode(' ' . ts('or') . ' ', $names);
3563 * @param bool $fromStateProvince
3565 * @return array|NULL
3567 public function country(&$values, $fromStateProvince = TRUE) {
3568 list($name, $op, $value, $grouping, $wildcard) = $values;
3570 if (!$fromStateProvince) {
3571 $stateValues = $this->getWhereValues('state_province', $grouping);
3572 if (!empty($stateValues)) {
3573 // return back to caller if there are state province values
3574 // since that handles this case
3579 $countryClause = $countryQill = NULL;
3585 $this->_tables
['civicrm_address'] = 1;
3586 $this->_whereTables
['civicrm_address'] = 1;
3588 $countries = CRM_Core_PseudoConstant
::country();
3589 if (is_numeric($value)) {
3590 $countryClause = self
::buildClause(
3591 'civicrm_address.country_id',
3596 $countryName = $countries[(int ) $value];
3600 $intValues = self
::parseSearchBuilderString($value);
3601 if ($intValues && ($op == 'IN' ||
$op == 'NOT IN')) {
3602 $countryClause = self
::buildClause(
3603 'civicrm_address.country_id',
3608 $countryNames = array();
3609 foreach ($intValues as $v) {
3610 $countryNames[] = $countries[$v];
3612 $countryName = implode(',', $countryNames);
3615 $countries = CRM_Core_PseudoConstant
::country();
3616 $intVal = CRM_Utils_Array
::key($value, $countries);
3617 $countryClause = self
::buildClause(
3618 'civicrm_address.country_id',
3623 $countryName = $value;
3626 $countryQill = ts('Country') . " {$op} '$countryName'";
3628 if (!$fromStateProvince) {
3629 $this->_where
[$grouping][] = $countryClause;
3630 $this->_qill
[$grouping][] = $countryQill;
3634 if ($fromStateProvince) {
3635 if (!empty($countryClause)) {
3638 " ...AND... " . $countryQill,
3642 return array(NULL, NULL);
3648 * Where / qill clause for county (if present)
3651 * @param null $status
3655 public function county(&$values, $status = NULL) {
3656 list($name, $op, $value, $grouping, $wildcard) = $values;
3658 if (!is_array($value)) {
3659 // force the county to be an array
3660 $value = array($value);
3663 // check if the values are ids OR names of the counties
3664 $inputFormat = 'id';
3665 foreach ($value as $v) {
3666 if (!is_numeric($v)) {
3667 $inputFormat = 'name';
3675 elseif ($op == '!=') {
3679 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3680 $op = str_replace('EMPTY', 'NULL', $op);
3683 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3684 $clause = "civicrm_address.county_id $op";
3686 elseif ($inputFormat == 'id') {
3687 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3689 $county = CRM_Core_PseudoConstant
::county();
3690 foreach ($value as $id) {
3691 $names[] = CRM_Utils_Array
::value($id, $county);
3695 $inputClause = array();
3696 $county = CRM_Core_PseudoConstant
::county();
3697 foreach ($value as $name) {
3698 $name = trim($name);
3699 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3701 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3704 $this->_tables
['civicrm_address'] = 1;
3705 $this->_whereTables
['civicrm_address'] = 1;
3707 $this->_where
[$grouping][] = $clause;
3709 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3712 return implode(' ' . ts('or') . ' ', $names);
3717 * Where / qill clause for state/province AND country (if present)
3720 * @param null $status
3724 public function stateProvince(&$values, $status = NULL) {
3725 list($name, $op, $value, $grouping, $wildcard) = $values;
3727 // quick escape for IS NULL
3728 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3731 elseif (!is_array($value)) {
3732 // force the state to be an array
3733 // check if its in the mapper format!
3734 $values = self
::parseSearchBuilderString($value);
3735 if (is_array($values)) {
3739 $value = array($value);
3743 // check if the values are ids OR names of the states
3744 $inputFormat = 'id';
3746 foreach ($value as $v) {
3747 if (!is_numeric($v)) {
3748 $inputFormat = 'name';
3758 elseif ($op == '!=') {
3762 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3763 $op = str_replace('EMPTY', 'NULL', $op);
3765 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3766 $stateClause = "civicrm_address.state_province_id $op";
3768 elseif ($inputFormat == 'id') {
3769 if ($op != 'NOT IN') {
3772 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
3774 foreach ($value as $id) {
3775 $names[] = CRM_Core_PseudoConstant
::stateProvince($id, FALSE);
3779 $inputClause = array();
3780 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3781 foreach ($value as $name) {
3782 $name = trim($name);
3783 $inputClause[] = CRM_Utils_Array
::key($name, $stateProvince);
3785 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
3788 $this->_tables
['civicrm_address'] = 1;
3789 $this->_whereTables
['civicrm_address'] = 1;
3791 $countryValues = $this->getWhereValues('country', $grouping);
3792 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3794 if ($countryClause) {
3795 $clause = "( $stateClause AND $countryClause )";
3798 $clause = $stateClause;
3801 $this->_where
[$grouping][] = $clause;
3803 $this->_qill
[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3806 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
3811 * Where / qill clause for change log
3817 public function changeLog(&$values) {
3818 list($name, $op, $value, $grouping, $wildcard) = $values;
3820 $targetName = $this->getWhereValues('changed_by', $grouping);
3825 $name = trim($targetName[2]);
3826 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3827 $name = $targetName[4] ?
"%$name%" : $name;
3828 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3829 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3830 $this->_qill
[$grouping][] = ts('Modified By') . " $name";
3836 public function modifiedDates($values) {
3837 $this->_useDistinct
= TRUE;
3839 // CRM-11281, default to added date if not set
3840 $fieldTitle = ts('Added Date');
3841 $fieldName = 'created_date';
3842 foreach (array_keys($this->_params
) as $id) {
3843 if ($this->_params
[$id][0] == 'log_date') {
3844 if ($this->_params
[$id][2] == 2) {
3845 $fieldTitle = ts('Modified Date');
3846 $fieldName = 'modified_date';
3851 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3853 self
::$_openedPanes[ts('Change Log')] = TRUE;
3859 public function demographics(&$values) {
3860 list($name, $op, $value, $grouping, $wildcard) = $values;
3862 if (($name == 'age_low') ||
($name == 'age_high')) {
3863 $this->ageRangeQueryBuilder($values,
3864 'contact_a', 'age', 'birth_date', ts('Age')
3867 elseif (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3869 $this->dateQueryBuilder($values,
3870 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3873 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3875 $this->dateQueryBuilder($values,
3876 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3880 self
::$_openedPanes[ts('Demographics')] = TRUE;
3886 public function privacy(&$values) {
3887 list($name, $op, $value, $grouping, $wildcard) = $values;
3888 //fixed for profile search listing CRM-4633
3889 if (strpbrk($value, "[")) {
3890 $value = "'{$value}'";
3892 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3895 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3897 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3898 $title = $field ?
$field['title'] : $name;
3899 $this->_qill
[$grouping][] = "$title $op $value";
3905 public function privacyOptions($values) {
3906 list($name, $op, $value, $grouping, $wildcard) = $values;
3908 if (empty($value) ||
!is_array($value)) {
3912 // get the operator and toggle values
3913 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3916 strtolower($opValues[2] == 'AND')
3921 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3923 if ($toggleValues &&
3924 $toggleValues[2] == 2
3931 foreach ($value as $dontCare => $pOption) {
3932 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
3933 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3934 $title = $field ?
$field['title'] : $pOption;
3935 $qill[] = " $title = 1 ";
3938 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
3939 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
3945 public function preferredCommunication(&$values) {
3946 list($name, $op, $value, $grouping, $wildcard) = $values;
3949 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3952 elseif (!is_array($value)) {
3954 $value = trim($value, ' ()');
3955 if (strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
3956 $v = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
3959 $v = explode(",", $value);
3962 foreach ($v as $item) {
3969 foreach ($value as $key => $checked) {
3976 $commPref = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
3978 $sqlValue = array();
3979 $showValue = array();
3980 $sql = "contact_a.preferred_communication_method";
3981 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3982 $sqlValue[] = "{$sql} {$op}";
3985 foreach ($pref as $val) {
3986 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $val . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' ) ";
3987 $showValue[] = $commPref[$val];
3990 $this->_where
[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
3991 $this->_qill
[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
3995 * Where / qill clause for relationship
4001 public function relationship(&$values) {
4002 list($name, $op, $value, $grouping, $wildcard) = $values;
4003 if ($this->_relationshipValuesAdded
) {
4006 // also get values array for relation_target_name
4007 // for relationship search we always do wildcard
4008 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4009 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4010 $relStatus = $this->getWhereValues('relation_status', $grouping);
4011 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4012 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4014 $nameClause = $name = NULL;
4016 $name = trim($targetName[2]);
4017 if (substr($name, 0, 1) == '"' &&
4018 substr($name, -1, 1) == '"'
4020 $name = substr($name, 1, -1);
4021 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4022 $nameClause = "= '$name'";
4025 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4026 $nameClause = "LIKE '%{$name}%'";
4030 $rTypeValues = array();
4031 if (!empty($relationType)) {
4032 $rel = explode('_', $relationType[2]);
4033 self
::$_relType = $rel[1];
4034 $params = array('id' => $rel[0]);
4035 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
4037 if (!empty($rTypeValues) && $rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
4038 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4039 //@todo unless we are dealing with a target group
4040 self
::$_relType = 'reciprocal';
4042 // if we are creating a temp table we build our own where for the relationship table
4043 $relationshipTempTable = NULL;
4044 if (self
::$_relType == 'reciprocal' && empty($targetGroup)) {
4046 self
::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO
::createTempTableName('civicrm_rel');
4048 $where[$grouping][] = " sort_name $nameClause ";
4052 $where = &$this->_where
;
4054 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4058 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
4059 $relTypeOrg = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
4060 $relTypeHou = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Household');
4061 $allRelationshipType = array();
4062 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
4063 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
4065 if ($nameClause ||
!$targetGroup) {
4066 if (!empty($relationType)) {
4067 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " $name";
4070 $this->_qill
[$grouping][] = $name;
4074 //check to see if the target contact is in specified group
4076 //add contacts from static groups
4077 $this->_tables
['civicrm_relationship_group_contact'] = $this->_whereTables
['civicrm_relationship_group_contact']
4078 = " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = contact_b.id AND civicrm_relationship_group_contact.status = 'Added'";
4079 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4080 implode(",", $targetGroup[2]) . ") ) ";
4082 //add contacts from saved searches
4083 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b", $op);
4085 //set the group where clause
4087 $groupWhere[] = "( " . $ssWhere . " )";
4089 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4091 //Get the names of the target groups for the qill
4092 $groupNames = CRM_Core_PseudoConstant
::group();
4093 $qillNames = array();
4094 foreach ($targetGroup[2] as $groupId) {
4095 if (array_key_exists($groupId, $groupNames)) {
4096 $qillNames[] = $groupNames[$groupId];
4099 if (!empty($relationType)) {
4100 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " ( " . implode(", ", $qillNames) . " )";
4103 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4107 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4108 $today = date('Ymd');
4109 //check for active, inactive and all relation status
4110 if ($relStatus[2] == 0) {
4111 $where[$grouping][] = "(
4112 civicrm_relationship.is_active = 1 AND
4113 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4114 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4116 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4118 elseif ($relStatus[2] == 1) {
4119 $where[$grouping][] = "(
4120 civicrm_relationship.is_active = 0 OR
4121 civicrm_relationship.end_date < {$today} OR
4122 civicrm_relationship.start_date > {$today}
4124 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4128 if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
)) {
4131 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4133 //check for permissioned, non-permissioned and all permissioned relations
4134 if ($relPermission[2] == 1) {
4135 $where[$grouping][] = "(
4136 civicrm_relationship.is_permission_a_b = 1
4138 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4140 elseif ($relPermission[2] == 2) {
4141 //non-allowed permission relationship.
4142 $where[$grouping][] = "(
4143 civicrm_relationship.is_permission_a_b = 0
4145 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4148 $this->addRelationshipDateClauses($grouping, $where);
4149 if (!empty($relationType) && !empty($rType) && isset($rType->id
)) {
4150 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
4152 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4153 $this->_useDistinct
= TRUE;
4154 $this->_relationshipValuesAdded
= TRUE;
4155 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4157 // @todo creating a temp table could be expanded to group filter
4158 // as even creating a temp table of all relationships is much much more efficient than
4159 // an OR in the join
4160 if ($relationshipTempTable) {
4162 if (!empty($where[$grouping])) {
4163 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4164 $whereClause = str_replace('contact_b', 'c', $whereClause);
4167 CREATE TEMPORARY TABLE {$relationshipTempTable}
4168 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4169 FROM civicrm_relationship
4170 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4173 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4174 FROM civicrm_relationship
4175 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4178 CRM_Core_DAO
::executeQuery($sql);
4184 * Add start & end date criteria in
4185 * @param string $grouping
4186 * @param array $where
4187 * = array to add where clauses to, in case you are generating a temp table.
4188 * not the main query.
4190 public function addRelationshipDateClauses($grouping, &$where) {
4191 $dateValues = array();
4197 foreach ($dateTypes as $dateField) {
4198 $dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping);
4199 $dateValueHigh = $this->getWhereValues('relation_' . $dateField . '_high', $grouping);
4200 if (!empty($dateValueLow)) {
4201 $date = date('Ymd', strtotime($dateValueLow[2]));
4202 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4203 $this->_qill
[$grouping][] = ($dateField == 'end_date' ?
ts('Relationship Ended on or After') : ts('Relationship Recorded Start Date On or Before')) . " " . CRM_Utils_Date
::customFormat($date);
4205 if (!empty($dateValueHigh)) {
4206 $date = date('Ymd', strtotime($dateValueHigh[2]));
4207 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4208 $this->_qill
[$grouping][] = ($dateField == 'end_date' ?
ts('Relationship Ended on or Before') : ts('Relationship Recorded Start Date On or After')) . " " . CRM_Utils_Date
::customFormat($date);
4214 * Default set of return properties.
4219 * derault return properties
4221 public static function &defaultReturnProperties($mode = 1) {
4222 if (!isset(self
::$_defaultReturnProperties)) {
4223 self
::$_defaultReturnProperties = array();
4226 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4227 // add activity return properties
4228 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4229 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4232 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4235 if (empty(self
::$_defaultReturnProperties[$mode])) {
4236 self
::$_defaultReturnProperties[$mode] = array(
4239 'legal_identifier' => 1,
4240 'external_identifier' => 1,
4241 'contact_type' => 1,
4242 'contact_sub_type' => 1,
4244 'display_name' => 1,
4245 'preferred_mail_format' => 1,
4252 'formal_title' => 1,
4253 'communication_style_id' => 1,
4256 'street_address' => 1,
4257 'supplemental_address_1' => 1,
4258 'supplemental_address_2' => 1,
4261 'postal_code_suffix' => 1,
4262 'state_province' => 1,
4264 'world_region' => 1,
4271 'household_name' => 1,
4272 'organization_name' => 1,
4273 'deceased_date' => 1,
4278 'current_employer' => 1,
4279 // FIXME: should we use defaultHierReturnProperties() for the below?
4280 'do_not_email' => 1,
4283 'do_not_phone' => 1,
4284 'do_not_trade' => 1,
4286 'contact_is_deleted' => 1,
4287 'preferred_communication_method' => 1,
4288 'preferred_language' => 1,
4292 return self
::$_defaultReturnProperties[$mode];
4296 * Get primary condition for a sql clause.
4300 * @return string|NULL
4302 public static function getPrimaryCondition($value) {
4303 if (is_numeric($value)) {
4304 $value = (int ) $value;
4305 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4311 * Wrapper for a simple search query.
4313 * @param array $params
4314 * @param array $returnProperties
4315 * @param bool $count
4319 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4320 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4321 list($select, $from, $where, $having) = $query->query();
4323 return "$select $from $where $having";
4327 * These are stub comments as this function needs more explanation - particularly in terms of how it
4328 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4330 * This function was originally written as a wrapper for the api query but is called from multiple places
4331 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4332 * but it is unclear as to whehter that is historical or there is a reason
4333 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4335 * @param array $params
4336 * @param array $returnProperties
4337 * @param null $fields
4338 * @param string $sort
4339 * @param int $offset
4340 * @param int $row_count
4341 * @param bool $smartGroupCache
4342 * ?? update smart group cache?.
4343 * @param bool $count
4344 * Return count obnly.
4345 * @param bool $skipPermissions
4346 * Should permissions be ignored or should the logged in user's permissions be applied.
4351 public static function apiQuery(
4353 $returnProperties = NULL,
4358 $smartGroupCache = TRUE,
4360 $skipPermissions = TRUE
4363 $query = new CRM_Contact_BAO_Query(
4364 $params, $returnProperties,
4365 NULL, TRUE, FALSE, 1,
4367 TRUE, $smartGroupCache
4370 //this should add a check for view deleted if permissions are enabled
4371 if ($skipPermissions) {
4372 $query->_skipDeleteClause
= TRUE;
4374 $query->generatePermissionClause(FALSE, $count);
4376 // note : this modifies _fromClause and _simpleFromClause
4377 $query->includePseudoFieldsJoin($sort);
4379 list($select, $from, $where, $having) = $query->query($count);
4381 $options = $query->_options
;
4382 if (!empty($query->_permissionWhereClause
)) {
4383 if (empty($where)) {
4384 $where = "WHERE $query->_permissionWhereClause";
4387 $where = "$where AND $query->_permissionWhereClause";
4391 $sql = "$select $from $where $having";
4394 if ($query->_useGroupBy
) {
4395 $sql .= ' GROUP BY contact_a.id';
4397 if (!empty($sort)) {
4398 $sort = CRM_Utils_Type
::escape($sort, 'String');
4399 $sql .= " ORDER BY $sort ";
4401 if ($row_count > 0 && $offset >= 0) {
4402 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4403 $rowCount = CRM_Utils_Type
::escape($row_count, 'Int');
4404 $sql .= " LIMIT $offset, $row_count ";
4407 $dao = CRM_Core_DAO
::executeQuery($sql);
4410 while ($dao->fetch()) {
4412 $noRows = $dao->rowCount
;
4414 return array($noRows, NULL);
4416 $val = $query->store($dao);
4417 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4419 if (!empty($convertedVals)) {
4420 $val = array_replace_recursive($val, $convertedVals);
4422 $values[$dao->contact_id
] = $val;
4425 return array($values, $options);
4429 * Create and query the db for an contact search.
4431 * @param int $offset
4432 * The offset for the query.
4433 * @param int $rowCount
4434 * The number of rows to return.
4435 * @param string $sort
4436 * The order by string.
4437 * @param bool $count
4438 * Is this a count only query ?.
4439 * @param bool $includeContactIds
4440 * Should we include contact ids?.
4441 * @param bool $sortByChar
4442 * If true returns the distinct array of first characters for search results.
4443 * @param bool $groupContacts
4444 * If true, return only the contact ids.
4445 * @param bool $returnQuery
4446 * Should we return the query as a string.
4447 * @param string $additionalWhereClause
4448 * If the caller wants to further restrict the search (used for components).
4449 * @param null $sortOrder
4450 * @param string $additionalFromClause
4451 * Should be clause with proper joins, effective to reduce where clause load.
4453 * @param bool $skipOrderAndLimit
4455 * @return CRM_Core_DAO
4457 public function searchQuery(
4458 $offset = 0, $rowCount = 0, $sort = NULL,
4459 $count = FALSE, $includeContactIds = FALSE,
4460 $sortByChar = FALSE, $groupContacts = FALSE,
4461 $returnQuery = FALSE,
4462 $additionalWhereClause = NULL, $sortOrder = NULL,
4463 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4466 if ($includeContactIds) {
4467 $this->_includeContactIds
= TRUE;
4468 $this->_whereClause
= $this->whereClause();
4471 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4473 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4474 // and that contact happens to be deleted, set $onlyDeleted to true
4475 foreach ($this->_params
as $values) {
4476 $name = CRM_Utils_Array
::value(0, $values);
4477 $op = CRM_Utils_Array
::value(1, $values);
4478 $value = CRM_Utils_Array
::value(2, $values);
4479 if ($name == 'contact_id' and $op == '=') {
4480 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4481 $onlyDeleted = TRUE;
4487 // building the query string
4490 if (isset($this->_groupByComponentClause
)) {
4491 $groupBy = $this->_groupByComponentClause
;
4493 elseif ($this->_useGroupBy
) {
4494 $groupBy = ' GROUP BY contact_a.id';
4497 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4498 $groupBy = 'GROUP BY civicrm_activity.id ';
4501 $order = $orderBy = $limit = '';
4503 $config = CRM_Core_Config
::singleton();
4504 if ($config->includeOrderByClause ||
4505 isset($this->_distinctComponentClause
)
4508 if (is_string($sort)) {
4512 $orderBy = trim($sort->orderBy());
4514 if (!empty($orderBy)) {
4515 // this is special case while searching for
4516 // change log CRM-1718
4517 if (preg_match('/sort_name/i', $orderBy)) {
4518 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4521 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
4522 $order = " ORDER BY $orderBy";
4525 $sortOrder = CRM_Utils_Type
::escape($sortOrder, 'String');
4526 $order .= " $sortOrder";
4529 // always add contact_a.id to the ORDER clause
4530 // so the order is deterministic
4531 if (strpos('contact_a.id', $order) === FALSE) {
4532 $order .= ", contact_a.id";
4536 elseif ($sortByChar) {
4537 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4540 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4544 // hack for order clause
4546 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4547 $fieldOrder = explode(' ', $fieldStr);
4548 $field = $fieldOrder[0];
4554 $this->_whereTables
["civicrm_address"] = 1;
4555 $order = str_replace($field, "civicrm_address.{$field}", $order);
4559 case 'state_province':
4560 $this->_whereTables
["civicrm_{$field}"] = 1;
4561 $order = str_replace($field, "civicrm_{$field}.name", $order);
4565 $this->_whereTables
["civicrm_email"] = 1;
4566 $order = str_replace($field, "civicrm_email.{$field}", $order);
4570 //CRM-12565 add "`" around $field if it is a pseudo constant
4571 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
4572 if (!empty($value['element']) && $value['element'] == $field) {
4573 $order = str_replace($field, "`{$field}`", $order);
4577 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4578 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4582 if ($rowCount > 0 && $offset >= 0) {
4583 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4584 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4585 $limit = " LIMIT $offset, $rowCount ";
4590 $this->_sort
= $sort;
4592 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4594 if ($additionalWhereClause) {
4595 $where = $where . ' AND ' . $additionalWhereClause;
4598 //additional from clause should be w/ proper joins.
4599 if ($additionalFromClause) {
4600 $from .= "\n" . $additionalFromClause;
4603 // if we are doing a transform, do it here
4604 // use the $from, $where and $having to get the contact ID
4605 if ($this->_displayRelationshipType
) {
4606 $this->filterRelatedContacts($from, $where, $having);
4609 if ($skipOrderAndLimit) {
4610 $query = "$select $from $where $having $groupBy";
4613 $query = "$select $from $where $having $groupBy $order $limit";
4620 return CRM_Core_DAO
::singleValueQuery($query);
4623 $dao = CRM_Core_DAO
::executeQuery($query);
4624 if ($groupContacts) {
4626 while ($dao->fetch()) {
4629 return implode(',', $ids);
4636 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4638 * @param string $cacheKey
4639 * @param int $offset
4640 * @param int $rowCount
4641 * @param bool $includeContactIds
4642 * @return CRM_Core_DAO
4644 public function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4645 $this->_includeContactIds
= $includeContactIds;
4646 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4647 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
4648 $from = " FROM civicrm_prevnext_cache pnc INNER JOIN civicrm_contact contact_a ON contact_a.id = pnc.entity_id1 AND pnc.cacheKey = '$cacheKey' " . substr($from, 31);
4649 $order = " ORDER BY pnc.id";
4650 $groupBy = " GROUP BY contact_a.id";
4651 $limit = " LIMIT $offset, $rowCount";
4652 $query = "$select $from $where $groupBy $order $limit";
4654 return CRM_Core_DAO
::executeQuery($query);
4658 * Populate $this->_permissionWhereClause with permission related clause and update other
4659 * query related properties.
4661 * Function calls ACL permission class and hooks to filter the query appropriately
4663 * Note that these 2 params were in the code when extracted from another function
4664 * and a second round extraction would be to make them properties of the class
4666 * @param bool $onlyDeleted
4667 * Only get deleted contacts.
4668 * @param bool $count
4669 * Return Count only.
4671 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4672 if (!$this->_skipPermission
) {
4673 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4674 CRM_Core_Permission
::VIEW
,
4676 $this->_whereTables
,
4679 $this->_skipDeleteClause
4682 // regenerate fromClause since permission might have added tables
4683 if ($this->_permissionWhereClause
) {
4684 //fix for row count in qill (in contribute/membership find)
4686 $this->_useDistinct
= TRUE;
4689 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4690 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4691 // note : this modifies _fromClause and _simpleFromClause
4692 $this->includePseudoFieldsJoin($this->_sort
);
4696 // add delete clause if needed even if we are skipping permission
4698 if (!$this->_skipDeleteClause
) {
4699 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4700 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4704 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4713 public function setSkipPermission($val) {
4714 $this->_skipPermission
= $val;
4718 * @param null $context
4722 public function &summaryContribution($context = NULL) {
4723 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4727 SELECT COUNT( conts.total_amount ) as total_count,
4728 SUM( conts.total_amount ) as total_amount,
4729 AVG( conts.total_amount ) as total_avg,
4730 conts.total_amount as amount,
4731 conts.currency as currency";
4732 if ($this->_permissionWhereClause
) {
4733 $where .= " AND " . $this->_permissionWhereClause
;
4735 if ($context == 'search') {
4736 $where .= " AND contact_a.is_deleted = 0 ";
4739 // make sure contribution is completed - CRM-4989
4740 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4743 $summary['total'] = array();
4744 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4745 $innerQuery = "SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
4746 civicrm_contribution.currency $from $completedWhere";
4748 $query = "$select FROM (
4749 $innerQuery GROUP BY civicrm_contribution.id
4753 $dao = CRM_Core_DAO
::executeQuery($query);
4755 $summary['total']['count'] = 0;
4756 $summary['total']['amount'] = $summary['total']['avg'] = array();
4757 while ($dao->fetch()) {
4758 $summary['total']['count'] +
= $dao->total_count
;
4759 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4760 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4763 $orderBy = 'ORDER BY civicrm_contribution_total_amount_count DESC';
4764 $groupBy = 'GROUP BY currency, civicrm_contribution.total_amount';
4765 $modeSQL = "$select, conts.civicrm_contribution_total_amount_count as civicrm_contribution_total_amount_count FROM ($innerQuery
4766 $groupBy $orderBy) as conts
4769 $summary['total']['mode'] = CRM_Contribute_BAO_Contribution
::computeStats('mode', $modeSQL);
4771 $medianSQL = "{$from} {$completedWhere}";
4772 $summary['total']['median'] = CRM_Contribute_BAO_Contribution
::computeStats('median', $medianSQL, 'civicrm_contribution');
4773 $summary['total']['currencyCount'] = count($summary['total']['median']);
4775 if (!empty($summary['total']['amount'])) {
4776 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4777 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4778 $summary['total']['mode'] = implode(', ', $summary['total']['mode']);
4779 $summary['total']['median'] = implode(', ', $summary['total']['median']);
4782 $summary['total']['amount'] = $summary['total']['avg'] = $summary['total']['median'] = 0;
4785 // soft credit summary
4786 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
4787 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
4790 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
4791 GROUP BY civicrm_contribution_soft.id
4794 $dao = CRM_Core_DAO
::executeQuery($query);
4795 $summary['soft_credit']['count'] = 0;
4796 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
4797 while ($dao->fetch()) {
4798 $summary['soft_credit']['count'] +
= $dao->total_count
;
4799 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4800 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4802 if (!empty($summary['soft_credit']['amount'])) {
4803 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
4804 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
4807 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
4812 //@todo - this could be one query using the IF in mysql - eg
4813 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
4814 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
4815 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
4816 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
4817 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
4818 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
4819 // FROM civicrm_contact contact_a
4820 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
4821 // WHERE ( ... where clause....
4822 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
4826 SELECT COUNT( conts.total_amount ) as cancel_count,
4827 SUM( conts.total_amount ) as cancel_amount,
4828 AVG( conts.total_amount ) as cancel_avg,
4829 conts.currency as currency";
4831 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4832 if ($context == 'search') {
4833 $where .= " AND contact_a.is_deleted = 0 ";
4836 $query = "$select FROM (
4837 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
4838 GROUP BY civicrm_contribution.id
4842 $dao = CRM_Core_DAO
::executeQuery($query);
4845 if ($dao->fetch()) {
4846 $summary['cancel']['count'] = $dao->cancel_count
;
4847 $summary['cancel']['amount'] = $dao->cancel_amount
;
4848 $summary['cancel']['avg'] = $dao->cancel_avg
;
4852 $summary['cancel']['count'] = 0;
4853 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4854 while ($dao->fetch()) {
4855 $summary['cancel']['count'] +
= $dao->cancel_count
;
4856 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4857 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4859 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4860 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
4867 * Getter for the qill object.
4871 public function qill() {
4872 return $this->_qill
;
4876 * Default set of return default hier return properties.
4880 public static function &defaultHierReturnProperties() {
4881 if (!isset(self
::$_defaultHierReturnProperties)) {
4882 self
::$_defaultHierReturnProperties = array(
4885 'legal_identifier' => 1,
4886 'external_identifier' => 1,
4887 'contact_type' => 1,
4888 'contact_sub_type' => 1,
4890 'display_name' => 1,
4897 'formal_title' => 1,
4898 'communication_style_id' => 1,
4899 'email_greeting' => 1,
4900 'postal_greeting' => 1,
4904 'preferred_communication_method' => 1,
4905 'do_not_phone' => 1,
4906 'do_not_email' => 1,
4909 'do_not_trade' => 1,
4910 'location' => array(
4912 'location_type' => 1,
4913 'street_address' => 1,
4915 'state_province' => 1,
4917 'postal_code_suffix' => 1,
4920 'phone-Mobile' => 1,
4933 'location_type' => 1,
4934 'street_address' => 1,
4936 'state_province' => 1,
4938 'postal_code_suffix' => 1,
4941 'phone-Mobile' => 1,
4955 return self
::$_defaultHierReturnProperties;
4960 * @param string $tableName
4961 * @param string $fieldName
4962 * @param string $dbFieldName
4963 * @param $fieldTitle
4964 * @param bool $appendTimeStamp
4966 public function dateQueryBuilder(
4967 &$values, $tableName, $fieldName,
4968 $dbFieldName, $fieldTitle,
4969 $appendTimeStamp = TRUE
4971 list($name, $op, $value, $grouping, $wildcard) = $values;
4973 if ($name == "{$fieldName}_low" ||
4974 $name == "{$fieldName}_high"
4976 if (isset($this->_rangeCache
[$fieldName]) ||
!$value) {
4979 $this->_rangeCache
[$fieldName] = 1;
4981 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4983 if ($name == $fieldName . '_low') {
4985 $firstPhrase = ts('greater than or equal to');
4986 $firstDate = CRM_Utils_Date
::processDate($value);
4988 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4989 if (!empty($secondValues) && $secondValues[2]) {
4991 $secondPhrase = ts('less than or equal to');
4992 $secondValue = $secondValues[2];
4994 if ($appendTimeStamp && strlen($secondValue) == 10) {
4995 $secondValue .= ' 23:59:59';
4997 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5000 elseif ($name == $fieldName . '_high') {
5002 $firstPhrase = ts('less than or equal to');
5004 if ($appendTimeStamp && strlen($value) == 10) {
5005 $value .= ' 23:59:59';
5007 $firstDate = CRM_Utils_Date
::processDate($value);
5009 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5010 if (!empty($secondValues) && $secondValues[2]) {
5012 $secondPhrase = ts('greater than or equal to');
5013 $secondValue = $secondValues[2];
5014 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5018 if (!$appendTimeStamp) {
5019 $firstDate = substr($firstDate, 0, 8);
5021 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5024 if (!$appendTimeStamp) {
5025 $secondDate = substr($secondDate, 0, 8);
5027 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5030 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5032 $this->_where
[$grouping][] = "
5033 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5034 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5036 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5039 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5040 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5044 if ($name == $fieldName) {
5045 //In Get API, for operators other then '=' the $value is in array(op => value) format
5046 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5048 $value = $value[$op];
5051 $date = $format = NULL;
5052 if (strstr($op, 'IN')) {
5054 foreach ($value as &$date) {
5055 $date = CRM_Utils_Date
::processDate($date);
5056 if (!$appendTimeStamp) {
5057 $date = substr($date, 0, 8);
5059 $format[] = CRM_Utils_Date
::customFormat($date);
5061 $date = "('" . implode("','", $value) . "')";
5062 $format = implode(', ', $format);
5064 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5065 $date = CRM_Utils_Date
::processDate($value);
5066 if (!$appendTimeStamp) {
5067 $date = substr($date, 0, 8);
5069 $format = CRM_Utils_Date
::customFormat($date);
5074 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5077 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op";
5080 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5082 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
5083 $this->_qill
[$grouping][] = "$fieldTitle $op $format";
5089 * @param string $tableName
5090 * @param string $fieldName
5091 * @param string $dbFieldName
5092 * @param $fieldTitle
5093 * @param null $options
5095 public function numberRangeBuilder(
5097 $tableName, $fieldName,
5098 $dbFieldName, $fieldTitle,
5101 list($name, $op, $value, $grouping, $wildcard) = $values;
5103 if ($name == "{$fieldName}_low" ||
5104 $name == "{$fieldName}_high"
5106 if (isset($this->_rangeCache
[$fieldName])) {
5109 $this->_rangeCache
[$fieldName] = 1;
5111 $secondOP = $secondPhrase = $secondValue = NULL;
5113 if ($name == "{$fieldName}_low") {
5115 $firstPhrase = ts('greater than');
5117 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5118 if (!empty($secondValues)) {
5120 $secondPhrase = ts('less than');
5121 $secondValue = $secondValues[2];
5126 $firstPhrase = ts('less than');
5128 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5129 if (!empty($secondValues)) {
5131 $secondPhrase = ts('greater than');
5132 $secondValue = $secondValues[2];
5137 $this->_where
[$grouping][] = "
5138 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5139 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5141 $displayValue = $options ?
$options[$value] : $value;
5142 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5144 $this->_qill
[$grouping][]
5145 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5148 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5149 $displayValue = $options ?
$options[$value] : $value;
5150 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5152 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5157 if ($name == $fieldName) {
5161 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5163 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5164 $displayValue = $options ?
$options[$value] : $value;
5165 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5172 * @param string $tableName
5173 * @param string $fieldName
5174 * @param string $dbFieldName
5175 * @param $fieldTitle
5176 * @param null $options
5178 public function ageRangeQueryBuilder(
5180 $tableName, $fieldName,
5181 $dbFieldName, $fieldTitle,
5184 list($name, $op, $value, $grouping, $wildcard) = $values;
5186 $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
5187 $asofDate = NULL; // will be treated as current day
5188 if ($asofDateValues) {
5189 $asofDate = CRM_Utils_Date
::processDate($asofDateValues[2]);
5190 $asofDateFormat = CRM_Utils_Date
::customFormat(substr($asofDate, 0, 8));
5191 $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat;
5194 if ($name == "{$fieldName}_low" ||
5195 $name == "{$fieldName}_high"
5197 if (isset($this->_rangeCache
[$fieldName])) {
5200 $this->_rangeCache
[$fieldName] = 1;
5202 $secondOP = $secondPhrase = $secondValue = NULL;
5204 if ($name == "{$fieldName}_low") {
5205 $firstPhrase = ts('greater than or equal to');
5206 // NB: age > X means date of birth < Y
5208 $firstDate = self
::calcDateFromAge($asofDate, $value, 'min');
5210 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5211 if (!empty($secondValues)) {
5213 $secondPhrase = ts('less than or equal to');
5214 $secondValue = $secondValues[2];
5215 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'max');
5220 $firstPhrase = ts('less than or equal to');
5221 $firstDate = self
::calcDateFromAge($asofDate, $value, 'max');
5223 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5224 if (!empty($secondValues)) {
5226 $secondPhrase = ts('greater than or equal to');
5227 $secondValue = $secondValues[2];
5228 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'min');
5233 $this->_where
[$grouping][] = "
5234 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5235 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5237 $displayValue = $options ?
$options[$value] : $value;
5238 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5240 $this->_qill
[$grouping][]
5241 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5244 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5245 $displayValue = $options ?
$options[$value] : $value;
5246 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5248 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5253 public static function calcDateFromAge($asofDate, $age, $type) {
5254 $date = new DateTime($asofDate);
5255 if ($type == "min") {
5256 // minimum age is $age: dob <= date - age "235959"
5257 $date->sub(new DateInterval("P" . $age . "Y"));
5258 return $date->format('Ymd') . "235959";
5261 // max age is $age: dob >= date - (age + 1y) + 1d "000000"
5262 $date->sub(new DateInterval("P" . ($age +
1) . "Y"))->add(new DateInterval("P1D"));
5263 return $date->format('Ymd') . "000000";
5268 * Given the field name, operator, value & its data type
5269 * builds the where Clause for the query
5270 * used for handling 'IS NULL'/'IS NOT NULL' operators
5272 * @param string $field
5276 * @param string $value
5278 * @param string $dataType
5279 * Data type of the field.
5282 * Where clause for the query.
5284 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5286 $clause = "$field $op";
5294 $clause = " (NULLIF($field, '') IS NULL) ";
5297 case 'IS NOT EMPTY':
5298 $clause = " (NULLIF($field, '') IS NOT NULL) ";
5302 if (empty($dataType)) {
5303 $dataType = 'String';
5305 if (is_array($value)) {
5306 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5307 // widely used and consistent across the codebase
5308 // adding this here won't accept the search functions which don't submit an array
5309 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, $value, $dataType)) != FALSE) {
5311 return $queryString;
5314 // This is the here-be-dragons zone. We have no other hopes left for an array so lets assume it 'should' be array('IN' => array(2,5))
5315 // but we got only array(2,5) from the form.
5316 // We could get away with keeping this in 4.6 if we make it such that it throws an enotice in 4.7 so
5317 // people have to de-slopify it.
5318 if (!empty($value[0])) {
5319 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReport;
5320 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => $value), $dataType)) != FALSE) {
5321 return $queryString;
5325 $value = CRM_Utils_Type
::escape($value, $dataType);
5326 // if we don't have a dataType we should assume
5327 if ($dataType == 'String' ||
$dataType == 'Text') {
5328 $value = "'" . strtolower($value) . "'";
5330 return "$clause $value";
5335 * @param bool $reset
5339 public function openedSearchPanes($reset = FALSE) {
5340 if (!$reset ||
empty($this->_whereTables
)) {
5341 return self
::$_openedPanes;
5344 // pane name to table mapper
5345 $panesMapper = array(
5346 ts('Contributions') => 'civicrm_contribution',
5347 ts('Memberships') => 'civicrm_membership',
5348 ts('Events') => 'civicrm_participant',
5349 ts('Relationships') => 'civicrm_relationship',
5350 ts('Activities') => 'civicrm_activity',
5351 ts('Pledges') => 'civicrm_pledge',
5352 ts('Cases') => 'civicrm_case',
5353 ts('Grants') => 'civicrm_grant',
5354 ts('Address Fields') => 'civicrm_address',
5355 ts('Notes') => 'civicrm_note',
5356 ts('Change Log') => 'civicrm_log',
5357 ts('Mailings') => 'civicrm_mailing_event_queue',
5359 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5361 foreach (array_keys($this->_whereTables
) as $table) {
5362 if ($panName = array_search($table, $panesMapper)) {
5363 self
::$_openedPanes[$panName] = TRUE;
5367 return self
::$_openedPanes;
5373 public function setOperator($operator) {
5374 $validOperators = array('AND', 'OR');
5375 if (!in_array($operator, $validOperators)) {
5378 $this->_operator
= $operator;
5384 public function getOperator() {
5385 return $this->_operator
;
5393 public function filterRelatedContacts(&$from, &$where, &$having) {
5394 static $_rTypeProcessed = NULL;
5395 static $_rTypeFrom = NULL;
5396 static $_rTypeWhere = NULL;
5398 if (!$_rTypeProcessed) {
5399 $_rTypeProcessed = TRUE;
5401 // create temp table with contact ids
5402 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5403 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5404 CRM_Core_DAO
::executeQuery($sql);
5407 REPLACE INTO $tableName ( contact_id )
5413 CRM_Core_DAO
::executeQuery($sql);
5415 $qillMessage = ts('Contacts with a Relationship Type of: ');
5416 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5418 if (is_numeric($this->_displayRelationshipType
)) {
5419 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5421 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5422 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5425 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5426 AND displayRelType.is_active = 1
5430 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5431 if ($dirOne == 'a') {
5432 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5434 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5435 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5439 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5441 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5442 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5446 WHERE displayRelType.relationship_type_id = $relType
5447 AND displayRelType.is_active = 1
5450 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5453 if (!empty($this->_permissionWhereClause
)) {
5454 $_rTypeWhere .= "AND $this->_permissionWhereClause";
5457 if (strpos($from, $_rTypeFrom) === FALSE) {
5458 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5459 // this happens when we have an event_type in the quert (CRM-7969)
5460 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5461 $from .= $_rTypeFrom;
5462 $where = $_rTypeWhere;
5473 public static function caseImportant($op) {
5475 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5479 * @param $returnProperties
5484 public static function componentPresent(&$returnProperties, $prefix) {
5485 foreach ($returnProperties as $name => $dontCare) {
5486 if (substr($name, 0, strlen($prefix)) == $prefix) {
5494 * Builds the necessary structures for all fields that are similar to option value lookups.
5496 * @param string $name
5497 * the name of the field.
5499 * the sql operator, this function should handle ALL SQL operators.
5500 * @param string $value
5501 * depends on the operator and who's calling the query builder.
5502 * @param int $grouping
5503 * the index where to place the where clause.
5504 * @param $selectValues
5505 * The key value pairs for this element. This allows us to use this function for things besides option-value pairs.
5506 * @param array $field
5507 * an array that contains various properties of the field identified by $name.
5508 * @param string $label
5509 * The label for this field element.
5510 * @param string $dataType
5511 * The data type for this element.
5512 * @param bool $useIDsOnly
5515 * adds the where clause and qill to the query object
5517 public function optionValueQuery(
5525 $dataType = 'String',
5529 if (!empty($selectValues) && !is_array($value) && !empty($selectValues[$value])) {
5530 $qill = $selectValues[$value];
5536 $pseudoFields = array(
5543 'communication_style_id',
5546 if (is_numeric($value)) {
5547 $qill = $selectValues[(int ) $value];
5549 elseif ($op == 'IN' ||
$op == 'NOT IN') {
5550 if (is_array($value)) {
5552 $newValues = array();
5553 foreach ($value as $k => $v) {
5554 $intVals[$k] = (int) $k;
5555 $newValues[] = $selectValues[(int) $k];
5558 $value = (in_array($name, $pseudoFields)) ?
$intVals : $newValues;
5559 $qill = implode(', ', $newValues);
5562 elseif (!array_key_exists($value, $selectValues)) {
5563 // its a string, lets get the int value
5564 $value = array_search($value, $selectValues);
5567 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5568 if ($tableName == 'civicrm_contact') {
5569 $wc = "contact_a.$fieldName";
5572 $wc = "$tableName.id";
5576 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5579 if (in_array($name, $pseudoFields)) {
5580 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5581 $wc = "contact_a.{$name}_id";
5583 $dataType = 'Positive';
5584 $value = (!$value) ?
0 : $value;
5587 $this->_qill
[$grouping][] = $label . " $op '$qill'";
5588 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' ||
$op == 'RLIKE')) ?
'=' : $op;
5589 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5593 * Check and explode a user defined numeric string into an array
5594 * this was the protocol used by search builder in the old old days before we had
5595 * super nice js widgets to do the hard work
5597 * @param string $string
5598 * @param string $dataType
5599 * The dataType we should check for the values, default integer.
5601 * @return bool|array
5602 * false if string does not match the pattern
5603 * array of numeric values if string does match the pattern
5605 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5606 $string = trim($string);
5607 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5611 $string = substr($string, 1, -1);
5612 $values = explode(',', $string);
5613 if (empty($values)) {
5617 $returnValues = array();
5618 foreach ($values as $v) {
5619 if ($dataType == 'Integer' && !is_numeric($v)) {
5622 elseif ($dataType == 'String' && !is_string($v)) {
5625 $returnValues[] = trim($v);
5628 if (empty($returnValues)) {
5632 return $returnValues;
5636 * Convert the pseudo constants id's to their names
5638 * @param CRM_Core_DAO $dao
5639 * @param bool $return
5641 * @return array|NULL
5643 public function convertToPseudoNames(&$dao, $return = FALSE) {
5644 if (empty($this->_pseudoConstantsSelect
)) {
5648 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5649 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5653 if (property_exists($dao, $value['idCol'])) {
5654 $val = $dao->$value['idCol'];
5656 if (CRM_Utils_System
::isNull($val)) {
5659 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5661 $idColumn = "{$key}_id";
5662 $dao->$idColumn = $val;
5664 if ($key == 'state_province_name') {
5665 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5668 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5671 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5672 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5674 // FIX ME: we should potentially move this to component Query and write a wrapper function that
5675 // handles pseudoconstant fixes for all component
5676 elseif (in_array($value['pseudoField'], array('participant_status', 'participant_role'))) {
5677 $pseudoOptions = $viewValues = array();
5678 $pseudoOptions = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', $value['idCol']);
5679 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val) as $k => $v) {
5680 $viewValues[] = $pseudoOptions[$v];
5682 $dao->$key = implode(', ', $viewValues);
5685 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5686 $dao->$key = $labels[$val];
5689 // return converted values in array format
5691 if (strpos($key, '-') !== FALSE) {
5692 $keyVal = explode('-', $key);
5693 $current = &$values;
5694 $lastElement = array_pop($keyVal);
5695 foreach ($keyVal as $v) {
5696 if (!array_key_exists($v, $current)) {
5697 $current[$v] = array();
5699 $current = &$current[$v];
5701 $current[$lastElement] = $dao->$key;
5704 $values[$key] = $dao->$key;
5713 * Include pseudo fields LEFT JOIN.
5714 * @param string|array $sort can be a object or string
5716 * @return array|NULL
5718 public function includePseudoFieldsJoin($sort) {
5719 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5722 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5725 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5726 if (!empty($value['table'])) {
5727 $regex = "/({$value['table']}\.|{$name})/";
5728 if (preg_match($regex, $sort)) {
5729 $this->_elemnt
[$value['element']] = 1;
5730 $this->_select
[$value['element']] = $value['select'];
5731 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5732 $present[$value['table']] = $value['join'];
5736 $presentSimpleFrom = $present;
5738 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5739 array_key_exists('civicrm_country', $presentSimpleFrom)
5741 unset($presentSimpleFrom['civicrm_country']);
5743 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5744 array_key_exists('civicrm_country', $present)
5746 unset($present['civicrm_country']);
5749 $presentClause = $presentSimpleFromClause = NULL;
5750 if (!empty($present)) {
5751 $presentClause = implode(' ', $present);
5753 if (!empty($presentSimpleFrom)) {
5754 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5757 $this->_fromClause
= $this->_fromClause
. $presentClause;
5758 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5760 return array($presentClause, $presentSimpleFromClause);
5764 * Build qill for field.
5766 * Qill refers to the query detail visible on the UI.
5770 * @param $fieldValue
5772 * @param array $pseduoExtraParam
5776 public static function buildQillForFieldValue($daoName = NULL, $fieldName, $fieldValue, $op, $pseduoExtraParam = array()) {
5777 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
5779 if ($fieldName == 'activity_type_id') {
5780 $pseduoOptions = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
5782 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
5783 $pseduoOptions = CRM_Event_BAO_Event
::getEvents(0, $fieldValue, TRUE, TRUE, TRUE);
5785 elseif ($fieldName == 'contribution_product_id') {
5786 $pseduoOptions = CRM_Contribute_PseudoConstant
::products();
5788 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
5789 $pseduoOptions = CRM_Core_PseudoConstant
::group();
5792 $pseduoOptions = CRM_Core_PseudoConstant
::get($daoName, $fieldName, $pseduoExtraParam = array());
5795 //API usually have fieldValue format as array(operator => array(values)),
5796 //so we need to separate operator out of fieldValue param
5797 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5798 $op = key($fieldValue);
5799 $fieldValue = $fieldValue[$op];
5802 if (is_array($fieldValue)) {
5803 $qillString = array();
5804 if (!empty($pseduoOptions)) {
5805 foreach ((array) $fieldValue as $val) {
5806 $qillString[] = CRM_Utils_Array
::value($val, $pseduoOptions, $val);
5808 $fieldValue = implode(', ', $qillString);
5811 $fieldValue = implode(', ', $fieldValue);
5814 elseif (!empty($pseduoOptions) && array_key_exists($fieldValue, $pseduoOptions)) {
5815 $fieldValue = $pseduoOptions[$fieldValue];
5818 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), $fieldValue);