3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 * This class is a heart of 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
66 static $_defaultReturnProperties = NULL;
69 * the default set of hier return properties
74 static $_defaultHierReturnProperties;
77 * the set of input params
89 * the set of output params
93 public $_returnProperties;
103 * the name of the elements that are in the select clause
104 * used to extract the values
111 * the tables involved in the query
118 * the table involved in the where clause
122 public $_whereTables;
137 public $_whereClause;
140 * additional permission Where Clause
145 public $_permissionWhereClause;
156 * additional permission from clause
161 public $_permissionFromClause;
164 * the from clause for the simple select and alphabetical
169 public $_simpleFromClause;
180 * The english language version of the query
187 * All the fields that could potentially be involved in
195 * The cache to translate the option values into labels
202 * are we in search mode
206 public $_search = TRUE;
209 * should we skip permission checking
213 public $_skipPermission = FALSE;
216 * should we skip adding of delete clause
220 public $_skipDeleteClause = FALSE;
223 * are we in strict mode (use equality over LIKE)
227 public $_strict = FALSE;
230 * What operator to use to group the clauses
234 public $_operator = 'AND';
239 * Should we only search on primary location
243 public $_primaryLocation = TRUE;
246 * are contact ids part of the query
250 public $_includeContactIds = FALSE;
253 * Should we use the smart group cache
257 public $_smartGroupCache = TRUE;
260 * Should we display contacts with a specific relationship type
264 public $_displayRelationshipType = NULL;
267 * reference to the query object for custom values
271 public $_customQuery;
274 * should we enable the distinct clause, used if we are including
275 * more than one group
279 public $_useDistinct = FALSE;
282 * Should we just display one contact record
284 public $_useGroupBy = FALSE;
287 * the relationship type direction
300 static $_activityRole;
303 * Consider the component activity type
304 * during activity search.
309 static $_considerCompActivities;
312 * Consider with contact activities only,
313 * during activity search.
318 static $_withContactActivitiesOnly;
321 * use distinct component clause for component searches
325 public $_distinctComponentClause;
327 public $_rowCountClause;
330 * use groupBy component clause for component searches
334 public $_groupByComponentClause;
337 * Track open panes, useful in advance search
342 public static $_openedPanes = array();
345 * For search builder - which custom fields are location-dependent
348 public $_locationSpecificCustomFields = array();
351 * The tables which have a dependency on location and/or address
356 static $_dependencies = array(
357 'civicrm_state_province' => 1,
358 'civicrm_country' => 1,
359 'civicrm_county' => 1,
360 'civicrm_address' => 1,
361 'civicrm_location_type' => 1,
365 * List of location specific fields
367 static $_locationSpecificFields = array(
372 'supplemental_address_1',
373 'supplemental_address_2',
376 'postal_code_suffix',
389 * Remember if we handle either end of a number or date range
390 * so we can skip the other
392 protected $_rangeCache = array();
394 * Set to true when $this->relationship is run to avoid adding twice
397 protected $_relationshipValuesAdded = FALSE;
400 * Set to the name of the temp table if one has been created
403 static $_relationshipTempTable = NULL;
405 public $_pseudoConstantsSelect = array();
408 * class constructor which also does all the work
410 * @param array $params
411 * @param array $returnProperties
412 * @param array $fields
413 * @param boolean $includeContactIds
414 * @param boolean $strict
415 * @param bool|int $mode - mode the search is operating on
417 * @param bool $skipPermission
418 * @param bool $searchDescendentGroups
419 * @param bool $smartGroupCache
420 * @param null $displayRelationshipType
421 * @param string $operator
423 * @return \CRM_Contact_BAO_Query
426 function __construct(
427 $params = NULL, $returnProperties = NULL, $fields = NULL,
428 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
429 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
430 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
433 $this->_params
= &$params;
434 if ($this->_params
== NULL) {
435 $this->_params
= array();
438 if (empty($returnProperties)) {
439 $this->_returnProperties
= self
::defaultReturnProperties($mode);
442 $this->_returnProperties
= &$returnProperties;
445 $this->_includeContactIds
= $includeContactIds;
446 $this->_strict
= $strict;
447 $this->_mode
= $mode;
448 $this->_skipPermission
= $skipPermission;
449 $this->_smartGroupCache
= $smartGroupCache;
450 $this->_displayRelationshipType
= $displayRelationshipType;
451 $this->setOperator($operator);
454 $this->_fields
= &$fields;
455 $this->_search
= FALSE;
456 $this->_skipPermission
= TRUE;
459 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE);
461 $fields = CRM_Core_Component
::getQueryFields();
462 unset($fields['note']);
463 $this->_fields
= array_merge($this->_fields
, $fields);
465 // add activity fields
466 $fields = CRM_Activity_BAO_Activity
::exportableFields();
467 $this->_fields
= array_merge($this->_fields
, $fields);
469 // add any fields provided by hook implementers
470 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
471 $this->_fields
= array_merge($this->_fields
, $extFields);
474 // basically do all the work once, and then reuse it
479 * function which actually does all the work for the constructor
484 function initialize() {
485 $this->_select
= array();
486 $this->_element
= array();
487 $this->_tables
= array();
488 $this->_whereTables
= array();
489 $this->_where
= array();
490 $this->_qill
= array();
491 $this->_options
= array();
492 $this->_cfIDs
= array();
493 $this->_paramLookup
= array();
494 $this->_having
= array();
496 $this->_customQuery
= NULL;
498 // reset cached static variables - CRM-5803
499 self
::$_activityRole = NULL;
500 self
::$_considerCompActivities = NULL;
501 self
::$_withContactActivitiesOnly = NULL;
503 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
504 $this->_element
['contact_id'] = 1;
505 $this->_tables
['civicrm_contact'] = 1;
507 if (!empty($this->_params
)) {
508 $this->buildParamsLookup();
511 $this->_whereTables
= $this->_tables
;
513 $this->selectClause();
514 $this->_whereClause
= $this->whereClause();
516 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
517 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
519 $this->openedSearchPanes(TRUE);
522 function buildParamsLookup() {
523 // first fix and handle contact deletion nicely
524 // this code is primarily for search builder use case
525 // where different clauses can specify if they want deleted
528 $trashParamExists = FALSE;
529 $paramByGroup = array();
530 foreach ( $this->_params
as $k => $param ) {
531 if (!empty($param[0]) && $param[0] == 'contact_is_deleted' ) {
532 $trashParamExists = TRUE;
534 if (!empty($param[3])) {
535 $paramByGroup[$param[3]][$k] = $param;
539 if ( $trashParamExists ) {
540 $this->_skipDeleteClause
= TRUE;
542 //cycle through group sets and explicitly add trash param if not set
543 foreach ( $paramByGroup as $setID => $set ) {
545 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params
) &&
546 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params
) ) {
547 $this->_params
[] = array(
548 'contact_is_deleted',
558 foreach ($this->_params
as $value) {
559 if (empty($value[0])) {
562 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
564 if (!array_key_exists($cfID, $this->_cfIDs
)) {
565 $this->_cfIDs
[$cfID] = array();
567 // Set wildcard value based on "and/or" selection
568 foreach ($this->_params
as $key => $param) {
569 if ($param[0] == $value[0] . '_operator') {
570 $value[4] = $param[2] == 'or';
574 $this->_cfIDs
[$cfID][] = $value;
577 if (!array_key_exists($value[0], $this->_paramLookup
)) {
578 $this->_paramLookup
[$value[0]] = array();
580 $this->_paramLookup
[$value[0]][] = $value;
585 * Some composite fields do not appear in the fields array
586 * hack to make them part of the query
591 function addSpecialFields() {
592 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
593 foreach ($special as $name) {
594 if (!empty($this->_returnProperties
[$name])) {
595 $this->_select
[$name] = "contact_a.{$name} as $name";
596 $this->_element
[$name] = 1;
602 * Given a list of conditions in params and a list of desired
603 * return Properties generate the required select and from
604 * clauses. Note that since the where clause introduces new
605 * tables, the initial attempt also retrieves all variables used
611 function selectClause() {
613 $this->addSpecialFields();
615 foreach ($this->_fields
as $name => $field) {
616 // skip component fields
617 // there are done by the alter query below
618 // and need not be done on every field
620 (substr($name, 0, 12) == 'participant_') ||
621 (substr($name, 0, 7) == 'pledge_') ||
622 (substr($name, 0, 5) == 'case_')
627 // redirect to activity select clause
629 (substr($name, 0, 9) == 'activity_') ||
630 ($name == 'parent_id')
632 CRM_Activity_BAO_Query
::select($this);
636 // if this is a hierarchical name, we ignore it
637 $names = explode('-', $name);
638 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
642 // make an exception for special cases, to add the field in select clause
643 $makeException = FALSE;
645 //special handling for groups/tags
646 if (in_array($name, array('groups', 'tags', 'notes'))
647 && isset($this->_returnProperties
[substr($name, 0, -1)])
649 $makeException = TRUE;
652 // since note has 3 different options we need special handling
653 // note / note_subject / note_body
654 if ($name == 'notes') {
655 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
656 if (isset($this->_returnProperties
[$noteField])) {
657 $makeException = TRUE;
663 if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id', 'communication_style_id'))) {
664 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
665 $makeException = TRUE;
669 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
670 if (!empty($this->_paramLookup
[$name]) ||
!empty($this->_returnProperties
[$name]) ||
674 // add to cfIDs array if not present
675 if (!array_key_exists($cfID, $this->_cfIDs
)) {
676 $this->_cfIDs
[$cfID] = array();
679 elseif (isset($field['where'])) {
680 list($tableName, $fieldName) = explode('.', $field['where'], 2);
681 if (isset($tableName)) {
682 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
683 $this->_tables
['civicrm_address'] = 1;
684 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
685 $this->_element
['address_id'] = 1;
688 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
689 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
691 if ($tableName == 'im_provider') {
692 CRM_Core_OptionValue
::select($this);
695 if (in_array($tableName,
696 array('email_greeting', 'postal_greeting', 'addressee'))) {
697 $this->_element
["{$name}_id"] = 1;
698 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
699 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
700 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
701 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
703 if ($tableName == 'email_greeting') {
704 $this->_pseudoConstantsSelect
[$name]['join'] =
705 " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
706 $this->_pseudoConstantsSelect
[$name]['join'] .=
707 " 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 ) ";
709 elseif ($tableName == 'postal_greeting') {
710 $this->_pseudoConstantsSelect
[$name]['join'] =
711 " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
712 $this->_pseudoConstantsSelect
[$name]['join'] .=
713 " 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 ) ";
715 elseif ($tableName == 'addressee') {
716 $this->_pseudoConstantsSelect
[$name]['join'] =
717 " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
718 $this->_pseudoConstantsSelect
[$name]['join'] .=
719 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
721 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
724 $greetField = "{$name}_display";
725 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
726 $this->_element
[$greetField] = 1;
728 $greetField = "{$name}_custom";
729 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
730 $this->_element
[$greetField] = 1;
734 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
735 $this->_tables
[$tableName] = 1;
738 // also get the id of the tableName
739 $tName = substr($tableName, 8);
740 if (in_array($tName, array('country', 'state_province', 'county'))) {
741 if ($tName == 'state_province') {
742 $this->_pseudoConstantsSelect
['state_province_name'] =
743 array('pseudoField' => "{$tName}", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address',
744 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
746 $this->_pseudoConstantsSelect
[$tName] =
747 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id",
748 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
751 $this->_pseudoConstantsSelect
[$name] =
752 array('pseudoField' => "{$tName}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address',
753 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
756 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
757 $this->_element
["{$tName}_id"] = 1;
759 elseif ($tName != 'contact') {
760 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
761 $this->_element
["{$tName}_id"] = 1;
764 //special case for phone
765 if ($name == 'phone') {
766 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
767 $this->_element
['phone_type_id'] = 1;
770 // if IM then select provider_id also
771 // to get "IM Service Provider" in a file to be exported, CRM-3140
773 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
774 $this->_element
['provider_id'] = 1;
777 if ($tName == 'contact') {
778 // special case, when current employer is set for Individual contact
779 if ($fieldName == 'organization_name') {
780 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
782 elseif ($fieldName != 'id') {
783 if ($fieldName == 'prefix_id') {
784 $this->_pseudoConstantsSelect
['individual_prefix'] = array('pseudoField' => 'prefix_id', 'idCol' => "prefix_id", 'bao' => 'CRM_Contact_BAO_Contact');
786 if ($fieldName == 'suffix_id') {
787 $this->_pseudoConstantsSelect
['individual_suffix'] = array('pseudoField' => 'suffix_id', 'idCol' => "suffix_id", 'bao' => 'CRM_Contact_BAO_Contact');
789 if ($fieldName == 'gender_id') {
790 $this->_pseudoConstantsSelect
['gender'] = array('pseudoField' => 'gender_id', 'idCol' => "gender_id", 'bao' => 'CRM_Contact_BAO_Contact');
792 if ($name == 'communication_style_id') {
793 $this->_pseudoConstantsSelect
['communication_style'] = array('pseudoField' => 'communication_style_id', 'idCol' => "communication_style_id", 'bao' => 'CRM_Contact_BAO_Contact');
795 $this->_select
[$name] = "contact_a.{$fieldName} as `$name`";
798 elseif (in_array($tName, array('country', 'county'))) {
799 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
800 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
802 elseif ($tName == 'state_province') {
803 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
804 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
807 $this->_select
[$name] = "{$field['where']} as `$name`";
809 if (!in_array($tName, array('state_province', 'country', 'county'))) {
810 $this->_element
[$name] = 1;
815 elseif ($name === 'tags') {
816 $this->_useGroupBy
= TRUE;
817 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
818 $this->_element
[$name] = 1;
819 $this->_tables
['civicrm_tag'] = 1;
820 $this->_tables
['civicrm_entity_tag'] = 1;
822 elseif ($name === 'groups') {
823 $this->_useGroupBy
= TRUE;
824 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
825 $this->_element
[$name] = 1;
826 $this->_tables
['civicrm_group'] = 1;
828 elseif ($name === 'notes') {
829 // if note field is subject then return subject else body of the note
830 $noteColumn = 'note';
831 if (isset($noteField) && $noteField == 'note_subject') {
832 $noteColumn = 'subject';
835 $this->_useGroupBy
= TRUE;
836 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
837 $this->_element
[$name] = 1;
838 $this->_tables
['civicrm_note'] = 1;
840 elseif ($name === 'current_employer') {
841 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
842 $this->_element
[$name] = 1;
846 if ($cfID && !empty($field['is_search_range'])) {
847 // this is a custom field with range search enabled, so we better check for two/from values
848 if (!empty($this->_paramLookup
[$name . '_from'])) {
849 if (!array_key_exists($cfID, $this->_cfIDs
)) {
850 $this->_cfIDs
[$cfID] = array();
852 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
853 // search in the cdID array for the same grouping
855 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
856 if ($c[3] == $p[3]) {
857 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
862 $p[2] = array('from' => $p[2]);
863 $this->_cfIDs
[$cfID][] = $p;
867 if (!empty($this->_paramLookup
[$name . '_to'])) {
868 if (!array_key_exists($cfID, $this->_cfIDs
)) {
869 $this->_cfIDs
[$cfID] = array();
871 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
872 // search in the cdID array for the same grouping
874 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
875 if ($c[4] == $p[4]) {
876 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
881 $p[2] = array('to' => $p[2]);
882 $this->_cfIDs
[$cfID][] = $p;
889 // add location as hierarchical elements
890 $this->addHierarchicalElements();
892 // add multiple field like website
893 $this->addMultipleElements();
896 CRM_Core_Component
::alterQuery($this, 'select');
898 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
900 if (!empty($this->_cfIDs
)) {
901 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
902 $this->_customQuery
->query();
903 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
904 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
905 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
906 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
907 $this->_options
= $this->_customQuery
->_options
;
912 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
918 function addHierarchicalElements() {
919 if (empty($this->_returnProperties
['location'])) {
922 if (!is_array($this->_returnProperties
['location'])) {
926 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
927 $processed = array();
930 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
931 $addressCustomFieldIds = array();
933 foreach ($this->_returnProperties
['location'] as $name => $elements) {
934 $lCond = self
::getPrimaryCondition($name);
937 $locationTypeId = array_search($name, $locationTypes);
938 if ($locationTypeId === FALSE) {
941 $lCond = "location_type_id = $locationTypeId";
942 $this->_useDistinct
= TRUE;
944 //commented for CRM-3256
945 $this->_useGroupBy
= TRUE;
948 $name = str_replace(' ', '_', $name);
950 $tName = "$name-location_type";
951 $ltName = "`$name-location_type`";
952 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
953 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
954 $this->_element
["{$tName}_id"] = 1;
955 $this->_element
["{$tName}"] = 1;
957 $locationTypeName = $tName;
958 $locationTypeJoin = array();
962 foreach ($elements as $elementFullName => $dontCare) {
964 $elementName = $elementCmpName = $elementFullName;
966 if (substr($elementCmpName, 0, 5) == 'phone') {
967 $elementCmpName = 'phone';
970 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
971 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
972 $addressCustomFieldIds[$cfID][$name] = 1;
975 //add address table only once
976 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
978 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
980 $tName = "$name-address";
981 $aName = "`$name-address`";
982 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
983 $this->_element
["{$tName}_id"] = 1;
984 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
985 $this->_tables
[$tName] = $addressJoin;
986 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
987 $processed[$aName] = 1;
991 $cond = $elementType = '';
992 if (strpos($elementName, '-') !== FALSE) {
993 // this is either phone, email or IM
994 list($elementName, $elementType) = explode('-', $elementName);
997 if (($elementName != 'phone') && ($elementName != 'im')) {
998 $cond = self
::getPrimaryCondition($elementType);
1000 // CRM-13011 : If location type is primary, do not restrict search to the phone
1001 // type id - we want the primary phone, regardless of what type it is.
1002 // Otherwise, restrict to the specified phone type for the given field.
1003 if ((!$cond) && ($elementName == 'phone') && $elements['location_type'] != 'Primary') {
1004 $cond = "phone_type_id = '$elementType'";
1006 elseif ((!$cond) && ($elementName == 'im')) {
1007 // IM service provider id, CRM-3140
1008 $cond = "provider_id = '$elementType'";
1010 $elementType = '-' . $elementType;
1013 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
1015 // hack for profile, add location id
1018 // fix for CRM-882( to handle phone types )
1019 !is_numeric($elementType)
1021 if (is_numeric($name)) {
1022 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1025 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1028 elseif (is_numeric($name)) {
1029 //this for phone type to work
1030 if (in_array($elementName, array('phone', 'phone_ext'))) {
1031 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1034 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1038 //this is for phone type to work for profile edit
1039 if (in_array($elementName, array('phone', 'phone_ext'))) {
1040 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1043 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1048 // Check if there is a value, if so also add to where Clause
1050 if ($this->_params
) {
1052 if (isset($locationTypeId)) {
1053 $nm .= "-$locationTypeId";
1055 if (!is_numeric($elementType)) {
1056 $nm .= "$elementType";
1059 foreach ($this->_params
as $id => $values) {
1060 if ((is_array($values) && $values[0] == $nm) ||
1061 (in_array($elementName, array('phone', 'im'))
1062 && (strpos($values[0], $nm) !== FALSE)
1072 if ($field && isset($field['where'])) {
1073 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1074 $pf = substr($tableName, 8);
1075 $tName = $name . '-' . $pf . $elementType;
1076 if (isset($tableName)) {
1077 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1078 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1081 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1084 $this->_element
["{$tName}_id"] = 1;
1085 if (substr($tName, -15) == '-state_province') {
1086 // FIXME: hack to fix CRM-1900
1087 $a = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1091 if (substr_count($a, 'state_province_name') > 0) {
1092 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1093 array('pseudoField' => "{$pf}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1094 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1097 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1098 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id");
1099 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1103 if (substr($elementFullName, 0, 2) == 'im') {
1104 $provider = "{$name}-{$elementFullName}-provider_id";
1105 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1106 $this->_element
[$provider] = 1;
1108 if ($pf == 'country' ||
$pf == 'county') {
1109 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array('pseudoField' => "{$pf}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1110 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1113 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1117 if (in_array($pf, array('state_province', 'country', 'county'))) {
1118 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1121 $this->_element
["{$name}-{$elementFullName}"] = 1;
1124 if (empty($processed["`$tName`"])) {
1125 $processed["`$tName`"] = 1;
1126 $newName = $tableName . '_' . $index;
1127 switch ($tableName) {
1128 case 'civicrm_phone':
1129 case 'civicrm_email':
1131 case 'civicrm_openid':
1133 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id AND `$tName`.$lCond";
1134 // this special case to add phone type
1136 $phoneTypeCondition = " AND `$tName`.$cond ";
1137 //gross hack to pickup corrupted data also, CRM-7603
1138 if (strpos($cond, 'phone_type_id') !== FALSE) {
1139 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1141 $this->_tables
[$tName] .= $phoneTypeCondition;
1144 //build locationType join
1145 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1148 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1152 case 'civicrm_state_province':
1153 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1154 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1155 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1157 $this->_whereTables
["{$name}-address"] = $addressJoin;
1161 case 'civicrm_country':
1162 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1163 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1164 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1166 $this->_whereTables
["{$name}-address"] = $addressJoin;
1170 case 'civicrm_county':
1171 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1172 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1173 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1175 $this->_whereTables
["{$name}-address"] = $addressJoin;
1181 $this->_whereTables
["{$name}-address"] = $addressJoin;
1190 // add location type join
1191 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1192 $this->_tables
[$locationTypeName] = $ltypeJoin;
1194 // table should be present in $this->_whereTables,
1195 // to add its condition in location type join, CRM-3939.
1196 if ($addWhereCount) {
1197 $locClause = array();
1198 foreach ($this->_whereTables
as $tableName => $clause) {
1199 if (!empty($locationTypeJoin[$tableName])) {
1200 $locClause[] = $locationTypeJoin[$tableName];
1204 if (!empty($locClause)) {
1205 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1210 if (!empty($addressCustomFieldIds)) {
1211 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1212 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1213 foreach ($locTypeName as $name => $dnc) {
1214 $this->_locationSpecificCustomFields
[$cfID] = array($name, array_search($name, $locationTypes));
1215 $fieldName = "$name-custom_{$cfID}";
1216 $tName = "$name-address-custom-{$cfID}";
1217 $aName = "`$name-address-custom-{$cfID}`";
1218 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1219 $this->_element
["{$tName}_id"] = 1;
1220 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1221 $this->_element
[$fieldName] = 1;
1222 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1229 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
1235 function addMultipleElements() {
1236 if (empty($this->_returnProperties
['website'])) {
1239 if (!is_array($this->_returnProperties
['website'])) {
1243 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1244 foreach ($elements as $elementFullName => $dontCare) {
1245 $tName = "website-{$key}-{$elementFullName}";
1246 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1247 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1248 $this->_element
["{$tName}_id"] = 1;
1249 $this->_element
["{$tName}"] = 1;
1251 $type = "website-{$key}-website_type_id";
1252 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1253 $this->_element
[$type] = 1;
1254 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1260 * generate the query based on what type of query we need
1262 * @param boolean $count
1263 * @param boolean $sortByChar
1264 * @param boolean $groupContacts
1265 * @param boolean $onlyDeleted
1267 * @return array sql query parts as an array
1270 function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1271 // build permission clause
1272 $this->generatePermissionClause($onlyDeleted, $count);
1275 if (isset($this->_rowCountClause
)) {
1276 $select = "SELECT {$this->_rowCountClause}";
1277 } else if (isset($this->_distinctComponentClause
)) {
1278 // we add distinct to get the right count for components
1279 // for the more complex result set, we use GROUP BY the same id
1281 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1284 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1286 $from = $this->_simpleFromClause
;
1287 if ($this->_useDistinct
) {
1288 $this->_useGroupBy
= TRUE;
1291 elseif ($sortByChar) {
1292 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1293 $from = $this->_simpleFromClause
;
1295 elseif ($groupContacts) {
1296 $select = 'SELECT contact_a.id as id';
1297 if ($this->_useDistinct
) {
1298 $this->_useGroupBy
= TRUE;
1300 $from = $this->_simpleFromClause
;
1303 if (!empty($this->_paramLookup
['group'])) {
1304 // make sure there is only one element
1305 // this is used when we are running under smog and need to know
1306 // how the contact was added (CRM-1203)
1307 if ((count($this->_paramLookup
['group']) == 1) &&
1308 (count($this->_paramLookup
['group'][0][2]) == 1)
1310 $groups = array_keys($this->_paramLookup
['group'][0][2]);
1311 $groupId = $groups[0];
1313 //check if group is saved search
1314 $group = new CRM_Contact_BAO_Group();
1315 $group->id
= $groupId;
1318 if (!isset($group->saved_search_id
)) {
1319 $tbName = "`civicrm_group_contact-{$groupId}`";
1320 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1321 $this->_element
['group_contact_id'] = 1;
1322 $this->_select
['status'] = "$tbName.status as status";
1323 $this->_element
['status'] = 1;
1326 $this->_useGroupBy
= TRUE;
1328 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1329 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1331 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1332 $this->_useDistinct
= FALSE;
1333 $this->_useGroupBy
= TRUE;
1337 $select = "SELECT ";
1338 if (isset($this->_distinctComponentClause
)) {
1339 $select .= "{$this->_distinctComponentClause}, ";
1341 $select .= implode(', ', $this->_select
);
1342 $from = $this->_fromClause
;
1346 if (!empty($this->_whereClause
)) {
1347 $where = "WHERE {$this->_whereClause}";
1350 if (!empty($this->_permissionWhereClause
)) {
1351 if (empty($where)) {
1352 $where = "WHERE $this->_permissionWhereClause";
1355 $where = "$where AND $this->_permissionWhereClause";
1360 if (!empty($this->_having
)) {
1361 foreach ($this->_having
as $havingSets) {
1362 foreach ($havingSets as $havingSet) {
1363 $havingValue[] = $havingSet;
1366 $having = ' HAVING ' . implode(' AND ', $havingValue);
1369 // if we are doing a transform, do it here
1370 // use the $from, $where and $having to get the contact ID
1371 if ($this->_displayRelationshipType
) {
1372 $this->filterRelatedContacts($from, $where, $having);
1375 return array($select, $from, $where, $having);
1384 function &getWhereValues($name, $grouping) {
1386 foreach ($this->_params
as $values) {
1387 if ($values[0] == $name && $values[3] == $grouping) {
1400 static function fixDateValues($relative, &$from, &$to) {
1402 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1407 * @param $formValues
1408 * @param int $wildcard
1409 * @param bool $useEquals
1413 static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE) {
1415 if (empty($formValues)) {
1419 foreach ($formValues as $id => $values) {
1420 if ($id == 'privacy') {
1421 if (is_array($formValues['privacy'])) {
1422 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1423 foreach ($formValues['privacy'] as $key => $value) {
1425 $params[] = array($key, $op, $value, 0, 0);
1430 elseif ($id == 'email_on_hold') {
1431 if ($formValues['email_on_hold']['on_hold']) {
1432 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1435 elseif (preg_match('/_date_relative$/', $id) ||
1436 $id == 'event_relative' ||
1437 $id == 'case_from_relative' ||
1438 $id == 'case_to_relative'
1440 if ($id == 'event_relative') {
1441 $fromRange = 'event_start_date_low';
1442 $toRange = 'event_end_date_high';
1444 else if ($id == 'case_from_relative') {
1445 $fromRange = 'case_from_start_date_low';
1446 $toRange = 'case_from_start_date_high';
1448 else if ($id == 'case_to_relative') {
1449 $fromRange = 'case_to_end_date_low';
1450 $toRange = 'case_to_end_date_high';
1453 $dateComponent = explode('_date_relative', $id);
1454 $fromRange = "{$dateComponent[0]}_date_low";
1455 $toRange = "{$dateComponent[0]}_date_high";
1458 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1459 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1464 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals);
1469 $params[] = $values;
1478 * @param int $wildcard
1479 * @param bool $useEquals
1481 * @return array|null
1483 static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE) {
1484 // skip a few search variables
1485 static $skipWhere = NULL;
1486 static $likeNames = NULL;
1489 if (CRM_Utils_System
::isNull($values)) {
1495 'task', 'radio_ts', 'uf_group_id',
1496 'component_mode', 'qfKey', 'operator',
1497 'display_relationship_type',
1501 if (in_array($id, $skipWhere) ||
1502 substr($id, 0, 4) == '_qf_' ||
1503 substr($id, 0, 7) == 'hidden_'
1509 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1512 // email comes in via advanced search
1513 // so use wildcard always
1514 if ($id == 'email') {
1518 if (!$useEquals && in_array($id, $likeNames)) {
1519 $result = array($id, 'LIKE', $values, 0, 1);
1521 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1522 $result = array($id, 'LIKE', $values, 0, 0);
1524 elseif ($id == 'group') {
1525 if (is_array($values)) {
1526 foreach ($values as $groupIds => $val) {
1528 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1529 if (strlen($matches[1]) > 0) {
1530 $values[$matches[1]] = 1;
1531 unset($values[$groupIds]);
1537 $groupIds = explode(',', $values);
1539 foreach ($groupIds as $groupId) {
1540 $values[$groupId] = 1;
1544 $result = array($id, 'IN', $values, 0, 0);
1546 elseif ($id == 'contact_tags' ||
$id == 'tag') {
1547 if (!is_array($values)) {
1548 $tagIds = explode(',', $values);
1550 foreach ($tagIds as $tagId) {
1551 $values[$tagId] = 1;
1554 $result = array($id, 'IN', $values, 0, 0);
1556 elseif ($id == 'contact_type') {
1557 $result = array($id, 'IN', $values, 0, $wildcard);
1560 $result = array($id, '=', $values, 0, $wildcard);
1569 function whereClauseSingle(&$values) {
1570 // do not process custom fields or prefixed contact ids or component params
1571 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1572 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1573 (substr($values[0], 0, 13) == 'contribution_') ||
1574 (substr($values[0], 0, 6) == 'event_') ||
1575 (substr($values[0], 0, 12) == 'participant_') ||
1576 (substr($values[0], 0, 7) == 'member_') ||
1577 (substr($values[0], 0, 6) == 'grant_') ||
1578 (substr($values[0], 0, 7) == 'pledge_') ||
1579 (substr($values[0], 0, 5) == 'case_') ||
1580 (substr($values[0], 0, 10) == 'financial_') ||
1581 (substr($values[0], 0, 11) == 'membership_')
1586 // skip for hook injected fields / params
1587 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1588 if (array_key_exists($values[0], $extFields)) {
1592 switch ($values[0]) {
1593 case 'deleted_contacts':
1594 $this->deletedContacts($values);
1597 case 'contact_type':
1598 $this->contactType($values);
1601 case 'contact_sub_type':
1602 $this->contactSubType($values);
1606 $this->group($values);
1610 // so we resolve this into a list of groups & proceed as if they had been
1612 list($name, $op, $value, $grouping, $wildcard) = $values;
1613 $values[0] = 'group';
1615 $this->_paramLookup
['group'][0][0] ='group';
1616 $this->_paramLookup
['group'][0][1] = 'IN';
1617 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1618 $this->group($values);
1621 // case tag comes from find contacts
1623 $this->tagSearch($values);
1627 case 'contact_tags':
1628 $this->tag($values);
1633 case 'note_subject':
1634 $this->notes($values);
1638 $this->ufUser($values);
1642 case 'display_name':
1643 $this->sortName($values);
1647 $this->email($values);
1650 case 'phone_numeric':
1651 $this->phone_numeric($values);
1654 case 'phone_phone_type_id':
1655 case 'phone_location_type_id':
1656 $this->phone_option_group($values);
1659 case 'street_address':
1660 $this->street_address($values);
1663 case 'street_number':
1664 $this->street_number($values);
1667 case 'sortByCharacter':
1668 $this->sortByCharacter($values);
1671 case 'location_type':
1672 $this->locationType($values);
1676 $this->county($values);
1679 case 'state_province':
1680 $this->stateProvince($values);
1684 $this->country($values, FALSE);
1688 case 'postal_code_low':
1689 case 'postal_code_high':
1690 $this->postalCode($values);
1693 case 'activity_date':
1694 case 'activity_date_low':
1695 case 'activity_date_high':
1696 case 'activity_role':
1697 case 'activity_status':
1698 case 'followup_parent_id':
1700 case 'activity_subject':
1701 case 'test_activities':
1702 case 'activity_type_id':
1703 case 'activity_type':
1704 case 'activity_survey_id':
1705 case 'activity_tags':
1706 case 'activity_taglist':
1707 case 'activity_test':
1708 case 'activity_campaign_id':
1709 case 'activity_engagement_level':
1711 case 'activity_result':
1712 case 'source_contact':
1713 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1716 case 'birth_date_low':
1717 case 'birth_date_high':
1718 case 'deceased_date_low':
1719 case 'deceased_date_high':
1720 $this->demographics($values);
1723 case 'log_date_low':
1724 case 'log_date_high':
1725 $this->modifiedDates($values);
1729 $this->changeLog($values);
1732 case 'do_not_phone':
1733 case 'do_not_email':
1736 case 'do_not_trade':
1738 $this->privacy($values);
1741 case 'privacy_options':
1742 $this->privacyOptions($values);
1745 case 'privacy_operator':
1746 case 'privacy_toggle':
1747 // these are handled by privacy options
1750 case 'preferred_communication_method':
1751 $this->preferredCommunication($values);
1754 case 'relation_type_id':
1755 case 'relation_start_date_high':
1756 case 'relation_start_date_low':
1757 case 'relation_end_date_high':
1758 case 'relation_end_date_low':
1759 case 'relation_target_name':
1760 case 'relation_status':
1761 case 'relation_date_low':
1762 case 'relation_date_high':
1763 $this->relationship($values);
1764 $this->_relationshipValuesAdded
= TRUE;
1767 case 'task_status_id':
1768 $this->task($values);
1772 // since this case is handled with the above
1775 case 'prox_distance':
1776 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1779 case 'prox_street_address':
1781 case 'prox_postal_code':
1782 case 'prox_state_province_id':
1783 case 'prox_country_id':
1784 // handled by the proximity_distance clause
1788 $this->restWhere($values);
1794 * Given a list of conditions in params generate the required
1800 function whereClause() {
1801 $this->_where
[0] = array();
1802 $this->_qill
[0] = array();
1804 $this->includeContactIds();
1805 if (!empty($this->_params
)) {
1806 foreach (array_keys($this->_params
) as $id) {
1807 if (empty($this->_params
[$id][0])) {
1810 // check for both id and contact_id
1811 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
1813 $this->_params
[$id][1] == 'IS NULL' ||
1814 $this->_params
[$id][1] == 'IS NOT NULL'
1816 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]}";
1818 elseif (is_array($this->_params
[$id][2])) {
1819 $idList = implode("','", $this->_params
[$id][2]);
1820 //why on earth do they put ' in the middle & not on the outside? We have to assume it's
1821 //to support 'something' so lets add them conditionally to support the api (which is a tested flow
1822 // so if you are looking to alter this check api test results
1823 if (strpos(trim($idList), "'") > 0) {
1824 $idList = "'" . $idList . "'";
1827 $this->_where
[0][] = "contact_a.id IN ({$idList})";
1830 $this->_where
[0][] = self
::buildClause("contact_a.id", "{$this->_params[$id][1]}", "{$this->_params[$id][2]}");
1834 $this->whereClauseSingle($this->_params
[$id]);
1838 CRM_Core_Component
::alterQuery($this, 'where');
1840 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
1843 if ($this->_customQuery
) {
1844 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1845 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1846 if (!empty($this->_customQuery
->_where
)) {
1847 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
1850 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
1854 $andClauses = array();
1857 if (!empty($this->_where
)) {
1858 foreach ($this->_where
as $grouping => $values) {
1859 if ($grouping > 0 && !empty($values)) {
1860 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1865 if (!empty($this->_where
[0])) {
1866 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
1868 if (!empty($clauses)) {
1869 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1872 if ($validClauses > 1) {
1873 $this->_useDistinct
= TRUE;
1877 return implode(' AND ', $andClauses);
1885 function restWhere(&$values) {
1886 $name = CRM_Utils_Array
::value(0, $values);
1887 $op = CRM_Utils_Array
::value(1, $values);
1888 $value = CRM_Utils_Array
::value(2, $values);
1889 $grouping = CRM_Utils_Array
::value(3, $values);
1890 $wildcard = CRM_Utils_Array
::value(4, $values);
1892 if (isset($grouping) && empty($this->_where
[$grouping])) {
1893 $this->_where
[$grouping] = array();
1896 $multipleFields = array('url');
1898 //check if the location type exits for fields
1900 $locType = explode('-', $name);
1902 if (!in_array($locType[0], $multipleFields)) {
1903 //add phone type if exists
1904 if (isset($locType[2]) && $locType[2]) {
1905 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
1909 $field = CRM_Utils_Array
::value($name, $this->_fields
);
1912 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
1921 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
1922 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1924 if (substr($name, 0, 14) === 'state_province') {
1925 if (isset($locType[1]) && is_numeric($locType[1])) {
1927 $aName = "{$locationType[$locType[1]]}-address";
1928 $where = "`$aName`.state_province_id";
1931 $where = "civicrm_address.state_province_id";
1934 $states = CRM_Core_PseudoConstant
::stateProvince();
1935 if (is_numeric($value)) {
1936 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1937 $value = $states[(int ) $value];
1940 $intVal = CRM_Utils_Array
::key($value, $states);
1941 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1944 $this->_qill
[$grouping][] = ts('State') . " $op '$value'";
1947 $this->_qill
[$grouping][] = ts('State') . " ($lType) $op '$value'";
1950 elseif (!empty($field['pseudoconstant'])) {
1951 $this->optionValueQuery(
1952 $name, $op, $value, $grouping,
1953 CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', $field['name']),
1959 if ($name == 'gender_id') {
1960 self
::$_openedPanes[ts('Demographics')] = TRUE;
1963 elseif (substr($name, 0, 7) === 'country') {
1964 if (isset($locType[1]) && is_numeric($locType[1])) {
1966 $aName = "{$locationType[$locType[1]]}-address";
1967 $where = "`$aName`.country_id";
1970 $where = "civicrm_address.country_id";
1973 $countries = CRM_Core_PseudoConstant
::country();
1974 if (is_numeric($value)) {
1975 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1976 $value = $countries[(int ) $value];
1979 $intVal = CRM_Utils_Array
::key($value, $countries);
1980 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1984 $this->_qill
[$grouping][] = ts('Country') . " $op '$value'";
1987 $this->_qill
[$grouping][] = ts('Country') . " ($lType) $op '$value'";
1990 elseif (substr($name, 0, 6) === 'county') {
1991 if (isset($locType[1]) && is_numeric($locType[1])) {
1993 $aName = "{$locationType[$locType[1]]}-address";
1994 $where = "`$aName`.county_id";
1997 $where = "civicrm_address.county_id";
2000 $counties = CRM_Core_PseudoConstant
::county();
2001 if (is_numeric($value)) {
2002 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2003 $value = $counties[(int ) $value];
2006 $intVal = CRM_Utils_Array
::key($value, $counties);
2007 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
2011 $this->_qill
[$grouping][] = ts('County') . " $op '$value'";
2014 $this->_qill
[$grouping][] = ts('County') . " ($lType) $op '$value'";
2017 elseif ($name === 'world_region') {
2018 $field['where'] = 'civicrm_worldregion.id';
2019 $this->optionValueQuery(
2020 $name, $op, $value, $grouping,
2021 CRM_Core_PseudoConstant
::worldRegion(),
2028 elseif ($name === 'birth_date') {
2029 $date = CRM_Utils_Date
::processDate($value);
2030 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
2033 $date = CRM_Utils_Date
::customFormat($date);
2034 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
2037 $this->_qill
[$grouping][] = "$field[title] $op";
2039 self
::$_openedPanes[ts('Demographics')] = TRUE;
2041 elseif ($name === 'deceased_date') {
2042 $date = CRM_Utils_Date
::processDate($value);
2043 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
2045 $date = CRM_Utils_Date
::customFormat($date);
2046 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
2049 $this->_qill
[$grouping][] = "$field[title] $op";
2051 self
::$_openedPanes[ts('Demographics')] = TRUE;
2053 elseif ($name === 'is_deceased') {
2054 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
2055 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2056 self
::$_openedPanes[ts('Demographics')] = TRUE;
2058 elseif ($name === 'contact_id') {
2059 if (is_int($value)) {
2060 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2061 $this->_qill
[$grouping][] = "$field[title] $op $value";
2064 elseif ($name === 'name') {
2065 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2067 $value = "%$value%";
2070 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2071 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2072 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2074 elseif ($name === 'current_employer') {
2075 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2077 $value = "%$value%";
2080 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
2081 $ceWhereClause = self
::buildClause($wc, $op,
2084 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2085 $this->_where
[$grouping][] = $ceWhereClause;
2086 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2088 elseif ($name === 'email_greeting') {
2089 $filterCondition = array('greeting_type' => 'email_greeting');
2090 $this->optionValueQuery(
2091 $name, $op, $value, $grouping,
2092 CRM_Core_PseudoConstant
::greeting($filterCondition),
2094 ts('Email Greeting')
2097 elseif ($name === 'postal_greeting') {
2098 $filterCondition = array('greeting_type' => 'postal_greeting');
2099 $this->optionValueQuery(
2100 $name, $op, $value, $grouping,
2101 CRM_Core_PseudoConstant
::greeting($filterCondition),
2103 ts('Postal Greeting')
2106 elseif ($name === 'addressee') {
2107 $filterCondition = array('greeting_type' => 'addressee');
2108 $this->optionValueQuery(
2109 $name, $op, $value, $grouping,
2110 CRM_Core_PseudoConstant
::greeting($filterCondition),
2115 elseif (substr($name, 0, 4) === 'url-') {
2116 $tName = 'civicrm_website';
2117 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2118 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2120 $value = "%$value%";
2124 $wc = 'civicrm_website.url';
2125 $this->_where
[$grouping][] = $d = self
::buildClause($wc, $op, $value);
2126 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2128 elseif ($name === 'contact_is_deleted') {
2129 $this->_where
[$grouping][] = self
::buildClause("contact_a.is_deleted", $op, $value);
2130 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2133 if (is_array($value)) {
2134 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2135 // for api style operators for functions that hit this point without worrying about regression
2136 // (the previous comments indicated the condition for hitting this point were unknown
2137 // per CRM-14743 we are adding modified_date & created_date operator support
2138 $operations = array_keys($value);
2139 foreach ($operations as $operator) {
2140 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2141 // we don't know when this might happen
2142 CRM_Core_Error
::fatal();
2145 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($name, $value, NULL);
2146 //since this is not currently being called by the form layer we can skip worrying about the 'qill' for now
2150 if (!empty($field['where'])) {
2152 $value = $strtolower($value);
2155 $value = "%$value%";
2159 if (isset($locType[1]) &&
2160 is_numeric($locType[1])
2164 //get the location name
2165 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2167 $where = "`$tName`.$fldName";
2169 $this->_where
[$grouping][] = self
::buildClause("LOWER($where)", $op, $value);
2170 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2171 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2172 $this->_qill
[$grouping][] = "$field[title] $op '$value'";
2175 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2176 if ($tableName == 'civicrm_contact') {
2177 $fieldName = "LOWER(contact_a.{$fieldName})";
2180 if ($op != 'IN' && !is_numeric($value)) {
2181 $fieldName = "LOWER({$field['where']})";
2184 $fieldName = "{$field['where']}";
2189 if (!empty($field['type'])) {
2190 $type = CRM_Utils_Type
::typeToString($field['type']);
2193 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2194 $this->_qill
[$grouping][] = "$field[title] $op $value";
2199 if ($setTables && isset($field['where'])) {
2200 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2201 if (isset($tableName)) {
2202 $this->_tables
[$tableName] = 1;
2203 $this->_whereTables
[$tableName] = 1;
2216 static function getLocationTableName(&$where, &$locType) {
2217 if (isset($locType[1]) && is_numeric($locType[1])) {
2218 list($tbName, $fldName) = explode(".", $where);
2220 //get the location name
2221 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2222 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2223 if (in_array($locType[0], $specialFields)) {
2224 //hack to fix / special handing for phone_ext
2225 if ($locType[0] == 'phone_ext') {
2226 $locType[0] = 'phone';
2228 if (isset($locType[2]) && $locType[2]) {
2229 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2232 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2235 elseif (in_array($locType[0],
2237 'address_name', 'street_address', 'supplemental_address_1', 'supplemental_address_2',
2238 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
2241 //fix for search by profile with address fields.
2242 $tName = "{$locationType[$locType[1]]}-address";
2244 elseif ($locType[0] == 'on_hold') {
2245 $tName = "{$locationType[$locType[1]]}-email";
2248 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2250 $tName = str_replace(' ', '_', $tName);
2251 return array($tName, $fldName);
2253 CRM_Core_Error
::fatal();
2257 * Given a result dao, extract the values and return that array
2259 * @param Object $dao
2261 * @return array values for this query
2263 function store($dao) {
2266 foreach ($this->_element
as $key => $dontCare) {
2267 if (property_exists($dao, $key)) {
2268 if (strpos($key, '-') !== FALSE) {
2269 $values = explode('-', $key);
2270 $lastElement = array_pop($values);
2272 $cnt = count($values);
2274 foreach ($values as $v) {
2275 if (!array_key_exists($v, $current)) {
2276 $current[$v] = array();
2278 //bad hack for im_provider
2279 if ($lastElement == 'provider_id') {
2280 if ($count < $cnt) {
2281 $current = &$current[$v];
2284 $lastElement = "{$v}_{$lastElement}";
2288 $current = &$current[$v];
2293 $current[$lastElement] = $dao->$key;
2296 $value[$key] = $dao->$key;
2304 * getter for tables array
2310 return $this->_tables
;
2314 * Where tables is sometimes used to create the from clause, but, not reliably, set this AND set tables
2315 * It's unclear the intent - there is a 'simpleFrom' clause which takes whereTables into account & a fromClause which doesn't
2316 * logic may have eroded
2319 function whereTables() {
2320 return $this->_whereTables
;
2324 * generate the where clause (used in match contacts and permissions)
2326 * @param array $params
2327 * @param array $fields
2328 * @param array $tables
2329 * @param $whereTables
2330 * @param boolean $strict
2336 static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2337 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2341 $tables = array_merge($query->tables(), $tables);
2342 $whereTables = array_merge($query->whereTables(), $whereTables);
2344 return $query->_whereClause
;
2348 * create the from clause
2350 * @param array $tables tables that need to be included in this from clause
2351 * if null, return mimimal from clause (i.e. civicrm_contact)
2352 * @param array $inner tables that should be inner-joined
2353 * @param array $right tables that should be right-joined
2355 * @param bool $primaryLocation
2358 * @return string the from clause
2362 static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2364 $from = ' FROM civicrm_contact contact_a';
2365 if (empty($tables)) {
2369 if (!empty($tables['civicrm_worldregion'])) {
2370 $tables = array_merge(array('civicrm_country' => 1), $tables);
2373 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2374 CRM_Utils_Array
::value('civicrm_county', $tables)
2375 ) && empty($tables['civicrm_address'])) {
2376 $tables = array_merge(array('civicrm_address' => 1),
2381 // add group_contact table if group table is present
2382 if (!empty($tables['civicrm_group']) && empty($tables['civicrm_group_contact'])) {
2383 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
2386 // add group_contact and group table is subscription history is present
2387 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2388 $tables = array_merge(array(
2389 'civicrm_group' => 1,
2390 'civicrm_group_contact' => 1,
2396 // to handle table dependencies of components
2397 CRM_Core_Component
::tableNames($tables);
2398 // to handle table dependencies of hook injected tables
2399 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2401 //format the table list according to the weight
2402 $info = CRM_Core_TableHierarchy
::info();
2404 foreach ($tables as $key => $value) {
2406 if (strpos($key, '-') !== FALSE) {
2407 $keyArray = explode('-', $key);
2408 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2410 elseif (strpos($key, '_') !== FALSE) {
2411 $keyArray = explode('_', $key);
2412 if (is_numeric(array_pop($keyArray))) {
2413 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2416 $k = CRM_Utils_Array
::value($key, $info, 99);
2420 $k = CRM_Utils_Array
::value($key, $info, 99);
2422 $tempTable[$k . ".$key"] = $key;
2425 $newTables = array();
2426 foreach ($tempTable as $key) {
2427 $newTables[$key] = $tables[$key];
2430 $tables = $newTables;
2432 foreach ($tables as $name => $value) {
2437 if (!empty($inner[$name])) {
2440 elseif (!empty($right[$name])) {
2448 // if there is already a join statement in value, use value itself
2449 if (strpos($value, 'JOIN')) {
2450 $from .= " $value ";
2453 $from .= " $side JOIN $name ON ( $value ) ";
2458 case 'civicrm_address':
2459 if ($primaryLocation) {
2460 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2463 //CRM-14263 further handling of address joins further down...
2464 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2468 case 'civicrm_phone':
2469 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2472 case 'civicrm_email':
2473 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2477 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2481 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2482 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2483 $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)";
2486 case 'civicrm_openid':
2487 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2490 case 'civicrm_worldregion':
2491 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2492 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2495 case 'civicrm_location_type':
2496 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2499 case 'civicrm_group':
2500 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2503 case 'civicrm_group_contact':
2504 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2507 case 'civicrm_activity':
2508 case 'civicrm_activity_tag':
2509 case 'activity_type':
2510 case 'activity_status':
2512 case 'civicrm_activity_contact':
2513 case 'source_contact':
2514 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2517 case 'civicrm_entity_tag':
2518 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2519 civicrm_entity_tag.entity_id = contact_a.id ) ";
2522 case 'civicrm_note':
2523 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2524 contact_a.id = civicrm_note.entity_id ) ";
2527 case 'civicrm_subscription_history':
2528 $from .= " $side JOIN civicrm_subscription_history
2529 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2530 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2533 case 'civicrm_relationship':
2534 if (self
::$_relType == 'reciprocal') {
2535 if (self
::$_relationshipTempTable) {
2536 // we have a temptable to join on
2537 $tbl = self
::$_relationshipTempTable;
2538 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2541 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2542 $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)";
2545 elseif (self
::$_relType == 'b') {
2546 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2547 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2550 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2551 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2556 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2557 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2561 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2564 case 'civicrm_grant':
2565 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2568 case 'civicrm_website':
2569 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2573 $locationTypeName = '';
2574 if (strpos($name, '-address') != 0) {
2575 $locationTypeName = 'address';
2577 elseif (strpos($name, '-phone') != 0) {
2578 $locationTypeName = 'phone';
2580 elseif (strpos($name, '-email') != 0) {
2581 $locationTypeName = 'email';
2583 if ($locationTypeName) {
2584 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2585 $parts = explode('-', $name);
2586 $locationID = array_search($parts[0], CRM_Core_BAO_Address
::buildOptions('location_type_id', 'get', array('name' => $parts[0])));
2587 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2590 $from .= CRM_Core_Component
::from($name, $mode, $side);
2592 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2601 * WHERE / QILL clause for deleted_contacts
2607 function deletedContacts($values) {
2608 list($_, $_, $value, $grouping, $_) = $values;
2610 // *prepend* to the relevant grouping as this is quite an important factor
2611 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2616 * where / qill clause for contact_type
2623 function contactType(&$values) {
2624 list($name, $op, $value, $grouping, $wildcard) = $values;
2626 $subTypes = array();
2629 // account for search builder mapping multiple values
2630 if (!is_array($value)) {
2631 $values = self
::parseSearchBuilderString($value, 'String');
2632 if (is_array($values)) {
2633 $value = array_flip($values);
2637 if (is_array($value)) {
2638 foreach ($value as $k => $v) {
2643 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2644 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2647 if (!empty($subType)) {
2648 $subTypes[$subType] = 1;
2650 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2655 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2656 $contactType = $contactTypeANDSubType[0];
2657 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2658 if (!empty($subType)) {
2659 $subTypes[$subType] = 1;
2661 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2665 if (!empty($clause)) {
2667 if ($op == 'IN' ||
$op == 'NOT IN') {
2668 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2671 $type = array_pop($clause);
2672 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2675 $this->_qill
[$grouping][] = ts('Contact Type') . ' - ' . implode(' ' . ts('or') . ' ', $quill);
2677 if (!empty($subTypes)) {
2678 $this->includeContactSubTypes($subTypes, $grouping);
2684 * where / qill clause for contact_sub_type
2691 function contactSubType(&$values) {
2692 list($name, $op, $value, $grouping, $wildcard) = $values;
2693 $this->includeContactSubTypes($value, $grouping);
2700 function includeContactSubTypes($value, $grouping) {
2703 $alias = "contact_a.contact_sub_type";
2705 if (is_array($value)) {
2706 foreach ($value as $k => $v) {
2708 $clause[$k] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($k, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2713 $clause[$value] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2716 if (!empty($clause)) {
2717 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2718 $this->_qill
[$grouping][] = ts('Contact Subtype') . ' - ' . implode(' ' . ts('or') . ' ', array_keys($clause));
2723 * where / qill clause for groups
2730 function group(&$values) {
2731 list($name, $op, $value, $grouping, $wildcard) = $values;
2733 if (count($value) > 1) {
2734 $this->_useDistinct
= TRUE;
2737 $groupNames = CRM_Core_PseudoConstant
::group();
2738 $groupIds = implode(',', array_keys($value));
2741 foreach ($value as $id => $dontCare) {
2742 if (array_key_exists($id, $groupNames) && $dontCare) {
2743 $names[] = $groupNames[$id];
2749 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2751 is_array($gcsValues[2])
2753 foreach ($gcsValues[2] as $k => $v) {
2755 if ($k == 'Added') {
2758 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2763 $statii[] = '"Added"';
2768 if (count($value) == 1 &&
2769 count($statii) == 1 &&
2770 $statii[0] == '"Added"'
2772 // check if smart group, if so we can get rid of that one additional
2774 $groupIDs = array_keys($value);
2776 if (!empty($groupIDs[0]) &&
2777 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
2787 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2788 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON ( contact_a.id = {$gcTable}.contact_id AND {$gcTable}.group_id $op ( $groupIds ) )";
2791 $qill = ts('Contacts %1', array(1 => $op));
2792 $qill .= ' ' . implode(' ' . ts('or') . ' ', $names);
2794 $groupClause = NULL;
2797 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2798 if (!empty($statii)) {
2799 $groupClause .= " AND {$gcTable}.status IN (" . implode(', ', $statii) . ")";
2800 $qill .= " " . ts('AND') . " " . ts('Group Status') . ' - ' . implode(' ' . ts('or') . ' ', $statii);
2805 $ssClause = $this->savedSearch($values);
2808 $groupClause = "( ( $groupClause ) OR ( $ssClause ) )";
2811 $groupClause = $ssClause;
2816 $this->_where
[$grouping][] = $groupClause;
2817 $this->_qill
[$grouping][] = $qill;
2820 * Function translates selection of group type into a list of groups
2827 function getGroupsFromTypeCriteria($value){
2828 $groupIds = array();
2829 foreach ($value as $groupTypeValue) {
2830 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2831 $groupIds = ($groupIds +
$groupList);
2837 * where / qill clause for smart groups
2841 * @return string|NULL
2844 function savedSearch(&$values) {
2845 list($name, $op, $value, $grouping, $wildcard) = $values;
2846 return $this->addGroupContactCache(array_keys($value));
2850 * @param array $groups
2851 * @param string $tableAlias
2852 * @param string $joinTable
2854 * @return null|string
2856 function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
2857 $config = CRM_Core_Config
::singleton();
2859 // Find all the groups that are part of a saved search.
2860 $groupIDs = implode(',', $groups);
2861 if (empty($groupIDs)) {
2866 SELECT id, cache_date, saved_search_id, children
2868 WHERE id IN ( $groupIDs )
2869 AND ( saved_search_id != 0
2870 OR saved_search_id IS NOT NULL
2871 OR children IS NOT NULL )
2874 $group = CRM_Core_DAO
::executeQuery($sql);
2875 $groupsFiltered = array();
2877 while ($group->fetch()) {
2878 $groupsFiltered[] = $group->id
;
2880 $this->_useDistinct
= TRUE;
2882 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
2883 CRM_Contact_BAO_GroupContactCache
::load($group);
2887 if (count($groupsFiltered)) {
2888 $groupIDsFiltered = implode(',', $groupsFiltered);
2890 if ($tableAlias == NULL) {
2891 $tableAlias = "civicrm_group_contact_cache_{$groupIDsFiltered}";
2894 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache `{$tableAlias}` ON {$joinTable}.id = `{$tableAlias}`.contact_id ";
2896 return "`{$tableAlias}`.group_id IN (" . $groupIDsFiltered . ")";
2903 * where / qill clause for cms users
2910 function ufUser(&$values) {
2911 list($name, $op, $value, $grouping, $wildcard) = $values;
2914 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2916 $this->_qill
[$grouping][] = ts('CMS User');
2918 elseif ($value == 0) {
2919 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2921 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2922 $this->_qill
[$grouping][] = ts('Not a CMS User');
2927 * all tag search specific
2934 function tagSearch(&$values) {
2935 list($name, $op, $value, $grouping, $wildcard) = $values;
2938 $value = "%{$value}%";
2941 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2942 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2944 $etTable = "`civicrm_entity_tag-" . $value . "`";
2945 $tTable = "`civicrm_tag-" . $value . "`";
2947 if ($useAllTagTypes[2]) {
2948 $this->_tables
[$etTable] =
2949 $this->_whereTables
[$etTable] =
2950 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
2951 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
2953 // search tag in cases
2954 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2955 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
2956 $this->_tables
[$etCaseTable] =
2957 $this->_whereTables
[$etCaseTable] =
2958 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2959 LEFT JOIN civicrm_case
2960 ON (civicrm_case_contact.case_id = civicrm_case.id
2961 AND civicrm_case.is_deleted = 0 )
2962 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
2963 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
2964 // search tag in activities
2965 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2966 $tActTable = "`civicrm_act_tag-" . $value . "`";
2967 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2968 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2970 $this->_tables
[$etActTable] =
2971 $this->_whereTables
[$etActTable] =
2972 " LEFT JOIN civicrm_activity_contact
2973 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
2974 LEFT JOIN civicrm_activity
2975 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
2976 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2977 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
2978 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
2980 $this->_where
[$grouping][] = "({$tTable}.name $op '". $value . "' OR {$tCaseTable}.name $op '". $value . "' OR {$tActTable}.name $op '". $value . "')";
2981 $this->_qill
[$grouping][] = ts('Tag %1 %2 ', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
2983 $etTable = "`civicrm_entity_tag-" . $value . "`";
2984 $tTable = "`civicrm_tag-" . $value . "`";
2985 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
2986 {$etTable}.entity_table = 'civicrm_contact' )
2987 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
2989 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
2990 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
2995 * where / qill clause for tag
3002 function tag(&$values) {
3003 list($name, $op, $value, $grouping, $wildcard) = $values;
3005 $tagNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
3006 if (is_array($value)) {
3007 if (count($value) > 1) {
3008 $this->_useDistinct
= TRUE;
3010 foreach ($value as $id => $dontCare) {
3011 $names[] = CRM_Utils_Array
::value($id, $tagNames);
3013 $names = implode(' ' . ts('or') . ' ', $names);
3014 $value = implode(',', array_keys($value));
3017 $names = CRM_Utils_Array
::value($value, $tagNames);
3021 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3022 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3024 $etTable = "`civicrm_entity_tag-" . $value . "`";
3026 if ($useAllTagTypes[2]) {
3027 $this->_tables
[$etTable] =
3028 $this->_whereTables
[$etTable] =
3029 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3031 // search tag in cases
3032 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3033 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3034 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3036 $this->_tables
[$etCaseTable] =
3037 $this->_whereTables
[$etCaseTable] =
3038 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3039 LEFT JOIN civicrm_case
3040 ON (civicrm_case_contact.case_id = civicrm_case.id
3041 AND civicrm_case.is_deleted = 0 )
3042 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3043 // search tag in activities
3044 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3045 $this->_tables
[$etActTable] =
3046 $this->_whereTables
[$etActTable] =
3047 " LEFT JOIN civicrm_activity_contact
3048 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3049 LEFT JOIN civicrm_activity
3050 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3051 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3052 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3055 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3056 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3059 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (". $value . ") OR {$etCaseTable}.tag_id $op (". $value . ") OR {$etActTable}.tag_id $op (". $value . "))";
3061 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
3063 $this->_tables
[$etTable] =
3064 $this->_whereTables
[$etTable] =
3065 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3068 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3069 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3070 $op = str_replace('EMPTY', 'NULL', $op);
3071 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3074 $this->_where
[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
3076 $this->_qill
[$grouping][] = ts('Tagged %1', array( 1 => $op)) . ' ' . $names;
3082 * where/qill clause for notes
3089 function notes(&$values) {
3090 list($name, $op, $value, $grouping, $wildcard) = $values;
3092 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3093 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3094 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3096 $this->_useDistinct
= TRUE;
3098 $this->_tables
['civicrm_note'] =
3099 $this->_whereTables
['civicrm_note'] =
3100 " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3102 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3104 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3105 if ($wildcard ||
$op == 'LIKE') {
3106 if (strpos($value, '%') === FALSE) {
3107 $value = "%$value%";
3111 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3117 if ( $noteOption %
2 == 0 ) {
3118 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3119 $label = ts('Note: Body Only');
3121 if ( $noteOption %
3 == 0 ) {
3122 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3123 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3125 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3126 $this->_qill
[$grouping][] = $label . " $op - '$n'";
3136 function nameNullOrEmptyOp($name, $op, $grouping) {
3140 $this->_where
[$grouping][] = "contact_a.$name $op";
3141 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3145 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3146 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3149 case 'IS NOT EMPTY':
3150 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3151 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3160 * where / qill clause for sort_name
3167 function sortName(&$values) {
3168 list($name, $op, $value, $grouping, $wildcard) = $values;
3170 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3171 if ( $this->nameNullOrEmptyOp( $name, $op, $grouping ) ) {
3176 $name = trim($value);
3182 $config = CRM_Core_Config
::singleton();
3186 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3189 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3190 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3192 if (substr($name, 0, 1) == '"' &&
3193 substr($name, -1, 1) == '"'
3195 //If name is encased in double quotes, the value should be taken to be the string in entirety and the
3196 $value = substr($name, 1, -1);
3197 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
3198 $wc = ($newName == 'sort_name') ?
'LOWER(contact_a.sort_name)' : 'LOWER(contact_a.display_name)';
3199 $sub[] = " ( $wc = '$value' ) ";
3200 if ($config->includeEmailInName
) {
3201 $sub[] = " ( civicrm_email.email = '$value' ) ";
3204 elseif (strpos($name, ',') !== FALSE) {
3205 // if we have a comma in the string, search for the entire string
3206 $value = $strtolower(CRM_Core_DAO
::escapeString($name));
3208 if ($config->includeWildCardInName
) {
3209 $value = "'%$value%'";
3212 $value = "'$value%'";
3217 $value = "'$value'";
3219 if ($newName == 'sort_name') {
3220 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3223 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3225 $sub[] = " ( $wc $op $value )";
3226 if ($config->includeNickNameInName
) {
3227 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3228 $sub[] = " ( $wc $op $value )";
3230 if ($config->includeEmailInName
) {
3231 $sub[] = " ( civicrm_email.email $op $value ) ";
3235 // the string should be treated as a series of keywords to be matched with match ANY OR
3236 // match ALL depending on Civi config settings (see CiviAdmin)
3238 // The Civi configuration setting can be overridden if the string *starts* with the case
3239 // insenstive strings 'AND:' or 'OR:'TO THINK ABOUT: what happens when someone searches
3240 // for the following "AND: 'a string in quotes'"? - probably nothing - it would make the
3241 // AND OR variable reduntant because there is only one search string?
3243 // Check to see if the $subGlue is overridden in the search text
3244 if (strtolower(substr($name, 0, 4)) == 'and:') {
3245 $name = substr($name, 4);
3248 if (strtolower(substr($name, 0, 3)) == 'or:') {
3249 $name = substr($name, 3);
3253 $firstChar = substr($name, 0, 1);
3254 $lastChar = substr($name, -1, 1);
3255 $quotes = array("'", '"');
3256 if ((strlen($name) > 2) && in_array($firstChar, $quotes) &&
3257 in_array($lastChar, $quotes)
3259 $name = substr($name, 1);
3260 $name = substr($name, 0, -1);
3261 $pieces = array($name);
3264 $pieces = explode(' ', $name);
3266 foreach ($pieces as $piece) {
3267 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($piece)));
3268 if (strlen($value)) {
3269 // Added If as a sanitization - without it, when you do an OR search, any string with
3270 // double spaces (i.e. " ") or that has a space after the keyword (e.g. "OR: ") will
3271 // return all contacts because it will include a condition similar to "OR contact
3272 // name LIKE '%'". It might be better to replace this with array_filter.
3273 $fieldsub = array();
3275 if ($config->includeWildCardInName
) {
3276 $value = "'%$value%'";
3279 $value = "'$value%'";
3284 $value = "'$value'";
3286 if ($newName == 'sort_name') {
3287 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3290 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3292 $fieldsub[] = " ( $wc $op $value )";
3293 if ($config->includeNickNameInName
) {
3294 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3295 $fieldsub[] = " ( $wc $op $value )";
3297 if ($config->includeEmailInName
) {
3298 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3300 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3301 // I seperated the glueing in two. The first stage should always be OR because we are searching for matches in *ANY* of these fields
3306 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3308 $this->_where
[$grouping][] = $sub;
3309 if ($config->includeEmailInName
) {
3310 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3311 $this->_qill
[$grouping][] = ts('Name or Email ') . "$op - '$name'";
3314 $this->_qill
[$grouping][] = ts('Name like') . " - '$name'";
3319 * where / qill clause for email
3326 function email(&$values) {
3327 list($name, $op, $value, $grouping, $wildcard) = $values;
3331 $config = CRM_Core_Config
::singleton();
3333 if (substr($n, 0, 1) == '"' &&
3334 substr($n, -1, 1) == '"'
3336 $n = substr($n, 1, -1);
3337 $value = strtolower(CRM_Core_DAO
::escapeString($n));
3338 $value = "'$value'";
3342 $value = strtolower($n);
3344 if (strpos($value, '%') === FALSE) {
3345 $value = "%{$value}%";
3350 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3351 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3354 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3355 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3358 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3362 * where / qill clause for phone number
3369 function phone_numeric(&$values) {
3370 list($name, $op, $value, $grouping, $wildcard) = $values;
3371 // Strip non-numeric characters; allow wildcards
3372 $number = preg_replace('/[^\d%]/', '', $value);
3374 if ( strpos($number, '%') === FALSE ) {
3375 $number = "%$number%";
3378 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3379 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3380 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3385 * where / qill clause for phone type/location
3392 function phone_option_group($values) {
3393 list($name, $op, $value, $grouping, $wildcard) = $values;
3394 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3395 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3396 $optionName = $options[$value];
3397 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3398 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3399 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3403 * where / qill clause for street_address
3410 function street_address(&$values) {
3411 list($name, $op, $value, $grouping, $wildcard) = $values;
3420 $value = strtolower($n);
3421 if (strpos($value, '%') === FALSE) {
3422 // only add wild card if not there
3423 $value = "%{$value}%";
3426 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3427 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3430 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3431 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3434 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3438 * where / qill clause for street_unit
3445 function street_number(&$values) {
3446 list($name, $op, $value, $grouping, $wildcard) = $values;
3454 if (strtolower($n) == 'odd') {
3455 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3456 $this->_qill
[$grouping][] = ts('Street Number is odd');
3458 elseif (strtolower($n) == 'even') {
3459 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3460 $this->_qill
[$grouping][] = ts('Street Number is even');
3463 $value = strtolower($n);
3465 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3466 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3469 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3473 * where / qill clause for sorting by character
3480 function sortByCharacter(&$values) {
3481 list($name, $op, $value, $grouping, $wildcard) = $values;
3483 $name = trim($value);
3484 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3485 $this->_where
[$grouping][] = $cond;
3486 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3490 * where / qill clause for including contact ids
3495 function includeContactIDs() {
3496 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3500 $contactIds = array();
3501 foreach ($this->_params
as $id => $values) {
3502 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3503 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3506 if (!empty($contactIds)) {
3507 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3512 * where / qill clause for postal code
3519 function postalCode(&$values) {
3520 // skip if the fields dont have anything to do with postal_code
3521 if (empty($this->_fields
['postal_code'])) {
3525 list($name, $op, $value, $grouping, $wildcard) = $values;
3527 // Handle numeric postal code range searches properly by casting the column as numeric
3528 if (is_numeric($value)) {
3529 $field = 'ROUND(civicrm_address.postal_code)';
3530 $val = CRM_Utils_Type
::escape($value, 'Integer');
3533 $field = 'civicrm_address.postal_code';
3534 $val = CRM_Utils_Type
::escape($value, 'String');
3537 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3539 if ($name == 'postal_code') {
3540 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3541 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3543 elseif ($name == 'postal_code_low') {
3544 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3545 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3547 elseif ($name == 'postal_code_high') {
3548 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3549 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3554 * where / qill clause for location type
3557 * @param null $status
3562 function locationType(&$values, $status = NULL) {
3563 list($name, $op, $value, $grouping, $wildcard) = $values;
3565 if (is_array($value)) {
3566 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3567 $this->_tables
['civicrm_address'] = 1;
3568 $this->_whereTables
['civicrm_address'] = 1;
3570 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3572 foreach ($value as $id) {
3573 $names[] = $locationType[$id];
3576 $this->_primaryLocation
= FALSE;
3579 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3582 return implode(' ' . ts('or') . ' ', $names);
3589 * @param bool $fromStateProvince
3593 function country(&$values, $fromStateProvince = TRUE) {
3594 list($name, $op, $value, $grouping, $wildcard) = $values;
3596 if (!$fromStateProvince) {
3597 $stateValues = $this->getWhereValues('state_province', $grouping);
3598 if (!empty($stateValues)) {
3599 // return back to caller if there are state province values
3600 // since that handles this case
3605 $countryClause = $countryQill = NULL;
3611 $this->_tables
['civicrm_address'] = 1;
3612 $this->_whereTables
['civicrm_address'] = 1;
3614 $countries = CRM_Core_PseudoConstant
::country();
3615 if (is_numeric($value)) {
3616 $countryClause = self
::buildClause(
3617 'civicrm_address.country_id',
3622 $countryName = $countries[(int ) $value];
3626 $intValues = self
::parseSearchBuilderString($value);
3627 if ($intValues && ($op == 'IN' ||
$op == 'NOT IN')) {
3628 $countryClause = self
::buildClause(
3629 'civicrm_address.country_id',
3634 $countryNames = array();
3635 foreach ($intValues as $v) {
3636 $countryNames[] = $countries[$v];
3638 $countryName = implode(',', $countryNames);
3641 $countries = CRM_Core_PseudoConstant
::country();
3642 $intVal = CRM_Utils_Array
::key($value, $countries);
3643 $countryClause = self
::buildClause(
3644 'civicrm_address.country_id',
3649 $countryName = $value;
3652 $countryQill = ts('Country') . " {$op} '$countryName'";
3654 if (!$fromStateProvince) {
3655 $this->_where
[$grouping][] = $countryClause;
3656 $this->_qill
[$grouping][] = $countryQill;
3660 if ($fromStateProvince) {
3661 if (!empty($countryClause)) {
3664 " ...AND... " . $countryQill,
3668 return array(NULL, NULL);
3674 * where / qill clause for county (if present)
3677 * @param null $status
3682 function county(&$values, $status = null) {
3683 list($name, $op, $value, $grouping, $wildcard) = $values;
3685 if (! is_array($value)) {
3686 // force the county to be an array
3687 $value = array($value);
3690 // check if the values are ids OR names of the counties
3691 $inputFormat = 'id';
3692 foreach ($value as $v) {
3693 if (!is_numeric($v)) {
3694 $inputFormat = 'name';
3702 else if ($op == '!=') {
3706 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3707 $op = str_replace('EMPTY', 'NULL', $op);
3710 if (in_array( $op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3711 $clause = "civicrm_address.county_id $op";
3713 elseif ($inputFormat == 'id') {
3714 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3716 $county = CRM_Core_PseudoConstant
::county();
3717 foreach ($value as $id) {
3718 $names[] = CRM_Utils_Array
::value($id, $county);
3722 $inputClause = array();
3723 $county = CRM_Core_PseudoConstant
::county();
3724 foreach ($value as $name) {
3725 $name = trim($name);
3726 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3728 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3731 $this->_tables
['civicrm_address'] = 1;
3732 $this->_whereTables
['civicrm_address'] = 1;
3734 $this->_where
[$grouping][] = $clause;
3736 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3738 return implode(' ' . ts('or') . ' ', $names);
3743 * where / qill clause for state/province AND country (if present)
3746 * @param null $status
3751 function stateProvince(&$values, $status = NULL) {
3752 list($name, $op, $value, $grouping, $wildcard) = $values;
3754 // quick escape for IS NULL
3755 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3758 else if (!is_array($value)) {
3759 // force the state to be an array
3760 // check if its in the mapper format!
3761 $values = self
::parseSearchBuilderString($value);
3762 if (is_array($values)) {
3766 $value = array($value);
3770 // check if the values are ids OR names of the states
3771 $inputFormat = 'id';
3773 foreach ($value as $v) {
3774 if (!is_numeric($v)) {
3775 $inputFormat = 'name';
3785 else if ($op == '!=') {
3789 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3790 $op = str_replace('EMPTY', 'NULL', $op);
3792 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3793 $stateClause = "civicrm_address.state_province_id $op";
3795 else if ($inputFormat == 'id') {
3796 if ($op != 'NOT IN') {
3799 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
3801 foreach ($value as $id) {
3802 $names[] = CRM_Core_PseudoConstant
::stateProvince($id, FALSE);
3806 $inputClause = array();
3807 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3808 foreach ($value as $name) {
3809 $name = trim($name);
3810 $inputClause[] = CRM_Utils_Array
::key($name, $stateProvince);
3812 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
3815 $this->_tables
['civicrm_address'] = 1;
3816 $this->_whereTables
['civicrm_address'] = 1;
3818 $countryValues = $this->getWhereValues('country', $grouping);
3819 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3821 if ($countryClause) {
3822 $clause = "( $stateClause AND $countryClause )";
3825 $clause = $stateClause;
3828 $this->_where
[$grouping][] = $clause;
3830 $this->_qill
[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3833 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
3838 * where / qill clause for change log
3845 function changeLog(&$values) {
3846 list($name, $op, $value, $grouping, $wildcard) = $values;
3848 $targetName = $this->getWhereValues('changed_by', $grouping);
3853 $name = trim($targetName[2]);
3854 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3855 $name = $targetName[4] ?
"%$name%" : $name;
3856 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3857 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3858 $this->_qill
[$grouping][] = ts('Modified by') . ": $name";
3864 function modifiedDates($values) {
3865 $this->_useDistinct
= TRUE;
3867 // CRM-11281, default to added date if not set
3868 $fieldTitle = ts('Added Date');
3869 $fieldName = 'created_date';
3870 foreach (array_keys($this->_params
) as $id) {
3871 if ($this->_params
[$id][0] == 'log_date') {
3872 if ($this->_params
[$id][2] == 2) {
3873 $fieldTitle = ts('Modified Date');
3874 $fieldName = 'modified_date';
3880 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3882 self
::$_openedPanes[ts('Change Log')] = TRUE;
3888 function demographics(&$values) {
3889 list($name, $op, $value, $grouping, $wildcard) = $values;
3891 if (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3893 $this->dateQueryBuilder($values,
3894 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3897 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3899 $this->dateQueryBuilder($values,
3900 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3904 self
::$_openedPanes[ts('Demographics')] = TRUE;
3910 function privacy(&$values) {
3911 list($name, $op, $value, $grouping, $wildcard) = $values;
3912 //fixed for profile search listing CRM-4633
3913 if (strpbrk($value, "[")) {
3914 $value = "'{$value}'";
3916 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3919 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3921 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3922 $title = $field ?
$field['title'] : $name;
3923 $this->_qill
[$grouping][] = "$title $op $value";
3929 function privacyOptions($values) {
3930 list($name, $op, $value, $grouping, $wildcard) = $values;
3932 if (empty($value) ||
!is_array($value)) {
3936 // get the operator and toggle values
3937 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3940 strtolower($opValues[2] == 'AND')
3945 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3947 if ($toggleValues &&
3948 $toggleValues[2] == 2
3955 foreach ($value as $dontCare => $pOption) {
3956 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
3957 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3958 $title = $field ?
$field['title'] : $pOption;
3959 $qill[] = " $title = 1 ";
3962 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
3963 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
3969 function preferredCommunication(&$values) {
3970 list($name, $op, $value, $grouping, $wildcard) = $values;
3973 if (in_array($op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3976 elseif (!is_array($value)) {
3978 $value = trim($value, ' ()');
3979 if (strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
3980 $v = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
3983 $v = explode(",", $value);
3986 foreach ($v as $item) {
3993 foreach ($value as $key => $checked) {
4000 $commPref = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
4002 $sqlValue = array();
4003 $showValue = array();
4004 $sql = "contact_a.preferred_communication_method";
4005 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
4006 $sqlValue[] = "{$sql} {$op}";
4009 foreach ($pref as $val) {
4010 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $val . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' ) ";
4011 $showValue[] = $commPref[$val];
4014 $this->_where
[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
4015 $this->_qill
[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
4019 * where / qill clause for relationship
4026 function relationship(&$values) {
4027 list($name, $op, $value, $grouping, $wildcard) = $values;
4028 if ($this->_relationshipValuesAdded
){
4031 // also get values array for relation_target_name
4032 // for relatinship search we always do wildcard
4033 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4034 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4035 $relStatus = $this->getWhereValues('relation_status', $grouping);
4036 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4037 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4039 $nameClause = $name = NULL;
4041 $name = trim($targetName[2]);
4042 if (substr($name, 0, 1) == '"' &&
4043 substr($name, -1, 1) == '"'
4045 $name = substr($name, 1, -1);
4046 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4047 $nameClause = "= '$name'";
4050 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4051 $nameClause = "LIKE '%{$name}%'";
4055 $rTypeValues = array();
4056 if (!empty($relationType) ) {
4057 $rel = explode('_', $relationType[2]);
4058 self
::$_relType = $rel[1];
4059 $params = array('id' => $rel[0]);
4060 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
4062 if ( empty($rTypeValues) ) {
4063 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4064 //@todo unless we are dealing with a target group
4065 self
::$_relType = 'reciprocal';
4067 // if we are creating a temp table we build our own where for the relationship table
4068 $relationshipTempTable = NULL;
4069 if (self
::$_relType == 'reciprocal' && empty($targetGroup)) {
4071 self
::$_relationshipTempTable =
4072 $relationshipTempTable =
4073 CRM_Core_DAO
::createTempTableName( 'civicrm_rel');
4075 $where[$grouping][] = " sort_name $nameClause ";
4079 $where = &$this->_where
;
4081 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4086 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
4087 $relTypeOrg = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
4088 $relTypeHou = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Household');
4089 $allRelationshipType = array();
4090 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
4091 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
4093 if ($nameClause ||
!$targetGroup) {
4094 if (!empty($relationType) ) {
4095 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] ." $name";
4097 $this->_qill
[$grouping][] = $name;
4102 //check to see if the target contact is in specified group
4104 //add contacts from static groups
4105 $this->_tables
['civicrm_relationship_group_contact'] =
4106 $this->_whereTables
['civicrm_relationship_group_contact'] =
4107 " 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'";
4109 "( civicrm_relationship_group_contact.group_id IN (" .
4110 implode(",", $targetGroup[2]) . ") ) ";
4112 //add contacts from saved searches
4113 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
4115 //set the group where clause
4117 $groupWhere[] = "( " . $ssWhere . " )";
4119 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4121 //Get the names of the target groups for the qill
4122 $groupNames = CRM_Core_PseudoConstant
::group();
4123 $qillNames = array();
4124 foreach ($targetGroup[2] as $groupId) {
4125 if (array_key_exists($groupId, $groupNames)) {
4126 $qillNames[] = $groupNames[$groupId];
4129 if ( !empty($relationType) ) {
4130 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] ." ( " . implode(", ", $qillNames) . " )";
4132 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4136 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4137 $today = date('Ymd');
4138 //check for active, inactive and all relation status
4139 if ($relStatus[2] == 0) {
4140 $where[$grouping][] = "(
4141 civicrm_relationship.is_active = 1 AND
4142 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4143 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4145 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4147 elseif ($relStatus[2] == 1) {
4148 $where[$grouping][] = "(
4149 civicrm_relationship.is_active = 0 OR
4150 civicrm_relationship.end_date < {$today} OR
4151 civicrm_relationship.start_date > {$today}
4153 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4156 //check for permissioned, non-permissioned and all permissioned relations
4157 if ($relPermission[2] == 1) {
4158 $where[$grouping][] = "(
4159 civicrm_relationship.is_permission_a_b = 1
4161 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4162 } elseif ($relPermission[2] == 2) {
4163 //non-allowed permission relationship.
4164 $where[$grouping][] = "(
4165 civicrm_relationship.is_permission_a_b = 0
4167 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4170 $this->addRelationshipDateClauses($grouping, $where);
4171 if (!empty($relationType) && !empty($rType) && isset($rType->id
)){
4172 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
4174 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4175 $this->_useDistinct
= TRUE;
4176 $this->_relationshipValuesAdded
= TRUE;
4177 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4179 // @todo creating a temp table could be expanded to group filter
4180 // as even creating a temp table of all relationships is much much more efficient than
4181 // an OR in the join
4182 if ($relationshipTempTable) {
4184 if ( ! empty( $where[$grouping] ) ) {
4185 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4188 CREATE TEMPORARY TABLE {$relationshipTempTable}
4189 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4190 FROM civicrm_relationship
4191 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4194 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4195 FROM civicrm_relationship
4196 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4199 CRM_Core_DAO
::executeQuery($sql);
4204 * Add start & end date criteria in
4205 * @param string $grouping
4206 * @param array $where = array to add where clauses to, in case you are generating a temp table
4207 * not the main query.
4209 function addRelationshipDateClauses($grouping, &$where){
4210 $dateValues = array();
4216 foreach ($dateTypes as $dateField){
4217 $dateValueLow = $this->getWhereValues('relation_'. $dateField .'_low', $grouping);
4218 $dateValueHigh= $this->getWhereValues('relation_'. $dateField .'_high', $grouping);
4219 if (!empty($dateValueLow)){
4220 $date = date('Ymd', strtotime($dateValueLow[2]));
4221 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4222 $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);
4224 if (!empty($dateValueHigh)){
4225 $date = date('Ymd', strtotime($dateValueHigh[2]));
4226 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4227 $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);
4233 * default set of return properties
4237 * @return array derault return properties
4240 static function &defaultReturnProperties($mode = 1) {
4241 if (!isset(self
::$_defaultReturnProperties)) {
4242 self
::$_defaultReturnProperties = array();
4245 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4246 // add activity return properties
4247 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4248 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4251 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4254 if (empty(self
::$_defaultReturnProperties[$mode])) {
4255 self
::$_defaultReturnProperties[$mode] = array(
4258 'legal_identifier' => 1,
4259 'external_identifier' => 1,
4260 'contact_type' => 1,
4261 'contact_sub_type' => 1,
4263 'display_name' => 1,
4264 'preferred_mail_format' => 1,
4271 'formal_title' => 1,
4272 'communication_style_id' => 1,
4275 'street_address' => 1,
4276 'supplemental_address_1' => 1,
4277 'supplemental_address_2' => 1,
4280 'postal_code_suffix' => 1,
4281 'state_province' => 1,
4283 'world_region' => 1,
4290 'household_name' => 1,
4291 'organization_name' => 1,
4292 'deceased_date' => 1,
4297 'current_employer' => 1,
4298 // FIXME: should we use defaultHierReturnProperties() for the below?
4299 'do_not_email' => 1,
4302 'do_not_phone' => 1,
4303 'do_not_trade' => 1,
4305 'contact_is_deleted' => 1,
4306 'preferred_communication_method' => 1,
4307 'preferred_language' => 1,
4311 return self
::$_defaultReturnProperties[$mode];
4315 * get primary condition for a sql clause
4319 * @return string|NULL
4322 static function getPrimaryCondition($value) {
4323 if (is_numeric($value)) {
4324 $value = (int ) $value;
4325 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4331 * wrapper for a simple search query
4333 * @param array $params
4334 * @param array $returnProperties
4335 * @param bool $count
4340 static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4341 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4342 list($select, $from, $where, $having) = $query->query();
4344 return "$select $from $where $having";
4348 * These are stub comments as this function needs more explanation - particularly in terms of how it
4349 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4351 * This function was originally written as a wrapper for the api query but is called from multiple places
4352 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4353 * but it is unclear as to whehter that is historical or there is a reason
4354 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4356 * @param array $params
4357 * @param array $returnProperties
4358 * @param null $fields
4359 * @param string $sort
4360 * @param int $offset
4361 * @param int $row_count
4362 * @param bool $smartGroupCache
4363 * @param bool $count return count obnly
4364 * @param bool $skipPermissions Should permissions be ignored or should the logged in user's permissions be applied
4366 * @params bool $smartGroupCache ?? update smart group cache?
4371 static function apiQuery(
4373 $returnProperties = NULL,
4378 $smartGroupCache = TRUE,
4380 $skipPermissions = TRUE
4383 $query = new CRM_Contact_BAO_Query(
4384 $params, $returnProperties,
4385 NULL, TRUE, FALSE, 1,
4387 TRUE, $smartGroupCache
4390 //this should add a check for view deleted if permissions are enabled
4391 if ($skipPermissions){
4392 $query->_skipDeleteClause
= TRUE;
4394 $query->generatePermissionClause(FALSE, $count);
4396 // note : this modifies _fromClause and _simpleFromClause
4397 $query->includePseudoFieldsJoin($sort);
4399 list($select, $from, $where, $having) = $query->query($count);
4401 $options = $query->_options
;
4402 if (!empty($query->_permissionWhereClause
)){
4403 if (empty($where)) {
4404 $where = "WHERE $query->_permissionWhereClause";
4407 $where = "$where AND $query->_permissionWhereClause";
4411 $sql = "$select $from $where $having";
4414 if ($query->_useGroupBy
) {
4415 $sql .= ' GROUP BY contact_a.id';
4417 if (!empty($sort)) {
4418 $sort = CRM_Utils_Type
::escape($sort, 'String');
4419 $sql .= " ORDER BY $sort ";
4421 if ($row_count > 0 && $offset >= 0) {
4422 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4423 $rowCount = CRM_Utils_Type
::escape($row_count, 'Int');
4424 $sql .= " LIMIT $offset, $row_count ";
4427 $dao = CRM_Core_DAO
::executeQuery($sql);
4430 while ($dao->fetch()) {
4432 $noRows = $dao->rowCount
;
4434 return array($noRows,NULL);
4436 $val = $query->store($dao);
4437 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4439 if (!empty($convertedVals)) {
4440 $val = array_replace_recursive($val, $convertedVals);
4442 $values[$dao->contact_id
] = $val;
4445 return array($values, $options);
4449 * create and query the db for an contact search
4451 * @param int $offset the offset for the query
4452 * @param int $rowCount the number of rows to return
4453 * @param string $sort the order by string
4454 * @param boolean $count is this a count only query ?
4455 * @param boolean $includeContactIds should we include contact ids?
4456 * @param boolean $sortByChar if true returns the distinct array of first characters for search results
4457 * @param boolean $groupContacts if true, return only the contact ids
4458 * @param boolean $returnQuery should we return the query as a string
4459 * @param string $additionalWhereClause if the caller wants to further restrict the search (used for components)
4460 * @param null $sortOrder
4461 * @param string $additionalFromClause should be clause with proper joins, effective to reduce where clause load.
4463 * @param bool $skipOrderAndLimit
4465 * @return CRM_Core_DAO
4468 function searchQuery(
4469 $offset = 0, $rowCount = 0, $sort = NULL,
4470 $count = FALSE, $includeContactIds = FALSE,
4471 $sortByChar = FALSE, $groupContacts = FALSE,
4472 $returnQuery = FALSE,
4473 $additionalWhereClause = NULL, $sortOrder = NULL,
4474 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4477 if ($includeContactIds) {
4478 $this->_includeContactIds
= TRUE;
4479 $this->_whereClause
= $this->whereClause();
4482 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4484 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4485 // and that contact happens to be deleted, set $onlyDeleted to true
4486 foreach ($this->_params
as $values) {
4487 $name = CRM_Utils_Array
::value(0, $values);
4488 $op = CRM_Utils_Array
::value(1, $values);
4489 $value = CRM_Utils_Array
::value(2, $values);
4490 if ($name == 'contact_id' and $op == '=') {
4491 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4492 $onlyDeleted = TRUE;
4498 // building the query string
4501 if (isset($this->_groupByComponentClause
)) {
4502 $groupBy = $this->_groupByComponentClause
;
4504 elseif ($this->_useGroupBy
) {
4505 $groupBy = ' GROUP BY contact_a.id';
4508 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4509 $groupBy = 'GROUP BY civicrm_activity.id ';
4512 $order = $orderBy = $limit = '';
4514 $config = CRM_Core_Config
::singleton();
4515 if ($config->includeOrderByClause ||
4516 isset($this->_distinctComponentClause
)
4519 if (is_string($sort)) {
4523 $orderBy = trim($sort->orderBy());
4525 if (!empty($orderBy)) {
4526 // this is special case while searching for
4527 // change log CRM-1718
4528 if (preg_match('/sort_name/i', $orderBy)) {
4529 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4532 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
4533 $order = " ORDER BY $orderBy";
4536 $sortOrder = CRM_Utils_Type
::escape($sortOrder, 'String');
4537 $order .= " $sortOrder";
4540 // always add contact_a.id to the ORDER clause
4541 // so the order is deterministic
4542 if (strpos('contact_a.id', $order) === FALSE) {
4543 $order .= ", contact_a.id";
4547 elseif ($sortByChar) {
4548 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4551 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4555 // hack for order clause
4557 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4558 $fieldOrder = explode(' ', $fieldStr);
4559 $field = $fieldOrder[0];
4565 $this->_whereTables
["civicrm_address"] = 1;
4566 $order = str_replace($field, "civicrm_address.{$field}", $order);
4570 case 'state_province':
4571 $this->_whereTables
["civicrm_{$field}"] = 1;
4572 $order = str_replace($field, "civicrm_{$field}.name", $order);
4576 $this->_whereTables
["civicrm_email"] = 1;
4577 $order = str_replace($field, "civicrm_email.{$field}", $order);
4581 //CRM-12565 add "`" around $field if it is a pseudo constant
4582 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
4583 if (!empty($value['element']) && $value['element'] == $field) {
4584 $order = str_replace($field, "`{$field}`", $order);
4588 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4589 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4593 if ($rowCount > 0 && $offset >= 0) {
4594 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4595 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4596 $limit = " LIMIT $offset, $rowCount ";
4601 $this->_sort
= $sort;
4603 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4605 if ($additionalWhereClause) {
4606 $where = $where . ' AND ' . $additionalWhereClause;
4609 //additional from clause should be w/ proper joins.
4610 if ($additionalFromClause) {
4611 $from .= "\n" . $additionalFromClause;
4614 // if we are doing a transform, do it here
4615 // use the $from, $where and $having to get the contact ID
4616 if ($this->_displayRelationshipType
) {
4617 $this->filterRelatedContacts($from, $where, $having);
4620 if ($skipOrderAndLimit) {
4621 $query = "$select $from $where $having $groupBy";
4624 $query = "$select $from $where $having $groupBy $order $limit";
4631 return CRM_Core_DAO
::singleValueQuery($query);
4634 $dao = CRM_Core_DAO
::executeQuery($query);
4635 if ($groupContacts) {
4637 while ($dao->fetch()) {
4640 return implode(',', $ids);
4647 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4649 * @param string $cacheKey
4650 * @param int $offset
4651 * @param int $rowCount
4652 * @param bool $includeContactIds
4653 * @return CRM_Core_DAO
4655 function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4656 $this->_includeContactIds
= $includeContactIds;
4657 list($select, $from, $where) = $this->query();
4658 $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);
4659 $order = " ORDER BY pnc.id";
4660 $groupBy = " GROUP BY contact_a.id";
4661 $limit = " LIMIT $offset, $rowCount";
4662 $query = "$select $from $where $groupBy $order $limit";
4664 return CRM_Core_DAO
::executeQuery($query);
4668 * Populate $this->_permissionWhereClause with permission related clause and update other
4669 * query related properties.
4671 * Function calls ACL permission class and hooks to filter the query appropriately
4673 * Note that these 2 params were in the code when extracted from another function
4674 * and a second round extraction would be to make them properties of the class
4676 * @param bool $onlyDeleted Only get deleted contacts
4677 * @param bool $count Return Count only
4681 function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4682 if (!$this->_skipPermission
) {
4683 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4684 CRM_Core_Permission
::VIEW
,
4686 $this->_whereTables
,
4689 $this->_skipDeleteClause
4692 // regenerate fromClause since permission might have added tables
4693 if ($this->_permissionWhereClause
) {
4694 //fix for row count in qill (in contribute/membership find)
4696 $this->_useDistinct
= TRUE;
4699 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4700 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4701 // note : this modifies _fromClause and _simpleFromClause
4702 $this->includePseudoFieldsJoin($this->_sort
);
4706 // add delete clause if needed even if we are skipping permission
4708 if (!$this->_skipDeleteClause
) {
4709 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4710 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4714 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4723 function setSkipPermission($val) {
4724 $this->_skipPermission
= $val;
4728 * @param null $context
4732 function &summaryContribution($context = NULL) {
4733 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4737 SELECT COUNT( conts.total_amount ) as total_count,
4738 SUM( conts.total_amount ) as total_amount,
4739 AVG( conts.total_amount ) as total_avg,
4740 conts.currency as currency";
4741 if ($this->_permissionWhereClause
) {
4742 $where .= " AND " . $this->_permissionWhereClause
;
4744 if ($context == 'search') {
4745 $where .= " AND contact_a.is_deleted = 0 ";
4748 // make sure contribution is completed - CRM-4989
4749 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4753 $summary['total'] = array();
4754 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4756 $query = "$select FROM (
4757 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $completedWhere
4758 GROUP BY civicrm_contribution.id
4762 $dao = CRM_Core_DAO
::executeQuery($query);
4764 $summary['total']['count'] = 0;
4765 $summary['total']['amount'] = $summary['total']['avg'] = array();
4766 while ($dao->fetch()) {
4767 $summary['total']['count'] +
= $dao->total_count
;
4768 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4769 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4771 if (!empty($summary['total']['amount'])) {
4772 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4773 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4776 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4779 // soft credit summary
4780 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
4781 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
4784 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
4785 GROUP BY civicrm_contribution_soft.id
4788 $dao = CRM_Core_DAO
::executeQuery($query);
4789 $summary['soft_credit']['count'] = 0;
4790 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
4791 while ($dao->fetch()) {
4792 $summary['soft_credit']['count'] +
= $dao->total_count
;
4793 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4794 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4796 if (!empty($summary['soft_credit']['amount'])) {
4797 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
4798 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
4801 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
4806 //@todo - this could be one query using the IF in mysql - eg
4807 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
4808 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
4809 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
4810 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
4811 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
4812 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
4813 // FROM civicrm_contact contact_a
4814 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
4815 // WHERE ( ... where clause....
4816 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
4820 SELECT COUNT( conts.total_amount ) as cancel_count,
4821 SUM( conts.total_amount ) as cancel_amount,
4822 AVG( conts.total_amount ) as cancel_avg,
4823 conts.currency as currency";
4825 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4826 if ($context == 'search') {
4827 $where .= " AND contact_a.is_deleted = 0 ";
4830 $query = "$select FROM (
4831 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
4832 GROUP BY civicrm_contribution.id
4836 $dao = CRM_Core_DAO
::executeQuery($query);
4839 if ($dao->fetch()) {
4840 $summary['cancel']['count'] = $dao->cancel_count
;
4841 $summary['cancel']['amount'] = $dao->cancel_amount
;
4842 $summary['cancel']['avg'] = $dao->cancel_avg
;
4846 $summary['cancel']['count'] = 0;
4847 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4848 while ($dao->fetch()) {
4849 $summary['cancel']['count'] +
= $dao->cancel_count
;
4850 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4851 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4853 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4854 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
4861 * getter for the qill object
4867 return $this->_qill
;
4871 * default set of return default hier return properties
4876 static function &defaultHierReturnProperties() {
4877 if (!isset(self
::$_defaultHierReturnProperties)) {
4878 self
::$_defaultHierReturnProperties = array(
4881 'legal_identifier' => 1,
4882 'external_identifier' => 1,
4883 'contact_type' => 1,
4884 'contact_sub_type' => 1,
4886 'display_name' => 1,
4893 'formal_title' => 1,
4894 'communication_style_id' => 1,
4895 'email_greeting' => 1,
4896 'postal_greeting' => 1,
4900 'preferred_communication_method' => 1,
4901 'do_not_phone' => 1,
4902 'do_not_email' => 1,
4905 'do_not_trade' => 1,
4908 '1' => array('location_type' => 1,
4909 'street_address' => 1,
4911 'state_province' => 1,
4913 'postal_code_suffix' => 1,
4916 'phone-Mobile' => 1,
4929 'location_type' => 1,
4930 'street_address' => 1,
4932 'state_province' => 1,
4934 'postal_code_suffix' => 1,
4937 'phone-Mobile' => 1,
4951 return self
::$_defaultHierReturnProperties;
4958 * @param $dbFieldName
4959 * @param $fieldTitle
4960 * @param bool $appendTimeStamp
4962 function dateQueryBuilder(
4963 &$values, $tableName, $fieldName,
4964 $dbFieldName, $fieldTitle,
4965 $appendTimeStamp = TRUE
4967 list($name, $op, $value, $grouping, $wildcard) = $values;
4973 if ($name == "{$fieldName}_low" ||
4974 $name == "{$fieldName}_high"
4976 if (isset($this->_rangeCache
[$fieldName])) {
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) {
5048 $date = CRM_Utils_Date
::processDate($value);
5050 if (!$appendTimeStamp) {
5051 $date = substr($date, 0, 8);
5054 $format = CRM_Utils_Date
::customFormat($date);
5057 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'";
5060 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op";
5062 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5063 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$format\"";
5071 * @param $dbFieldName
5072 * @param $fieldTitle
5073 * @param null $options
5075 function numberRangeBuilder(&$values,
5076 $tableName, $fieldName,
5077 $dbFieldName, $fieldTitle,
5080 list($name, $op, $value, $grouping, $wildcard) = $values;
5082 if ($name == "{$fieldName}_low" ||
5083 $name == "{$fieldName}_high"
5085 if (isset($this->_rangeCache
[$fieldName])) {
5088 $this->_rangeCache
[$fieldName] = 1;
5090 $secondOP = $secondPhrase = $secondValue = NULL;
5092 if ($name == "{$fieldName}_low") {
5094 $firstPhrase = ts('greater than');
5096 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5097 if (!empty($secondValues)) {
5099 $secondPhrase = ts('less than');
5100 $secondValue = $secondValues[2];
5105 $firstPhrase = ts('less than');
5107 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5108 if (!empty($secondValues)) {
5110 $secondPhrase = ts('greater than');
5111 $secondValue = $secondValues[2];
5116 $this->_where
[$grouping][] = "
5117 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5118 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5120 $displayValue = $options ?
$options[$value] : $value;
5121 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5123 $this->_qill
[$grouping][] =
5124 "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5127 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5128 $displayValue = $options ?
$options[$value] : $value;
5129 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5131 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5136 if ($name == $fieldName) {
5140 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5142 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5143 $displayValue = $options ?
$options[$value] : $value;
5144 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5151 * Given the field name, operator, value & its data type
5152 * builds the where Clause for the query
5153 * used for handling 'IS NULL'/'IS NOT NULL' operators
5155 * @param string $field fieldname
5156 * @param string $op operator
5157 * @param string $value value
5158 * @param string $dataType data type of the field
5160 * @return string where clause for the query
5163 static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5165 $clause = "$field $op";
5173 $clause = " (NULLIF($field, '') IS NULL) ";
5176 case 'IS NOT EMPTY':
5177 $clause = " (NULLIF($field, '') IS NOT NULL) ";
5182 if (isset($dataType)) {
5183 if (is_array($value)) {
5187 $value = CRM_Utils_Type
::escape($value, "String");
5188 $values = explode(',', CRM_Utils_Array
::value(0, explode(')', CRM_Utils_Array
::value(1, explode('(', $value)))));
5190 // supporting multiple values in IN clause
5192 foreach ($values as $v) {
5194 $val[] = "'" . CRM_Utils_Type
::escape($v, $dataType) . "'";
5196 $value = "(" . implode($val, ",") . ")";
5198 return "$clause $value";
5201 if (empty($dataType)) {
5202 $dataType = 'String';
5205 $value = CRM_Utils_Type
::escape($value, $dataType);
5206 // if we don't have a dataType we should assume
5207 if ($dataType == 'String' ||
$dataType == 'Text') {
5208 $value = "'" . strtolower($value) . "'";
5210 return "$clause $value";
5215 * @param bool $reset
5219 function openedSearchPanes($reset = FALSE) {
5220 if (!$reset ||
empty($this->_whereTables
)) {
5221 return self
::$_openedPanes;
5224 // pane name to table mapper
5225 $panesMapper = array(
5226 ts('Contributions') => 'civicrm_contribution',
5227 ts('Memberships') => 'civicrm_membership',
5228 ts('Events') => 'civicrm_participant',
5229 ts('Relationships') => 'civicrm_relationship',
5230 ts('Activities') => 'civicrm_activity',
5231 ts('Pledges') => 'civicrm_pledge',
5232 ts('Cases') => 'civicrm_case',
5233 ts('Grants') => 'civicrm_grant',
5234 ts('Address Fields') => 'civicrm_address',
5235 ts('Notes') => 'civicrm_note',
5236 ts('Change Log') => 'civicrm_log',
5237 ts('Mailings') => 'civicrm_mailing_event_queue',
5239 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5241 foreach (array_keys($this->_whereTables
) as $table) {
5242 if ($panName = array_search($table, $panesMapper)) {
5243 self
::$_openedPanes[$panName] = TRUE;
5247 return self
::$_openedPanes;
5253 function setOperator($operator) {
5254 $validOperators = array('AND', 'OR');
5255 if (!in_array($operator, $validOperators)) {
5258 $this->_operator
= $operator;
5264 function getOperator() {
5265 return $this->_operator
;
5273 function filterRelatedContacts(&$from, &$where, &$having) {
5274 static $_rTypeProcessed = NULL;
5275 static $_rTypeFrom = NULL;
5276 static $_rTypeWhere = NULL;
5278 if (!$_rTypeProcessed) {
5279 $_rTypeProcessed = TRUE;
5281 // create temp table with contact ids
5282 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5283 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5284 CRM_Core_DAO
::executeQuery($sql);
5287 REPLACE INTO $tableName ( contact_id )
5293 CRM_Core_DAO
::executeQuery($sql);
5295 $qillMessage = ts('Contacts with a Relationship Type of: ');
5296 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5298 if (is_numeric($this->_displayRelationshipType
)) {
5299 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5301 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5302 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5305 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5306 AND displayRelType.is_active = 1
5310 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5311 if ($dirOne == 'a') {
5312 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5314 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5315 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5319 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5321 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5322 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5326 WHERE displayRelType.relationship_type_id = $relType
5327 AND displayRelType.is_active = 1
5330 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5333 if (strpos($from, $_rTypeFrom) === FALSE) {
5334 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5335 // this happens when we have an event_type in the quert (CRM-7969)
5336 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5337 $from .= $_rTypeFrom;
5338 $where = $_rTypeWhere;
5349 static function caseImportant( $op ) {
5351 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5355 * @param $returnProperties
5360 static function componentPresent( &$returnProperties, $prefix ) {
5361 foreach ($returnProperties as $name => $dontCare ) {
5362 if (substr($name, 0, strlen($prefix)) == $prefix) {
5370 * Builds the necessary structures for all fields that are similar to option value lookups
5372 * @param $name string the name of the field
5373 * @param $op string the sql operator, this function should handle ALL SQL operators
5374 * @param $value string|integer|array depends on the operator and who's calling the query builder
5375 * @param $grouping int the index where to place the where clause
5376 * @param $selectValues
5377 * @param $field array an array that contains various properties of the field identified by $name
5378 * @param $label string The label for this field element
5379 * @param $dataType string The data type for this element
5381 * @param bool $useIDsOnly
5383 * @internal param array $selectValue the key value pairs for this element. This allows us to use this function for things besides option-value pairs
5384 * @return void adds the where clause and qill to the query object
5386 function optionValueQuery(
5394 $dataType = 'String',
5398 if (!empty($selectValues) && !is_array($value) && !empty($selectValues[$value])) {
5399 $qill = $selectValues[$value];
5405 $pseudoFields = array('email_greeting', 'postal_greeting', 'addressee', 'gender_id', 'prefix_id', 'suffix_id', 'communication_style_id');
5407 if (is_numeric($value)) {
5408 $qill = $selectValues[(int ) $value];
5410 elseif ($op == 'IN' ||
$op == 'NOT IN') {
5411 if (is_array($value)) {
5413 $newValues = array();
5414 foreach ($value as $k => $v) {
5415 $intVals[$k] = (int) $k;
5416 $newValues[] = $selectValues[(int) $k];
5419 $value = (in_array($name, $pseudoFields)) ?
$intVals : $newValues;
5420 $qill = implode(', ', $newValues);
5423 elseif (!array_key_exists($value, $selectValues)) {
5424 // its a string, lets get the int value
5425 $value = array_search($value, $selectValues);
5428 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5429 if ($tableName == 'civicrm_contact') {
5430 $wc = "contact_a.$fieldName";
5433 $wc = "$tableName.id";
5437 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5440 if (in_array($name, $pseudoFields)) {
5441 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5442 $wc = "contact_a.{$name}_id";
5444 $dataType = 'Positive';
5445 $value = (!$value) ?
0 : $value;
5448 $this->_qill
[$grouping][] = $label . " $op '$qill'";
5449 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' ||
$op == 'RLIKE')) ?
'=' : $op;
5450 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5454 * function to check and explode a user defined numeric string into an array
5455 * this was the protocol used by search builder in the old old days before we had
5456 * super nice js widgets to do the hard work
5458 * @param string $string
5459 * @param string $dataType the dataType we should check for the values, default integer
5461 * @return bool|array if string does not match the patter
5462 * array of numeric values if string does match the pattern
5465 static function parseSearchBuilderString($string, $dataType = 'Integer') {
5466 $string = trim($string);
5467 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5471 $string = substr($string, 1, -1);
5472 $values = explode(',', $string);
5473 if (empty($values)) {
5477 $returnValues = array();
5478 foreach ($values as $v) {
5479 if ($dataType == 'Integer' && ! is_numeric($v)) {
5482 else if ($dataType == 'String' && ! is_string($v)) {
5485 $returnValues[] = trim($v);
5488 if (empty($returnValues)) {
5492 return $returnValues;
5496 * convert the pseudo constants id's to their names
5498 * @param CRM_Core_DAO dao
5499 * @param bool $return
5503 function convertToPseudoNames(&$dao, $return = FALSE) {
5504 if (empty($this->_pseudoConstantsSelect
)) {
5508 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5509 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5513 if (property_exists($dao, $value['idCol'])) {
5514 $val = $dao->$value['idCol'];
5516 if (CRM_Utils_System
::isNull($val)) {
5519 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5521 $idColumn = "{$key}_id";
5522 $dao->$idColumn = $val;
5524 if ($key == 'state_province_name') {
5525 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5528 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5531 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5532 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5534 // FIX ME: we should potentially move this to component Query and write a wrapper function that
5535 // handles pseudoconstant fixes for all component
5536 elseif ($value['pseudoField'] == 'participant_role') {
5537 $viewRoles = array();
5538 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val) as $k => $v) {
5539 $viewRoles[] = CRM_Event_PseudoConstant
::participantRole($v);
5541 $dao->$key = implode(', ', $viewRoles);
5544 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5545 $dao->$key = $labels[$val];
5548 // return converted values in array format
5550 if (strpos($key, '-') !== FALSE) {
5551 $keyVal = explode('-', $key);
5552 $current = &$values;
5553 $lastElement = array_pop($keyVal);
5554 foreach ($keyVal as $v) {
5555 if (!array_key_exists($v, $current)) {
5556 $current[$v] = array();
5558 $current = &$current[$v];
5560 $current[$lastElement] = $dao->$key;
5563 $values[$key] = $dao->$key;
5572 * include pseudo fields LEFT JOIN
5573 * @param string|array $sort can be a object or string
5577 function includePseudoFieldsJoin($sort) {
5578 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5581 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5584 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5585 if (!empty($value['table'])) {
5586 $regex = "/({$value['table']}\.|{$name})/";
5587 if (preg_match($regex, $sort)) {
5588 $this->_elemnt
[$value['element']] = 1;
5589 $this->_select
[$value['element']] = $value['select'];
5590 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5591 $present[$value['table']] = $value['join'];
5595 $presentSimpleFrom = $present;
5597 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5598 array_key_exists('civicrm_country', $presentSimpleFrom)) {
5599 unset($presentSimpleFrom['civicrm_country']);
5601 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5602 array_key_exists('civicrm_country', $present)) {
5603 unset($present['civicrm_country']);
5606 $presentClause = $presentSimpleFromClause = NULL;
5607 if (!empty($present)) {
5608 $presentClause = implode(' ', $present);
5610 if (!empty($presentSimpleFrom)) {
5611 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5614 $this->_fromClause
= $this->_fromClause
. $presentClause;
5615 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5617 return array($presentClause, $presentSimpleFromClause);