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')) {
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";
1134 if ($tableName != 'civicrm_phone') {
1135 $this->_tables
[$tName] .= " AND `$tName`.$lCond";
1137 elseif (is_numeric($name)) {
1138 $this->_select
[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1141 // this special case to add phone type
1143 $phoneTypeCondition = " AND `$tName`.$cond ";
1144 //gross hack to pickup corrupted data also, CRM-7603
1145 if (strpos($cond, 'phone_type_id') !== FALSE) {
1146 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1148 $this->_tables
[$tName] .= $phoneTypeCondition;
1151 //build locationType join
1152 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1155 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1159 case 'civicrm_state_province':
1160 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1161 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1162 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1164 $this->_whereTables
["{$name}-address"] = $addressJoin;
1168 case 'civicrm_country':
1169 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1170 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1171 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1173 $this->_whereTables
["{$name}-address"] = $addressJoin;
1177 case 'civicrm_county':
1178 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1179 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1180 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1182 $this->_whereTables
["{$name}-address"] = $addressJoin;
1188 $this->_whereTables
["{$name}-address"] = $addressJoin;
1197 // add location type join
1198 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1199 $this->_tables
[$locationTypeName] = $ltypeJoin;
1201 // table should be present in $this->_whereTables,
1202 // to add its condition in location type join, CRM-3939.
1203 if ($addWhereCount) {
1204 $locClause = array();
1205 foreach ($this->_whereTables
as $tableName => $clause) {
1206 if (!empty($locationTypeJoin[$tableName])) {
1207 $locClause[] = $locationTypeJoin[$tableName];
1211 if (!empty($locClause)) {
1212 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1217 if (!empty($addressCustomFieldIds)) {
1218 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1219 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1220 foreach ($locTypeName as $name => $dnc) {
1221 $this->_locationSpecificCustomFields
[$cfID] = array($name, array_search($name, $locationTypes));
1222 $fieldName = "$name-custom_{$cfID}";
1223 $tName = "$name-address-custom-{$cfID}";
1224 $aName = "`$name-address-custom-{$cfID}`";
1225 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1226 $this->_element
["{$tName}_id"] = 1;
1227 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1228 $this->_element
[$fieldName] = 1;
1229 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1236 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
1242 function addMultipleElements() {
1243 if (empty($this->_returnProperties
['website'])) {
1246 if (!is_array($this->_returnProperties
['website'])) {
1250 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1251 foreach ($elements as $elementFullName => $dontCare) {
1252 $tName = "website-{$key}-{$elementFullName}";
1253 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1254 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1255 $this->_element
["{$tName}_id"] = 1;
1256 $this->_element
["{$tName}"] = 1;
1258 $type = "website-{$key}-website_type_id";
1259 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1260 $this->_element
[$type] = 1;
1261 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1267 * generate the query based on what type of query we need
1269 * @param boolean $count
1270 * @param boolean $sortByChar
1271 * @param boolean $groupContacts
1272 * @param boolean $onlyDeleted
1274 * @return array sql query parts as an array
1277 function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1278 // build permission clause
1279 $this->generatePermissionClause($onlyDeleted, $count);
1282 if (isset($this->_rowCountClause
)) {
1283 $select = "SELECT {$this->_rowCountClause}";
1284 } else if (isset($this->_distinctComponentClause
)) {
1285 // we add distinct to get the right count for components
1286 // for the more complex result set, we use GROUP BY the same id
1288 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1291 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1293 $from = $this->_simpleFromClause
;
1294 if ($this->_useDistinct
) {
1295 $this->_useGroupBy
= TRUE;
1298 elseif ($sortByChar) {
1299 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1300 $from = $this->_simpleFromClause
;
1302 elseif ($groupContacts) {
1303 $select = 'SELECT contact_a.id as id';
1304 if ($this->_useDistinct
) {
1305 $this->_useGroupBy
= TRUE;
1307 $from = $this->_simpleFromClause
;
1310 if (!empty($this->_paramLookup
['group'])) {
1311 // make sure there is only one element
1312 // this is used when we are running under smog and need to know
1313 // how the contact was added (CRM-1203)
1314 if ((count($this->_paramLookup
['group']) == 1) &&
1315 (count($this->_paramLookup
['group'][0][2]) == 1)
1317 $groups = array_keys($this->_paramLookup
['group'][0][2]);
1318 $groupId = $groups[0];
1320 //check if group is saved search
1321 $group = new CRM_Contact_BAO_Group();
1322 $group->id
= $groupId;
1325 if (!isset($group->saved_search_id
)) {
1326 $tbName = "`civicrm_group_contact-{$groupId}`";
1327 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1328 $this->_element
['group_contact_id'] = 1;
1329 $this->_select
['status'] = "$tbName.status as status";
1330 $this->_element
['status'] = 1;
1333 $this->_useGroupBy
= TRUE;
1335 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1336 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1338 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1339 $this->_useDistinct
= FALSE;
1340 $this->_useGroupBy
= TRUE;
1344 $select = "SELECT ";
1345 if (isset($this->_distinctComponentClause
)) {
1346 $select .= "{$this->_distinctComponentClause}, ";
1348 $select .= implode(', ', $this->_select
);
1349 $from = $this->_fromClause
;
1353 if (!empty($this->_whereClause
)) {
1354 $where = "WHERE {$this->_whereClause}";
1357 if (!empty($this->_permissionWhereClause
)) {
1358 if (empty($where)) {
1359 $where = "WHERE $this->_permissionWhereClause";
1362 $where = "$where AND $this->_permissionWhereClause";
1367 if (!empty($this->_having
)) {
1368 foreach ($this->_having
as $havingSets) {
1369 foreach ($havingSets as $havingSet) {
1370 $havingValue[] = $havingSet;
1373 $having = ' HAVING ' . implode(' AND ', $havingValue);
1376 // if we are doing a transform, do it here
1377 // use the $from, $where and $having to get the contact ID
1378 if ($this->_displayRelationshipType
) {
1379 $this->filterRelatedContacts($from, $where, $having);
1382 return array($select, $from, $where, $having);
1391 function &getWhereValues($name, $grouping) {
1393 foreach ($this->_params
as $values) {
1394 if ($values[0] == $name && $values[3] == $grouping) {
1407 static function fixDateValues($relative, &$from, &$to) {
1409 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1414 * @param $formValues
1415 * @param int $wildcard
1416 * @param bool $useEquals
1420 static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE) {
1422 if (empty($formValues)) {
1426 foreach ($formValues as $id => $values) {
1427 if ($id == 'privacy') {
1428 if (is_array($formValues['privacy'])) {
1429 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1430 foreach ($formValues['privacy'] as $key => $value) {
1432 $params[] = array($key, $op, $value, 0, 0);
1437 elseif ($id == 'email_on_hold') {
1438 if ($formValues['email_on_hold']['on_hold']) {
1439 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1442 elseif (preg_match('/_date_relative$/', $id) ||
1443 $id == 'event_relative' ||
1444 $id == 'case_from_relative' ||
1445 $id == 'case_to_relative'
1447 if ($id == 'event_relative') {
1448 $fromRange = 'event_start_date_low';
1449 $toRange = 'event_end_date_high';
1451 else if ($id == 'case_from_relative') {
1452 $fromRange = 'case_from_start_date_low';
1453 $toRange = 'case_from_start_date_high';
1455 else if ($id == 'case_to_relative') {
1456 $fromRange = 'case_to_end_date_low';
1457 $toRange = 'case_to_end_date_high';
1460 $dateComponent = explode('_date_relative', $id);
1461 $fromRange = "{$dateComponent[0]}_date_low";
1462 $toRange = "{$dateComponent[0]}_date_high";
1465 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1466 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1471 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals);
1476 $params[] = $values;
1485 * @param int $wildcard
1486 * @param bool $useEquals
1488 * @return array|null
1490 static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE) {
1491 // skip a few search variables
1492 static $skipWhere = NULL;
1493 static $likeNames = NULL;
1496 if (CRM_Utils_System
::isNull($values)) {
1502 'task', 'radio_ts', 'uf_group_id',
1503 'component_mode', 'qfKey', 'operator',
1504 'display_relationship_type',
1508 if (in_array($id, $skipWhere) ||
1509 substr($id, 0, 4) == '_qf_' ||
1510 substr($id, 0, 7) == 'hidden_'
1516 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1519 // email comes in via advanced search
1520 // so use wildcard always
1521 if ($id == 'email') {
1525 if (!$useEquals && in_array($id, $likeNames)) {
1526 $result = array($id, 'LIKE', $values, 0, 1);
1528 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1529 $result = array($id, 'LIKE', $values, 0, 0);
1531 elseif ($id == 'group') {
1532 if (is_array($values)) {
1533 foreach ($values as $groupIds => $val) {
1535 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1536 if (strlen($matches[1]) > 0) {
1537 $values[$matches[1]] = 1;
1538 unset($values[$groupIds]);
1544 $groupIds = explode(',', $values);
1546 foreach ($groupIds as $groupId) {
1547 $values[$groupId] = 1;
1551 $result = array($id, 'IN', $values, 0, 0);
1553 elseif ($id == 'contact_tags' ||
$id == 'tag') {
1554 if (!is_array($values)) {
1555 $tagIds = explode(',', $values);
1557 foreach ($tagIds as $tagId) {
1558 $values[$tagId] = 1;
1561 $result = array($id, 'IN', $values, 0, 0);
1563 elseif ($id == 'contact_type') {
1564 $result = array($id, 'IN', $values, 0, $wildcard);
1567 $result = array($id, '=', $values, 0, $wildcard);
1576 function whereClauseSingle(&$values) {
1577 // do not process custom fields or prefixed contact ids or component params
1578 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1579 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1580 (substr($values[0], 0, 13) == 'contribution_') ||
1581 (substr($values[0], 0, 6) == 'event_') ||
1582 (substr($values[0], 0, 12) == 'participant_') ||
1583 (substr($values[0], 0, 7) == 'member_') ||
1584 (substr($values[0], 0, 6) == 'grant_') ||
1585 (substr($values[0], 0, 7) == 'pledge_') ||
1586 (substr($values[0], 0, 5) == 'case_') ||
1587 (substr($values[0], 0, 10) == 'financial_') ||
1588 (substr($values[0], 0, 11) == 'membership_')
1593 // skip for hook injected fields / params
1594 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1595 if (array_key_exists($values[0], $extFields)) {
1599 switch ($values[0]) {
1600 case 'deleted_contacts':
1601 $this->deletedContacts($values);
1604 case 'contact_type':
1605 $this->contactType($values);
1608 case 'contact_sub_type':
1609 $this->contactSubType($values);
1613 $this->group($values);
1617 // so we resolve this into a list of groups & proceed as if they had been
1619 list($name, $op, $value, $grouping, $wildcard) = $values;
1620 $values[0] = 'group';
1622 $this->_paramLookup
['group'][0][0] ='group';
1623 $this->_paramLookup
['group'][0][1] = 'IN';
1624 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1625 $this->group($values);
1628 // case tag comes from find contacts
1630 $this->tagSearch($values);
1634 case 'contact_tags':
1635 $this->tag($values);
1640 case 'note_subject':
1641 $this->notes($values);
1645 $this->ufUser($values);
1649 case 'display_name':
1650 $this->sortName($values);
1654 $this->email($values);
1657 case 'phone_numeric':
1658 $this->phone_numeric($values);
1661 case 'phone_phone_type_id':
1662 case 'phone_location_type_id':
1663 $this->phone_option_group($values);
1666 case 'street_address':
1667 $this->street_address($values);
1670 case 'street_number':
1671 $this->street_number($values);
1674 case 'sortByCharacter':
1675 $this->sortByCharacter($values);
1678 case 'location_type':
1679 $this->locationType($values);
1683 $this->county($values);
1686 case 'state_province':
1687 $this->stateProvince($values);
1691 $this->country($values, FALSE);
1695 case 'postal_code_low':
1696 case 'postal_code_high':
1697 $this->postalCode($values);
1700 case 'activity_date':
1701 case 'activity_date_low':
1702 case 'activity_date_high':
1703 case 'activity_role':
1704 case 'activity_status':
1705 case 'followup_parent_id':
1707 case 'activity_subject':
1708 case 'test_activities':
1709 case 'activity_type_id':
1710 case 'activity_type':
1711 case 'activity_survey_id':
1712 case 'activity_tags':
1713 case 'activity_taglist':
1714 case 'activity_test':
1715 case 'activity_campaign_id':
1716 case 'activity_engagement_level':
1718 case 'activity_result':
1719 case 'source_contact':
1720 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1723 case 'birth_date_low':
1724 case 'birth_date_high':
1725 case 'deceased_date_low':
1726 case 'deceased_date_high':
1727 $this->demographics($values);
1730 case 'log_date_low':
1731 case 'log_date_high':
1732 $this->modifiedDates($values);
1736 $this->changeLog($values);
1739 case 'do_not_phone':
1740 case 'do_not_email':
1743 case 'do_not_trade':
1745 $this->privacy($values);
1748 case 'privacy_options':
1749 $this->privacyOptions($values);
1752 case 'privacy_operator':
1753 case 'privacy_toggle':
1754 // these are handled by privacy options
1757 case 'preferred_communication_method':
1758 $this->preferredCommunication($values);
1761 case 'relation_type_id':
1762 case 'relation_start_date_high':
1763 case 'relation_start_date_low':
1764 case 'relation_end_date_high':
1765 case 'relation_end_date_low':
1766 case 'relation_target_name':
1767 case 'relation_status':
1768 case 'relation_date_low':
1769 case 'relation_date_high':
1770 $this->relationship($values);
1771 $this->_relationshipValuesAdded
= TRUE;
1774 case 'task_status_id':
1775 $this->task($values);
1779 // since this case is handled with the above
1782 case 'prox_distance':
1783 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1786 case 'prox_street_address':
1788 case 'prox_postal_code':
1789 case 'prox_state_province_id':
1790 case 'prox_country_id':
1791 // handled by the proximity_distance clause
1795 $this->restWhere($values);
1801 * Given a list of conditions in params generate the required
1807 function whereClause() {
1808 $this->_where
[0] = array();
1809 $this->_qill
[0] = array();
1811 $this->includeContactIds();
1812 if (!empty($this->_params
)) {
1813 foreach (array_keys($this->_params
) as $id) {
1814 if (empty($this->_params
[$id][0])) {
1817 // check for both id and contact_id
1818 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
1820 $this->_params
[$id][1] == 'IS NULL' ||
1821 $this->_params
[$id][1] == 'IS NOT NULL'
1823 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]}";
1825 elseif (is_array($this->_params
[$id][2])) {
1826 $idList = implode("','", $this->_params
[$id][2]);
1827 //why on earth do they put ' in the middle & not on the outside? We have to assume it's
1828 //to support 'something' so lets add them conditionally to support the api (which is a tested flow
1829 // so if you are looking to alter this check api test results
1830 if (strpos(trim($idList), "'") > 0) {
1831 $idList = "'" . $idList . "'";
1834 $this->_where
[0][] = "contact_a.id IN ({$idList})";
1837 $this->_where
[0][] = self
::buildClause("contact_a.id", "{$this->_params[$id][1]}", "{$this->_params[$id][2]}");
1841 $this->whereClauseSingle($this->_params
[$id]);
1845 CRM_Core_Component
::alterQuery($this, 'where');
1847 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
1850 if ($this->_customQuery
) {
1851 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1852 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1853 if (!empty($this->_customQuery
->_where
)) {
1854 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
1857 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
1861 $andClauses = array();
1864 if (!empty($this->_where
)) {
1865 foreach ($this->_where
as $grouping => $values) {
1866 if ($grouping > 0 && !empty($values)) {
1867 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1872 if (!empty($this->_where
[0])) {
1873 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
1875 if (!empty($clauses)) {
1876 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1879 if ($validClauses > 1) {
1880 $this->_useDistinct
= TRUE;
1884 return implode(' AND ', $andClauses);
1892 function restWhere(&$values) {
1893 $name = CRM_Utils_Array
::value(0, $values);
1894 $op = CRM_Utils_Array
::value(1, $values);
1895 $value = CRM_Utils_Array
::value(2, $values);
1896 $grouping = CRM_Utils_Array
::value(3, $values);
1897 $wildcard = CRM_Utils_Array
::value(4, $values);
1899 if (isset($grouping) && empty($this->_where
[$grouping])) {
1900 $this->_where
[$grouping] = array();
1903 $multipleFields = array('url');
1905 //check if the location type exits for fields
1907 $locType = explode('-', $name);
1909 if (!in_array($locType[0], $multipleFields)) {
1910 //add phone type if exists
1911 if (isset($locType[2]) && $locType[2]) {
1912 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
1916 $field = CRM_Utils_Array
::value($name, $this->_fields
);
1919 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
1928 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
1929 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1931 if (substr($name, 0, 14) === 'state_province') {
1932 if (isset($locType[1]) && is_numeric($locType[1])) {
1934 $aName = "{$locationType[$locType[1]]}-address";
1935 $where = "`$aName`.state_province_id";
1938 $where = "civicrm_address.state_province_id";
1941 $states = CRM_Core_PseudoConstant
::stateProvince();
1942 if (is_numeric($value)) {
1943 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1944 $value = $states[(int ) $value];
1947 $intVal = CRM_Utils_Array
::key($value, $states);
1948 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1951 $this->_qill
[$grouping][] = ts('State') . " $op '$value'";
1954 $this->_qill
[$grouping][] = ts('State') . " ($lType) $op '$value'";
1957 elseif (!empty($field['pseudoconstant'])) {
1958 $this->optionValueQuery(
1959 $name, $op, $value, $grouping,
1960 CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', $field['name']),
1966 if ($name == 'gender_id') {
1967 self
::$_openedPanes[ts('Demographics')] = TRUE;
1970 elseif (substr($name, 0, 7) === 'country') {
1971 if (isset($locType[1]) && is_numeric($locType[1])) {
1973 $aName = "{$locationType[$locType[1]]}-address";
1974 $where = "`$aName`.country_id";
1977 $where = "civicrm_address.country_id";
1980 $countries = CRM_Core_PseudoConstant
::country();
1981 if (is_numeric($value)) {
1982 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1983 $value = $countries[(int ) $value];
1986 $intVal = CRM_Utils_Array
::key($value, $countries);
1987 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1991 $this->_qill
[$grouping][] = ts('Country') . " $op '$value'";
1994 $this->_qill
[$grouping][] = ts('Country') . " ($lType) $op '$value'";
1997 elseif (substr($name, 0, 6) === 'county') {
1998 if (isset($locType[1]) && is_numeric($locType[1])) {
2000 $aName = "{$locationType[$locType[1]]}-address";
2001 $where = "`$aName`.county_id";
2004 $where = "civicrm_address.county_id";
2007 $counties = CRM_Core_PseudoConstant
::county();
2008 if (is_numeric($value)) {
2009 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2010 $value = $counties[(int ) $value];
2013 $intVal = CRM_Utils_Array
::key($value, $counties);
2014 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
2018 $this->_qill
[$grouping][] = ts('County') . " $op '$value'";
2021 $this->_qill
[$grouping][] = ts('County') . " ($lType) $op '$value'";
2024 elseif ($name === 'world_region') {
2025 $field['where'] = 'civicrm_worldregion.id';
2026 $this->optionValueQuery(
2027 $name, $op, $value, $grouping,
2028 CRM_Core_PseudoConstant
::worldRegion(),
2035 elseif ($name === 'birth_date') {
2036 $date = CRM_Utils_Date
::processDate($value);
2037 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
2040 $date = CRM_Utils_Date
::customFormat($date);
2041 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
2044 $this->_qill
[$grouping][] = "$field[title] $op";
2046 self
::$_openedPanes[ts('Demographics')] = TRUE;
2048 elseif ($name === 'deceased_date') {
2049 $date = CRM_Utils_Date
::processDate($value);
2050 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
2052 $date = CRM_Utils_Date
::customFormat($date);
2053 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
2056 $this->_qill
[$grouping][] = "$field[title] $op";
2058 self
::$_openedPanes[ts('Demographics')] = TRUE;
2060 elseif ($name === 'is_deceased') {
2061 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
2062 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2063 self
::$_openedPanes[ts('Demographics')] = TRUE;
2065 elseif ($name === 'contact_id') {
2066 if (is_int($value)) {
2067 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2068 $this->_qill
[$grouping][] = "$field[title] $op $value";
2071 elseif ($name === 'name') {
2072 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2074 $value = "%$value%";
2077 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2078 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2079 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2081 elseif ($name === 'current_employer') {
2082 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2084 $value = "%$value%";
2087 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
2088 $ceWhereClause = self
::buildClause($wc, $op,
2091 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2092 $this->_where
[$grouping][] = $ceWhereClause;
2093 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2095 elseif ($name === 'email_greeting') {
2096 $filterCondition = array('greeting_type' => 'email_greeting');
2097 $this->optionValueQuery(
2098 $name, $op, $value, $grouping,
2099 CRM_Core_PseudoConstant
::greeting($filterCondition),
2101 ts('Email Greeting')
2104 elseif ($name === 'postal_greeting') {
2105 $filterCondition = array('greeting_type' => 'postal_greeting');
2106 $this->optionValueQuery(
2107 $name, $op, $value, $grouping,
2108 CRM_Core_PseudoConstant
::greeting($filterCondition),
2110 ts('Postal Greeting')
2113 elseif ($name === 'addressee') {
2114 $filterCondition = array('greeting_type' => 'addressee');
2115 $this->optionValueQuery(
2116 $name, $op, $value, $grouping,
2117 CRM_Core_PseudoConstant
::greeting($filterCondition),
2122 elseif (substr($name, 0, 4) === 'url-') {
2123 $tName = 'civicrm_website';
2124 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2125 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2127 $value = "%$value%";
2131 $wc = 'civicrm_website.url';
2132 $this->_where
[$grouping][] = $d = self
::buildClause($wc, $op, $value);
2133 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2135 elseif ($name === 'contact_is_deleted') {
2136 $this->_where
[$grouping][] = self
::buildClause("contact_a.is_deleted", $op, $value);
2137 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2140 if (is_array($value)) {
2141 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2142 // for api style operators for functions that hit this point without worrying about regression
2143 // (the previous comments indicated the condition for hitting this point were unknown
2144 // per CRM-14743 we are adding modified_date & created_date operator support
2145 $operations = array_keys($value);
2146 foreach ($operations as $operator) {
2147 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2148 // we don't know when this might happen
2149 CRM_Core_Error
::fatal();
2152 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($name, $value, NULL);
2153 //since this is not currently being called by the form layer we can skip worrying about the 'qill' for now
2157 if (!empty($field['where'])) {
2159 $value = $strtolower($value);
2162 $value = "%$value%";
2166 if (isset($locType[1]) &&
2167 is_numeric($locType[1])
2171 //get the location name
2172 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2174 $where = "`$tName`.$fldName";
2176 $this->_where
[$grouping][] = self
::buildClause("LOWER($where)", $op, $value);
2177 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2178 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2179 $this->_qill
[$grouping][] = "$field[title] $op '$value'";
2182 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2183 if ($tableName == 'civicrm_contact') {
2184 $fieldName = "LOWER(contact_a.{$fieldName})";
2187 if ($op != 'IN' && !is_numeric($value)) {
2188 $fieldName = "LOWER({$field['where']})";
2191 $fieldName = "{$field['where']}";
2196 if (!empty($field['type'])) {
2197 $type = CRM_Utils_Type
::typeToString($field['type']);
2200 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2201 $this->_qill
[$grouping][] = "$field[title] $op $value";
2206 if ($setTables && isset($field['where'])) {
2207 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2208 if (isset($tableName)) {
2209 $this->_tables
[$tableName] = 1;
2210 $this->_whereTables
[$tableName] = 1;
2223 static function getLocationTableName(&$where, &$locType) {
2224 if (isset($locType[1]) && is_numeric($locType[1])) {
2225 list($tbName, $fldName) = explode(".", $where);
2227 //get the location name
2228 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2229 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2230 if (in_array($locType[0], $specialFields)) {
2231 //hack to fix / special handing for phone_ext
2232 if ($locType[0] == 'phone_ext') {
2233 $locType[0] = 'phone';
2235 if (isset($locType[2]) && $locType[2]) {
2236 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2239 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2242 elseif (in_array($locType[0],
2244 'address_name', 'street_address', 'supplemental_address_1', 'supplemental_address_2',
2245 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
2248 //fix for search by profile with address fields.
2249 $tName = "{$locationType[$locType[1]]}-address";
2251 elseif ($locType[0] == 'on_hold') {
2252 $tName = "{$locationType[$locType[1]]}-email";
2255 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2257 $tName = str_replace(' ', '_', $tName);
2258 return array($tName, $fldName);
2260 CRM_Core_Error
::fatal();
2264 * Given a result dao, extract the values and return that array
2266 * @param Object $dao
2268 * @return array values for this query
2270 function store($dao) {
2273 foreach ($this->_element
as $key => $dontCare) {
2274 if (property_exists($dao, $key)) {
2275 if (strpos($key, '-') !== FALSE) {
2276 $values = explode('-', $key);
2277 $lastElement = array_pop($values);
2279 $cnt = count($values);
2281 foreach ($values as $v) {
2282 if (!array_key_exists($v, $current)) {
2283 $current[$v] = array();
2285 //bad hack for im_provider
2286 if ($lastElement == 'provider_id') {
2287 if ($count < $cnt) {
2288 $current = &$current[$v];
2291 $lastElement = "{$v}_{$lastElement}";
2295 $current = &$current[$v];
2300 $current[$lastElement] = $dao->$key;
2303 $value[$key] = $dao->$key;
2311 * getter for tables array
2317 return $this->_tables
;
2321 * Where tables is sometimes used to create the from clause, but, not reliably, set this AND set tables
2322 * It's unclear the intent - there is a 'simpleFrom' clause which takes whereTables into account & a fromClause which doesn't
2323 * logic may have eroded
2326 function whereTables() {
2327 return $this->_whereTables
;
2331 * generate the where clause (used in match contacts and permissions)
2333 * @param array $params
2334 * @param array $fields
2335 * @param array $tables
2336 * @param $whereTables
2337 * @param boolean $strict
2343 static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2344 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2348 $tables = array_merge($query->tables(), $tables);
2349 $whereTables = array_merge($query->whereTables(), $whereTables);
2351 return $query->_whereClause
;
2355 * create the from clause
2357 * @param array $tables tables that need to be included in this from clause
2358 * if null, return mimimal from clause (i.e. civicrm_contact)
2359 * @param array $inner tables that should be inner-joined
2360 * @param array $right tables that should be right-joined
2362 * @param bool $primaryLocation
2365 * @return string the from clause
2369 static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2371 $from = ' FROM civicrm_contact contact_a';
2372 if (empty($tables)) {
2376 if (!empty($tables['civicrm_worldregion'])) {
2377 $tables = array_merge(array('civicrm_country' => 1), $tables);
2380 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2381 CRM_Utils_Array
::value('civicrm_county', $tables)
2382 ) && empty($tables['civicrm_address'])) {
2383 $tables = array_merge(array('civicrm_address' => 1),
2388 // add group_contact table if group table is present
2389 if (!empty($tables['civicrm_group']) && empty($tables['civicrm_group_contact'])) {
2390 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
2393 // add group_contact and group table is subscription history is present
2394 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2395 $tables = array_merge(array(
2396 'civicrm_group' => 1,
2397 'civicrm_group_contact' => 1,
2403 // to handle table dependencies of components
2404 CRM_Core_Component
::tableNames($tables);
2405 // to handle table dependencies of hook injected tables
2406 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2408 //format the table list according to the weight
2409 $info = CRM_Core_TableHierarchy
::info();
2411 foreach ($tables as $key => $value) {
2413 if (strpos($key, '-') !== FALSE) {
2414 $keyArray = explode('-', $key);
2415 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2417 elseif (strpos($key, '_') !== FALSE) {
2418 $keyArray = explode('_', $key);
2419 if (is_numeric(array_pop($keyArray))) {
2420 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2423 $k = CRM_Utils_Array
::value($key, $info, 99);
2427 $k = CRM_Utils_Array
::value($key, $info, 99);
2429 $tempTable[$k . ".$key"] = $key;
2432 $newTables = array();
2433 foreach ($tempTable as $key) {
2434 $newTables[$key] = $tables[$key];
2437 $tables = $newTables;
2439 foreach ($tables as $name => $value) {
2444 if (!empty($inner[$name])) {
2447 elseif (!empty($right[$name])) {
2455 // if there is already a join statement in value, use value itself
2456 if (strpos($value, 'JOIN')) {
2457 $from .= " $value ";
2460 $from .= " $side JOIN $name ON ( $value ) ";
2465 case 'civicrm_address':
2466 if ($primaryLocation) {
2467 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2470 //CRM-14263 further handling of address joins further down...
2471 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2475 case 'civicrm_phone':
2476 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2479 case 'civicrm_email':
2480 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2484 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2488 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2489 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2490 $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)";
2493 case 'civicrm_openid':
2494 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2497 case 'civicrm_worldregion':
2498 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2499 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2502 case 'civicrm_location_type':
2503 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2506 case 'civicrm_group':
2507 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2510 case 'civicrm_group_contact':
2511 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2514 case 'civicrm_activity':
2515 case 'civicrm_activity_tag':
2516 case 'activity_type':
2517 case 'activity_status':
2519 case 'civicrm_activity_contact':
2520 case 'source_contact':
2521 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2524 case 'civicrm_entity_tag':
2525 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2526 civicrm_entity_tag.entity_id = contact_a.id ) ";
2529 case 'civicrm_note':
2530 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2531 contact_a.id = civicrm_note.entity_id ) ";
2534 case 'civicrm_subscription_history':
2535 $from .= " $side JOIN civicrm_subscription_history
2536 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2537 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2540 case 'civicrm_relationship':
2541 if (self
::$_relType == 'reciprocal') {
2542 if (self
::$_relationshipTempTable) {
2543 // we have a temptable to join on
2544 $tbl = self
::$_relationshipTempTable;
2545 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2548 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2549 $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)";
2552 elseif (self
::$_relType == 'b') {
2553 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2554 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2557 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2558 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2563 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2564 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2568 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2571 case 'civicrm_grant':
2572 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2575 case 'civicrm_website':
2576 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2580 $locationTypeName = '';
2581 if (strpos($name, '-address') != 0) {
2582 $locationTypeName = 'address';
2584 elseif (strpos($name, '-phone') != 0) {
2585 $locationTypeName = 'phone';
2587 elseif (strpos($name, '-email') != 0) {
2588 $locationTypeName = 'email';
2590 if ($locationTypeName) {
2591 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2592 $parts = explode('-', $name);
2593 $locationID = array_search($parts[0], CRM_Core_BAO_Address
::buildOptions('location_type_id', 'get', array('name' => $parts[0])));
2594 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2597 $from .= CRM_Core_Component
::from($name, $mode, $side);
2599 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2608 * WHERE / QILL clause for deleted_contacts
2614 function deletedContacts($values) {
2615 list($_, $_, $value, $grouping, $_) = $values;
2617 // *prepend* to the relevant grouping as this is quite an important factor
2618 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2623 * where / qill clause for contact_type
2630 function contactType(&$values) {
2631 list($name, $op, $value, $grouping, $wildcard) = $values;
2633 $subTypes = array();
2636 // account for search builder mapping multiple values
2637 if (!is_array($value)) {
2638 $values = self
::parseSearchBuilderString($value, 'String');
2639 if (is_array($values)) {
2640 $value = array_flip($values);
2644 if (is_array($value)) {
2645 foreach ($value as $k => $v) {
2650 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2651 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2654 if (!empty($subType)) {
2655 $subTypes[$subType] = 1;
2657 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2662 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2663 $contactType = $contactTypeANDSubType[0];
2664 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2665 if (!empty($subType)) {
2666 $subTypes[$subType] = 1;
2668 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2672 if (!empty($clause)) {
2674 if ($op == 'IN' ||
$op == 'NOT IN') {
2675 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2678 $type = array_pop($clause);
2679 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2682 $this->_qill
[$grouping][] = ts('Contact Type') . ' - ' . implode(' ' . ts('or') . ' ', $quill);
2684 if (!empty($subTypes)) {
2685 $this->includeContactSubTypes($subTypes, $grouping);
2691 * where / qill clause for contact_sub_type
2698 function contactSubType(&$values) {
2699 list($name, $op, $value, $grouping, $wildcard) = $values;
2700 $this->includeContactSubTypes($value, $grouping);
2707 function includeContactSubTypes($value, $grouping) {
2710 $alias = "contact_a.contact_sub_type";
2712 if (is_array($value)) {
2713 foreach ($value as $k => $v) {
2715 $clause[$k] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($k, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2720 $clause[$value] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2723 if (!empty($clause)) {
2724 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2725 $this->_qill
[$grouping][] = ts('Contact Subtype') . ' - ' . implode(' ' . ts('or') . ' ', array_keys($clause));
2730 * where / qill clause for groups
2737 function group(&$values) {
2738 list($name, $op, $value, $grouping, $wildcard) = $values;
2740 if (count($value) > 1) {
2741 $this->_useDistinct
= TRUE;
2744 $groupNames = CRM_Core_PseudoConstant
::group();
2745 $groupIds = implode(',', array_keys($value));
2748 foreach ($value as $id => $dontCare) {
2749 if (array_key_exists($id, $groupNames) && $dontCare) {
2750 $names[] = $groupNames[$id];
2756 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2758 is_array($gcsValues[2])
2760 foreach ($gcsValues[2] as $k => $v) {
2762 if ($k == 'Added') {
2765 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2770 $statii[] = '"Added"';
2775 if (count($value) == 1 &&
2776 count($statii) == 1 &&
2777 $statii[0] == '"Added"'
2779 // check if smart group, if so we can get rid of that one additional
2781 $groupIDs = array_keys($value);
2783 if (!empty($groupIDs[0]) &&
2784 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
2794 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2795 $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 ) )";
2798 $qill = ts('Contacts %1', array(1 => $op));
2799 $qill .= ' ' . implode(' ' . ts('or') . ' ', $names);
2801 $groupClause = NULL;
2804 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2805 if (!empty($statii)) {
2806 $groupClause .= " AND {$gcTable}.status IN (" . implode(', ', $statii) . ")";
2807 $qill .= " " . ts('AND') . " " . ts('Group Status') . ' - ' . implode(' ' . ts('or') . ' ', $statii);
2812 $ssClause = $this->savedSearch($values);
2815 $groupClause = "( ( $groupClause ) OR ( $ssClause ) )";
2818 $groupClause = $ssClause;
2823 $this->_where
[$grouping][] = $groupClause;
2824 $this->_qill
[$grouping][] = $qill;
2827 * Function translates selection of group type into a list of groups
2834 function getGroupsFromTypeCriteria($value){
2835 $groupIds = array();
2836 foreach ($value as $groupTypeValue) {
2837 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2838 $groupIds = ($groupIds +
$groupList);
2844 * where / qill clause for smart groups
2848 * @return string|NULL
2851 function savedSearch(&$values) {
2852 list($name, $op, $value, $grouping, $wildcard) = $values;
2853 return $this->addGroupContactCache(array_keys($value));
2857 * @param array $groups
2858 * @param string $tableAlias
2859 * @param string $joinTable
2861 * @return null|string
2863 function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
2864 $config = CRM_Core_Config
::singleton();
2866 // Find all the groups that are part of a saved search.
2867 $groupIDs = implode(',', $groups);
2868 if (empty($groupIDs)) {
2873 SELECT id, cache_date, saved_search_id, children
2875 WHERE id IN ( $groupIDs )
2876 AND ( saved_search_id != 0
2877 OR saved_search_id IS NOT NULL
2878 OR children IS NOT NULL )
2881 $group = CRM_Core_DAO
::executeQuery($sql);
2882 $groupsFiltered = array();
2884 while ($group->fetch()) {
2885 $groupsFiltered[] = $group->id
;
2887 $this->_useDistinct
= TRUE;
2889 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
2890 CRM_Contact_BAO_GroupContactCache
::load($group);
2894 if (count($groupsFiltered)) {
2895 $groupIDsFiltered = implode(',', $groupsFiltered);
2897 if ($tableAlias == NULL) {
2898 $tableAlias = "civicrm_group_contact_cache_{$groupIDsFiltered}";
2901 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache `{$tableAlias}` ON {$joinTable}.id = `{$tableAlias}`.contact_id ";
2903 return "`{$tableAlias}`.group_id IN (" . $groupIDsFiltered . ")";
2910 * where / qill clause for cms users
2917 function ufUser(&$values) {
2918 list($name, $op, $value, $grouping, $wildcard) = $values;
2921 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2923 $this->_qill
[$grouping][] = ts('CMS User');
2925 elseif ($value == 0) {
2926 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2928 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2929 $this->_qill
[$grouping][] = ts('Not a CMS User');
2934 * all tag search specific
2941 function tagSearch(&$values) {
2942 list($name, $op, $value, $grouping, $wildcard) = $values;
2945 $value = "%{$value}%";
2948 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2949 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2951 $etTable = "`civicrm_entity_tag-" . $value . "`";
2952 $tTable = "`civicrm_tag-" . $value . "`";
2954 if ($useAllTagTypes[2]) {
2955 $this->_tables
[$etTable] =
2956 $this->_whereTables
[$etTable] =
2957 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
2958 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
2960 // search tag in cases
2961 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2962 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
2963 $this->_tables
[$etCaseTable] =
2964 $this->_whereTables
[$etCaseTable] =
2965 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2966 LEFT JOIN civicrm_case
2967 ON (civicrm_case_contact.case_id = civicrm_case.id
2968 AND civicrm_case.is_deleted = 0 )
2969 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
2970 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
2971 // search tag in activities
2972 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2973 $tActTable = "`civicrm_act_tag-" . $value . "`";
2974 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2975 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2977 $this->_tables
[$etActTable] =
2978 $this->_whereTables
[$etActTable] =
2979 " LEFT JOIN civicrm_activity_contact
2980 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
2981 LEFT JOIN civicrm_activity
2982 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
2983 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2984 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
2985 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
2987 $this->_where
[$grouping][] = "({$tTable}.name $op '". $value . "' OR {$tCaseTable}.name $op '". $value . "' OR {$tActTable}.name $op '". $value . "')";
2988 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
2990 $etTable = "`civicrm_entity_tag-" . $value . "`";
2991 $tTable = "`civicrm_tag-" . $value . "`";
2992 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
2993 {$etTable}.entity_table = 'civicrm_contact' )
2994 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
2996 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
2997 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
3002 * where / qill clause for tag
3009 function tag(&$values) {
3010 list($name, $op, $value, $grouping, $wildcard) = $values;
3012 $tagNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
3013 if (is_array($value)) {
3014 if (count($value) > 1) {
3015 $this->_useDistinct
= TRUE;
3017 foreach ($value as $id => $dontCare) {
3018 $names[] = CRM_Utils_Array
::value($id, $tagNames);
3020 $names = implode(' ' . ts('or') . ' ', $names);
3021 $value = implode(',', array_keys($value));
3024 $names = CRM_Utils_Array
::value($value, $tagNames);
3028 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3029 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3031 $etTable = "`civicrm_entity_tag-" . $value . "`";
3033 if ($useAllTagTypes[2]) {
3034 $this->_tables
[$etTable] =
3035 $this->_whereTables
[$etTable] =
3036 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3038 // search tag in cases
3039 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3040 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3041 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3043 $this->_tables
[$etCaseTable] =
3044 $this->_whereTables
[$etCaseTable] =
3045 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3046 LEFT JOIN civicrm_case
3047 ON (civicrm_case_contact.case_id = civicrm_case.id
3048 AND civicrm_case.is_deleted = 0 )
3049 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3050 // search tag in activities
3051 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3052 $this->_tables
[$etActTable] =
3053 $this->_whereTables
[$etActTable] =
3054 " LEFT JOIN civicrm_activity_contact
3055 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3056 LEFT JOIN civicrm_activity
3057 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3058 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3059 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3062 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3063 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3066 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (". $value . ") OR {$etCaseTable}.tag_id $op (". $value . ") OR {$etActTable}.tag_id $op (". $value . "))";
3068 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
3070 $this->_tables
[$etTable] =
3071 $this->_whereTables
[$etTable] =
3072 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3075 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3076 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3077 $op = str_replace('EMPTY', 'NULL', $op);
3078 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3081 $this->_where
[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
3083 $this->_qill
[$grouping][] = ts('Tagged %1', array( 1 => $op)) . ' ' . $names;
3089 * where/qill clause for notes
3096 function notes(&$values) {
3097 list($name, $op, $value, $grouping, $wildcard) = $values;
3099 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3100 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3101 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3103 $this->_useDistinct
= TRUE;
3105 $this->_tables
['civicrm_note'] =
3106 $this->_whereTables
['civicrm_note'] =
3107 " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3109 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3111 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3112 if ($wildcard ||
$op == 'LIKE') {
3113 if (strpos($value, '%') === FALSE) {
3114 $value = "%$value%";
3118 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3124 if ( $noteOption %
2 == 0 ) {
3125 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3126 $label = ts('Note: Body Only');
3128 if ( $noteOption %
3 == 0 ) {
3129 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3130 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3132 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3133 $this->_qill
[$grouping][] = $label . " $op - '$n'";
3143 function nameNullOrEmptyOp($name, $op, $grouping) {
3147 $this->_where
[$grouping][] = "contact_a.$name $op";
3148 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3152 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3153 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3156 case 'IS NOT EMPTY':
3157 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3158 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3167 * where / qill clause for sort_name
3174 function sortName(&$values) {
3175 list($name, $op, $value, $grouping, $wildcard) = $values;
3177 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3178 if ( $this->nameNullOrEmptyOp( $name, $op, $grouping ) ) {
3183 $name = trim($value);
3189 $config = CRM_Core_Config
::singleton();
3193 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3196 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3197 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3199 if (substr($name, 0, 1) == '"' &&
3200 substr($name, -1, 1) == '"'
3202 //If name is encased in double quotes, the value should be taken to be the string in entirety and the
3203 $value = substr($name, 1, -1);
3204 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
3205 $wc = ($newName == 'sort_name') ?
'LOWER(contact_a.sort_name)' : 'LOWER(contact_a.display_name)';
3206 $sub[] = " ( $wc = '$value' ) ";
3207 if ($config->includeEmailInName
) {
3208 $sub[] = " ( civicrm_email.email = '$value' ) ";
3211 elseif (strpos($name, ',') !== FALSE) {
3212 // if we have a comma in the string, search for the entire string
3213 $value = $strtolower(CRM_Core_DAO
::escapeString($name));
3215 if ($config->includeWildCardInName
) {
3216 $value = "'%$value%'";
3219 $value = "'$value%'";
3224 $value = "'$value'";
3226 if ($newName == 'sort_name') {
3227 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3230 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3232 $sub[] = " ( $wc $op $value )";
3233 if ($config->includeNickNameInName
) {
3234 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3235 $sub[] = " ( $wc $op $value )";
3237 if ($config->includeEmailInName
) {
3238 $sub[] = " ( civicrm_email.email $op $value ) ";
3242 // the string should be treated as a series of keywords to be matched with match ANY OR
3243 // match ALL depending on Civi config settings (see CiviAdmin)
3245 // The Civi configuration setting can be overridden if the string *starts* with the case
3246 // insenstive strings 'AND:' or 'OR:'TO THINK ABOUT: what happens when someone searches
3247 // for the following "AND: 'a string in quotes'"? - probably nothing - it would make the
3248 // AND OR variable reduntant because there is only one search string?
3250 // Check to see if the $subGlue is overridden in the search text
3251 if (strtolower(substr($name, 0, 4)) == 'and:') {
3252 $name = substr($name, 4);
3255 if (strtolower(substr($name, 0, 3)) == 'or:') {
3256 $name = substr($name, 3);
3260 $firstChar = substr($name, 0, 1);
3261 $lastChar = substr($name, -1, 1);
3262 $quotes = array("'", '"');
3263 if ((strlen($name) > 2) && in_array($firstChar, $quotes) &&
3264 in_array($lastChar, $quotes)
3266 $name = substr($name, 1);
3267 $name = substr($name, 0, -1);
3268 $pieces = array($name);
3271 $pieces = explode(' ', $name);
3273 foreach ($pieces as $piece) {
3274 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($piece)));
3275 if (strlen($value)) {
3276 // Added If as a sanitization - without it, when you do an OR search, any string with
3277 // double spaces (i.e. " ") or that has a space after the keyword (e.g. "OR: ") will
3278 // return all contacts because it will include a condition similar to "OR contact
3279 // name LIKE '%'". It might be better to replace this with array_filter.
3280 $fieldsub = array();
3282 if ($config->includeWildCardInName
) {
3283 $value = "'%$value%'";
3286 $value = "'$value%'";
3291 $value = "'$value'";
3293 if ($newName == 'sort_name') {
3294 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3297 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3299 $fieldsub[] = " ( $wc $op $value )";
3300 if ($config->includeNickNameInName
) {
3301 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3302 $fieldsub[] = " ( $wc $op $value )";
3304 if ($config->includeEmailInName
) {
3305 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3307 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3308 // I seperated the glueing in two. The first stage should always be OR because we are searching for matches in *ANY* of these fields
3313 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3315 $this->_where
[$grouping][] = $sub;
3316 if ($config->includeEmailInName
) {
3317 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3318 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$name'";
3321 $this->_qill
[$grouping][] = ts('Name like') . " - '$name'";
3326 * where / qill clause for email
3333 function email(&$values) {
3334 list($name, $op, $value, $grouping, $wildcard) = $values;
3338 $config = CRM_Core_Config
::singleton();
3340 if (substr($n, 0, 1) == '"' &&
3341 substr($n, -1, 1) == '"'
3343 $n = substr($n, 1, -1);
3344 $value = strtolower(CRM_Core_DAO
::escapeString($n));
3345 $value = "'$value'";
3349 $value = strtolower($n);
3351 if (strpos($value, '%') === FALSE) {
3352 $value = "%{$value}%";
3357 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3358 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3361 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3362 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3365 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3369 * where / qill clause for phone number
3376 function phone_numeric(&$values) {
3377 list($name, $op, $value, $grouping, $wildcard) = $values;
3378 // Strip non-numeric characters; allow wildcards
3379 $number = preg_replace('/[^\d%]/', '', $value);
3381 if ( strpos($number, '%') === FALSE ) {
3382 $number = "%$number%";
3385 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3386 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3387 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3392 * where / qill clause for phone type/location
3399 function phone_option_group($values) {
3400 list($name, $op, $value, $grouping, $wildcard) = $values;
3401 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3402 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3403 $optionName = $options[$value];
3404 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3405 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3406 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3410 * where / qill clause for street_address
3417 function street_address(&$values) {
3418 list($name, $op, $value, $grouping, $wildcard) = $values;
3427 $value = strtolower($n);
3428 if (strpos($value, '%') === FALSE) {
3429 // only add wild card if not there
3430 $value = "%{$value}%";
3433 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3434 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3437 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3438 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3441 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3445 * where / qill clause for street_unit
3452 function street_number(&$values) {
3453 list($name, $op, $value, $grouping, $wildcard) = $values;
3461 if (strtolower($n) == 'odd') {
3462 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3463 $this->_qill
[$grouping][] = ts('Street Number is odd');
3465 elseif (strtolower($n) == 'even') {
3466 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3467 $this->_qill
[$grouping][] = ts('Street Number is even');
3470 $value = strtolower($n);
3472 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3473 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3476 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3480 * where / qill clause for sorting by character
3487 function sortByCharacter(&$values) {
3488 list($name, $op, $value, $grouping, $wildcard) = $values;
3490 $name = trim($value);
3491 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3492 $this->_where
[$grouping][] = $cond;
3493 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3497 * where / qill clause for including contact ids
3502 function includeContactIDs() {
3503 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3507 $contactIds = array();
3508 foreach ($this->_params
as $id => $values) {
3509 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3510 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3513 if (!empty($contactIds)) {
3514 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3519 * where / qill clause for postal code
3526 function postalCode(&$values) {
3527 // skip if the fields dont have anything to do with postal_code
3528 if (empty($this->_fields
['postal_code'])) {
3532 list($name, $op, $value, $grouping, $wildcard) = $values;
3534 // Handle numeric postal code range searches properly by casting the column as numeric
3535 if (is_numeric($value)) {
3536 $field = 'ROUND(civicrm_address.postal_code)';
3537 $val = CRM_Utils_Type
::escape($value, 'Integer');
3540 $field = 'civicrm_address.postal_code';
3541 $val = CRM_Utils_Type
::escape($value, 'String');
3544 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3546 if ($name == 'postal_code') {
3547 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3548 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3550 elseif ($name == 'postal_code_low') {
3551 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3552 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3554 elseif ($name == 'postal_code_high') {
3555 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3556 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3561 * where / qill clause for location type
3564 * @param null $status
3569 function locationType(&$values, $status = NULL) {
3570 list($name, $op, $value, $grouping, $wildcard) = $values;
3572 if (is_array($value)) {
3573 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3574 $this->_tables
['civicrm_address'] = 1;
3575 $this->_whereTables
['civicrm_address'] = 1;
3577 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3579 foreach ($value as $id) {
3580 $names[] = $locationType[$id];
3583 $this->_primaryLocation
= FALSE;
3586 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3589 return implode(' ' . ts('or') . ' ', $names);
3596 * @param bool $fromStateProvince
3600 function country(&$values, $fromStateProvince = TRUE) {
3601 list($name, $op, $value, $grouping, $wildcard) = $values;
3603 if (!$fromStateProvince) {
3604 $stateValues = $this->getWhereValues('state_province', $grouping);
3605 if (!empty($stateValues)) {
3606 // return back to caller if there are state province values
3607 // since that handles this case
3612 $countryClause = $countryQill = NULL;
3618 $this->_tables
['civicrm_address'] = 1;
3619 $this->_whereTables
['civicrm_address'] = 1;
3621 $countries = CRM_Core_PseudoConstant
::country();
3622 if (is_numeric($value)) {
3623 $countryClause = self
::buildClause(
3624 'civicrm_address.country_id',
3629 $countryName = $countries[(int ) $value];
3633 $intValues = self
::parseSearchBuilderString($value);
3634 if ($intValues && ($op == 'IN' ||
$op == 'NOT IN')) {
3635 $countryClause = self
::buildClause(
3636 'civicrm_address.country_id',
3641 $countryNames = array();
3642 foreach ($intValues as $v) {
3643 $countryNames[] = $countries[$v];
3645 $countryName = implode(',', $countryNames);
3648 $countries = CRM_Core_PseudoConstant
::country();
3649 $intVal = CRM_Utils_Array
::key($value, $countries);
3650 $countryClause = self
::buildClause(
3651 'civicrm_address.country_id',
3656 $countryName = $value;
3659 $countryQill = ts('Country') . " {$op} '$countryName'";
3661 if (!$fromStateProvince) {
3662 $this->_where
[$grouping][] = $countryClause;
3663 $this->_qill
[$grouping][] = $countryQill;
3667 if ($fromStateProvince) {
3668 if (!empty($countryClause)) {
3671 " ...AND... " . $countryQill,
3675 return array(NULL, NULL);
3681 * where / qill clause for county (if present)
3684 * @param null $status
3689 function county(&$values, $status = null) {
3690 list($name, $op, $value, $grouping, $wildcard) = $values;
3692 if (! is_array($value)) {
3693 // force the county to be an array
3694 $value = array($value);
3697 // check if the values are ids OR names of the counties
3698 $inputFormat = 'id';
3699 foreach ($value as $v) {
3700 if (!is_numeric($v)) {
3701 $inputFormat = 'name';
3709 else if ($op == '!=') {
3713 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3714 $op = str_replace('EMPTY', 'NULL', $op);
3717 if (in_array( $op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3718 $clause = "civicrm_address.county_id $op";
3720 elseif ($inputFormat == 'id') {
3721 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3723 $county = CRM_Core_PseudoConstant
::county();
3724 foreach ($value as $id) {
3725 $names[] = CRM_Utils_Array
::value($id, $county);
3729 $inputClause = array();
3730 $county = CRM_Core_PseudoConstant
::county();
3731 foreach ($value as $name) {
3732 $name = trim($name);
3733 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3735 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3738 $this->_tables
['civicrm_address'] = 1;
3739 $this->_whereTables
['civicrm_address'] = 1;
3741 $this->_where
[$grouping][] = $clause;
3743 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3745 return implode(' ' . ts('or') . ' ', $names);
3750 * where / qill clause for state/province AND country (if present)
3753 * @param null $status
3758 function stateProvince(&$values, $status = NULL) {
3759 list($name, $op, $value, $grouping, $wildcard) = $values;
3761 // quick escape for IS NULL
3762 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3765 else if (!is_array($value)) {
3766 // force the state to be an array
3767 // check if its in the mapper format!
3768 $values = self
::parseSearchBuilderString($value);
3769 if (is_array($values)) {
3773 $value = array($value);
3777 // check if the values are ids OR names of the states
3778 $inputFormat = 'id';
3780 foreach ($value as $v) {
3781 if (!is_numeric($v)) {
3782 $inputFormat = 'name';
3792 else if ($op == '!=') {
3796 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3797 $op = str_replace('EMPTY', 'NULL', $op);
3799 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3800 $stateClause = "civicrm_address.state_province_id $op";
3802 else if ($inputFormat == 'id') {
3803 if ($op != 'NOT IN') {
3806 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
3808 foreach ($value as $id) {
3809 $names[] = CRM_Core_PseudoConstant
::stateProvince($id, FALSE);
3813 $inputClause = array();
3814 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3815 foreach ($value as $name) {
3816 $name = trim($name);
3817 $inputClause[] = CRM_Utils_Array
::key($name, $stateProvince);
3819 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
3822 $this->_tables
['civicrm_address'] = 1;
3823 $this->_whereTables
['civicrm_address'] = 1;
3825 $countryValues = $this->getWhereValues('country', $grouping);
3826 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3828 if ($countryClause) {
3829 $clause = "( $stateClause AND $countryClause )";
3832 $clause = $stateClause;
3835 $this->_where
[$grouping][] = $clause;
3837 $this->_qill
[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3840 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
3845 * where / qill clause for change log
3852 function changeLog(&$values) {
3853 list($name, $op, $value, $grouping, $wildcard) = $values;
3855 $targetName = $this->getWhereValues('changed_by', $grouping);
3860 $name = trim($targetName[2]);
3861 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3862 $name = $targetName[4] ?
"%$name%" : $name;
3863 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3864 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3865 $this->_qill
[$grouping][] = ts('Modified By') . " $name";
3871 function modifiedDates($values) {
3872 $this->_useDistinct
= TRUE;
3874 // CRM-11281, default to added date if not set
3875 $fieldTitle = ts('Added Date');
3876 $fieldName = 'created_date';
3877 foreach (array_keys($this->_params
) as $id) {
3878 if ($this->_params
[$id][0] == 'log_date') {
3879 if ($this->_params
[$id][2] == 2) {
3880 $fieldTitle = ts('Modified Date');
3881 $fieldName = 'modified_date';
3887 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3889 self
::$_openedPanes[ts('Change Log')] = TRUE;
3895 function demographics(&$values) {
3896 list($name, $op, $value, $grouping, $wildcard) = $values;
3898 if (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3900 $this->dateQueryBuilder($values,
3901 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3904 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3906 $this->dateQueryBuilder($values,
3907 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3911 self
::$_openedPanes[ts('Demographics')] = TRUE;
3917 function privacy(&$values) {
3918 list($name, $op, $value, $grouping, $wildcard) = $values;
3919 //fixed for profile search listing CRM-4633
3920 if (strpbrk($value, "[")) {
3921 $value = "'{$value}'";
3923 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3926 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3928 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3929 $title = $field ?
$field['title'] : $name;
3930 $this->_qill
[$grouping][] = "$title $op $value";
3936 function privacyOptions($values) {
3937 list($name, $op, $value, $grouping, $wildcard) = $values;
3939 if (empty($value) ||
!is_array($value)) {
3943 // get the operator and toggle values
3944 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3947 strtolower($opValues[2] == 'AND')
3952 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3954 if ($toggleValues &&
3955 $toggleValues[2] == 2
3962 foreach ($value as $dontCare => $pOption) {
3963 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
3964 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3965 $title = $field ?
$field['title'] : $pOption;
3966 $qill[] = " $title = 1 ";
3969 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
3970 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
3976 function preferredCommunication(&$values) {
3977 list($name, $op, $value, $grouping, $wildcard) = $values;
3980 if (in_array($op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3983 elseif (!is_array($value)) {
3985 $value = trim($value, ' ()');
3986 if (strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
3987 $v = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
3990 $v = explode(",", $value);
3993 foreach ($v as $item) {
4000 foreach ($value as $key => $checked) {
4007 $commPref = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
4009 $sqlValue = array();
4010 $showValue = array();
4011 $sql = "contact_a.preferred_communication_method";
4012 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
4013 $sqlValue[] = "{$sql} {$op}";
4016 foreach ($pref as $val) {
4017 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $val . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' ) ";
4018 $showValue[] = $commPref[$val];
4021 $this->_where
[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
4022 $this->_qill
[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
4026 * where / qill clause for relationship
4033 function relationship(&$values) {
4034 list($name, $op, $value, $grouping, $wildcard) = $values;
4035 if ($this->_relationshipValuesAdded
){
4038 // also get values array for relation_target_name
4039 // for relationship search we always do wildcard
4040 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4041 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4042 $relStatus = $this->getWhereValues('relation_status', $grouping);
4043 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4044 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4046 $nameClause = $name = NULL;
4048 $name = trim($targetName[2]);
4049 if (substr($name, 0, 1) == '"' &&
4050 substr($name, -1, 1) == '"'
4052 $name = substr($name, 1, -1);
4053 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4054 $nameClause = "= '$name'";
4057 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4058 $nameClause = "LIKE '%{$name}%'";
4062 $rTypeValues = array();
4063 if (!empty($relationType) ) {
4064 $rel = explode('_', $relationType[2]);
4065 self
::$_relType = $rel[1];
4066 $params = array('id' => $rel[0]);
4067 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
4069 if (!empty($rTypeValues) && $rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
4070 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4071 //@todo unless we are dealing with a target group
4072 self
::$_relType = 'reciprocal';
4074 // if we are creating a temp table we build our own where for the relationship table
4075 $relationshipTempTable = NULL;
4076 if (self
::$_relType == 'reciprocal' && empty($targetGroup)) {
4078 self
::$_relationshipTempTable =
4079 $relationshipTempTable =
4080 CRM_Core_DAO
::createTempTableName( 'civicrm_rel');
4082 $where[$grouping][] = " sort_name $nameClause ";
4086 $where = &$this->_where
;
4088 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4093 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
4094 $relTypeOrg = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
4095 $relTypeHou = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Household');
4096 $allRelationshipType = array();
4097 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
4098 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
4100 if ($nameClause ||
!$targetGroup) {
4101 if (!empty($relationType) ) {
4102 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] ." $name";
4104 $this->_qill
[$grouping][] = $name;
4109 //check to see if the target contact is in specified group
4111 //add contacts from static groups
4112 $this->_tables
['civicrm_relationship_group_contact'] =
4113 $this->_whereTables
['civicrm_relationship_group_contact'] =
4114 " 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'";
4116 "( civicrm_relationship_group_contact.group_id IN (" .
4117 implode(",", $targetGroup[2]) . ") ) ";
4119 //add contacts from saved searches
4120 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
4122 //set the group where clause
4124 $groupWhere[] = "( " . $ssWhere . " )";
4126 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4128 //Get the names of the target groups for the qill
4129 $groupNames = CRM_Core_PseudoConstant
::group();
4130 $qillNames = array();
4131 foreach ($targetGroup[2] as $groupId) {
4132 if (array_key_exists($groupId, $groupNames)) {
4133 $qillNames[] = $groupNames[$groupId];
4136 if ( !empty($relationType) ) {
4137 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] ." ( " . implode(", ", $qillNames) . " )";
4139 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4143 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4144 $today = date('Ymd');
4145 //check for active, inactive and all relation status
4146 if ($relStatus[2] == 0) {
4147 $where[$grouping][] = "(
4148 civicrm_relationship.is_active = 1 AND
4149 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4150 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4152 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4154 elseif ($relStatus[2] == 1) {
4155 $where[$grouping][] = "(
4156 civicrm_relationship.is_active = 0 OR
4157 civicrm_relationship.end_date < {$today} OR
4158 civicrm_relationship.start_date > {$today}
4160 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4163 //check for permissioned, non-permissioned and all permissioned relations
4164 if ($relPermission[2] == 1) {
4165 $where[$grouping][] = "(
4166 civicrm_relationship.is_permission_a_b = 1
4168 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4169 } elseif ($relPermission[2] == 2) {
4170 //non-allowed permission relationship.
4171 $where[$grouping][] = "(
4172 civicrm_relationship.is_permission_a_b = 0
4174 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4177 $this->addRelationshipDateClauses($grouping, $where);
4178 if (!empty($relationType) && !empty($rType) && isset($rType->id
)){
4179 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
4181 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4182 $this->_useDistinct
= TRUE;
4183 $this->_relationshipValuesAdded
= TRUE;
4184 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4186 // @todo creating a temp table could be expanded to group filter
4187 // as even creating a temp table of all relationships is much much more efficient than
4188 // an OR in the join
4189 if ($relationshipTempTable) {
4191 if ( ! empty( $where[$grouping] ) ) {
4192 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4195 CREATE TEMPORARY TABLE {$relationshipTempTable}
4196 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4197 FROM civicrm_relationship
4198 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4201 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4202 FROM civicrm_relationship
4203 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4206 CRM_Core_DAO
::executeQuery($sql);
4211 * Add start & end date criteria in
4212 * @param string $grouping
4213 * @param array $where = array to add where clauses to, in case you are generating a temp table
4214 * not the main query.
4216 function addRelationshipDateClauses($grouping, &$where){
4217 $dateValues = array();
4223 foreach ($dateTypes as $dateField){
4224 $dateValueLow = $this->getWhereValues('relation_'. $dateField .'_low', $grouping);
4225 $dateValueHigh= $this->getWhereValues('relation_'. $dateField .'_high', $grouping);
4226 if (!empty($dateValueLow)){
4227 $date = date('Ymd', strtotime($dateValueLow[2]));
4228 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4229 $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);
4231 if (!empty($dateValueHigh)){
4232 $date = date('Ymd', strtotime($dateValueHigh[2]));
4233 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4234 $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);
4240 * default set of return properties
4244 * @return array derault return properties
4247 static function &defaultReturnProperties($mode = 1) {
4248 if (!isset(self
::$_defaultReturnProperties)) {
4249 self
::$_defaultReturnProperties = array();
4252 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4253 // add activity return properties
4254 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4255 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4258 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4261 if (empty(self
::$_defaultReturnProperties[$mode])) {
4262 self
::$_defaultReturnProperties[$mode] = array(
4265 'legal_identifier' => 1,
4266 'external_identifier' => 1,
4267 'contact_type' => 1,
4268 'contact_sub_type' => 1,
4270 'display_name' => 1,
4271 'preferred_mail_format' => 1,
4278 'formal_title' => 1,
4279 'communication_style_id' => 1,
4282 'street_address' => 1,
4283 'supplemental_address_1' => 1,
4284 'supplemental_address_2' => 1,
4287 'postal_code_suffix' => 1,
4288 'state_province' => 1,
4290 'world_region' => 1,
4297 'household_name' => 1,
4298 'organization_name' => 1,
4299 'deceased_date' => 1,
4304 'current_employer' => 1,
4305 // FIXME: should we use defaultHierReturnProperties() for the below?
4306 'do_not_email' => 1,
4309 'do_not_phone' => 1,
4310 'do_not_trade' => 1,
4312 'contact_is_deleted' => 1,
4313 'preferred_communication_method' => 1,
4314 'preferred_language' => 1,
4318 return self
::$_defaultReturnProperties[$mode];
4322 * get primary condition for a sql clause
4326 * @return string|NULL
4329 static function getPrimaryCondition($value) {
4330 if (is_numeric($value)) {
4331 $value = (int ) $value;
4332 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4338 * wrapper for a simple search query
4340 * @param array $params
4341 * @param array $returnProperties
4342 * @param bool $count
4347 static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4348 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4349 list($select, $from, $where, $having) = $query->query();
4351 return "$select $from $where $having";
4355 * These are stub comments as this function needs more explanation - particularly in terms of how it
4356 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4358 * This function was originally written as a wrapper for the api query but is called from multiple places
4359 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4360 * but it is unclear as to whehter that is historical or there is a reason
4361 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4363 * @param array $params
4364 * @param array $returnProperties
4365 * @param null $fields
4366 * @param string $sort
4367 * @param int $offset
4368 * @param int $row_count
4369 * @param bool $smartGroupCache
4370 * @param bool $count return count obnly
4371 * @param bool $skipPermissions Should permissions be ignored or should the logged in user's permissions be applied
4373 * @params bool $smartGroupCache ?? update smart group cache?
4378 static function apiQuery(
4380 $returnProperties = NULL,
4385 $smartGroupCache = TRUE,
4387 $skipPermissions = TRUE
4390 $query = new CRM_Contact_BAO_Query(
4391 $params, $returnProperties,
4392 NULL, TRUE, FALSE, 1,
4394 TRUE, $smartGroupCache
4397 //this should add a check for view deleted if permissions are enabled
4398 if ($skipPermissions){
4399 $query->_skipDeleteClause
= TRUE;
4401 $query->generatePermissionClause(FALSE, $count);
4403 // note : this modifies _fromClause and _simpleFromClause
4404 $query->includePseudoFieldsJoin($sort);
4406 list($select, $from, $where, $having) = $query->query($count);
4408 $options = $query->_options
;
4409 if (!empty($query->_permissionWhereClause
)){
4410 if (empty($where)) {
4411 $where = "WHERE $query->_permissionWhereClause";
4414 $where = "$where AND $query->_permissionWhereClause";
4418 $sql = "$select $from $where $having";
4421 if ($query->_useGroupBy
) {
4422 $sql .= ' GROUP BY contact_a.id';
4424 if (!empty($sort)) {
4425 $sort = CRM_Utils_Type
::escape($sort, 'String');
4426 $sql .= " ORDER BY $sort ";
4428 if ($row_count > 0 && $offset >= 0) {
4429 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4430 $rowCount = CRM_Utils_Type
::escape($row_count, 'Int');
4431 $sql .= " LIMIT $offset, $row_count ";
4434 $dao = CRM_Core_DAO
::executeQuery($sql);
4437 while ($dao->fetch()) {
4439 $noRows = $dao->rowCount
;
4441 return array($noRows,NULL);
4443 $val = $query->store($dao);
4444 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4446 if (!empty($convertedVals)) {
4447 $val = array_replace_recursive($val, $convertedVals);
4449 $values[$dao->contact_id
] = $val;
4452 return array($values, $options);
4456 * create and query the db for an contact search
4458 * @param int $offset the offset for the query
4459 * @param int $rowCount the number of rows to return
4460 * @param string $sort the order by string
4461 * @param boolean $count is this a count only query ?
4462 * @param boolean $includeContactIds should we include contact ids?
4463 * @param boolean $sortByChar if true returns the distinct array of first characters for search results
4464 * @param boolean $groupContacts if true, return only the contact ids
4465 * @param boolean $returnQuery should we return the query as a string
4466 * @param string $additionalWhereClause if the caller wants to further restrict the search (used for components)
4467 * @param null $sortOrder
4468 * @param string $additionalFromClause should be clause with proper joins, effective to reduce where clause load.
4470 * @param bool $skipOrderAndLimit
4472 * @return CRM_Core_DAO
4475 function searchQuery(
4476 $offset = 0, $rowCount = 0, $sort = NULL,
4477 $count = FALSE, $includeContactIds = FALSE,
4478 $sortByChar = FALSE, $groupContacts = FALSE,
4479 $returnQuery = FALSE,
4480 $additionalWhereClause = NULL, $sortOrder = NULL,
4481 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4484 if ($includeContactIds) {
4485 $this->_includeContactIds
= TRUE;
4486 $this->_whereClause
= $this->whereClause();
4489 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4491 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4492 // and that contact happens to be deleted, set $onlyDeleted to true
4493 foreach ($this->_params
as $values) {
4494 $name = CRM_Utils_Array
::value(0, $values);
4495 $op = CRM_Utils_Array
::value(1, $values);
4496 $value = CRM_Utils_Array
::value(2, $values);
4497 if ($name == 'contact_id' and $op == '=') {
4498 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4499 $onlyDeleted = TRUE;
4505 // building the query string
4508 if (isset($this->_groupByComponentClause
)) {
4509 $groupBy = $this->_groupByComponentClause
;
4511 elseif ($this->_useGroupBy
) {
4512 $groupBy = ' GROUP BY contact_a.id';
4515 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4516 $groupBy = 'GROUP BY civicrm_activity.id ';
4519 $order = $orderBy = $limit = '';
4521 $config = CRM_Core_Config
::singleton();
4522 if ($config->includeOrderByClause ||
4523 isset($this->_distinctComponentClause
)
4526 if (is_string($sort)) {
4530 $orderBy = trim($sort->orderBy());
4532 if (!empty($orderBy)) {
4533 // this is special case while searching for
4534 // change log CRM-1718
4535 if (preg_match('/sort_name/i', $orderBy)) {
4536 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4539 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
4540 $order = " ORDER BY $orderBy";
4543 $sortOrder = CRM_Utils_Type
::escape($sortOrder, 'String');
4544 $order .= " $sortOrder";
4547 // always add contact_a.id to the ORDER clause
4548 // so the order is deterministic
4549 if (strpos('contact_a.id', $order) === FALSE) {
4550 $order .= ", contact_a.id";
4554 elseif ($sortByChar) {
4555 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4558 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4562 // hack for order clause
4564 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4565 $fieldOrder = explode(' ', $fieldStr);
4566 $field = $fieldOrder[0];
4572 $this->_whereTables
["civicrm_address"] = 1;
4573 $order = str_replace($field, "civicrm_address.{$field}", $order);
4577 case 'state_province':
4578 $this->_whereTables
["civicrm_{$field}"] = 1;
4579 $order = str_replace($field, "civicrm_{$field}.name", $order);
4583 $this->_whereTables
["civicrm_email"] = 1;
4584 $order = str_replace($field, "civicrm_email.{$field}", $order);
4588 //CRM-12565 add "`" around $field if it is a pseudo constant
4589 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
4590 if (!empty($value['element']) && $value['element'] == $field) {
4591 $order = str_replace($field, "`{$field}`", $order);
4595 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4596 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4600 if ($rowCount > 0 && $offset >= 0) {
4601 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4602 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4603 $limit = " LIMIT $offset, $rowCount ";
4608 $this->_sort
= $sort;
4610 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4612 if ($additionalWhereClause) {
4613 $where = $where . ' AND ' . $additionalWhereClause;
4616 //additional from clause should be w/ proper joins.
4617 if ($additionalFromClause) {
4618 $from .= "\n" . $additionalFromClause;
4621 // if we are doing a transform, do it here
4622 // use the $from, $where and $having to get the contact ID
4623 if ($this->_displayRelationshipType
) {
4624 $this->filterRelatedContacts($from, $where, $having);
4627 if ($skipOrderAndLimit) {
4628 $query = "$select $from $where $having $groupBy";
4631 $query = "$select $from $where $having $groupBy $order $limit";
4638 return CRM_Core_DAO
::singleValueQuery($query);
4641 $dao = CRM_Core_DAO
::executeQuery($query);
4642 if ($groupContacts) {
4644 while ($dao->fetch()) {
4647 return implode(',', $ids);
4654 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4656 * @param string $cacheKey
4657 * @param int $offset
4658 * @param int $rowCount
4659 * @param bool $includeContactIds
4660 * @return CRM_Core_DAO
4662 function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4663 $this->_includeContactIds
= $includeContactIds;
4664 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4665 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
4666 $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);
4667 $order = " ORDER BY pnc.id";
4668 $groupBy = " GROUP BY contact_a.id";
4669 $limit = " LIMIT $offset, $rowCount";
4670 $query = "$select $from $where $groupBy $order $limit";
4672 return CRM_Core_DAO
::executeQuery($query);
4676 * Populate $this->_permissionWhereClause with permission related clause and update other
4677 * query related properties.
4679 * Function calls ACL permission class and hooks to filter the query appropriately
4681 * Note that these 2 params were in the code when extracted from another function
4682 * and a second round extraction would be to make them properties of the class
4684 * @param bool $onlyDeleted Only get deleted contacts
4685 * @param bool $count Return Count only
4689 function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4690 if (!$this->_skipPermission
) {
4691 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4692 CRM_Core_Permission
::VIEW
,
4694 $this->_whereTables
,
4697 $this->_skipDeleteClause
4700 // regenerate fromClause since permission might have added tables
4701 if ($this->_permissionWhereClause
) {
4702 //fix for row count in qill (in contribute/membership find)
4704 $this->_useDistinct
= TRUE;
4707 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4708 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4709 // note : this modifies _fromClause and _simpleFromClause
4710 $this->includePseudoFieldsJoin($this->_sort
);
4714 // add delete clause if needed even if we are skipping permission
4716 if (!$this->_skipDeleteClause
) {
4717 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4718 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4722 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4731 function setSkipPermission($val) {
4732 $this->_skipPermission
= $val;
4736 * @param null $context
4740 function &summaryContribution($context = NULL) {
4741 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4745 SELECT COUNT( conts.total_amount ) as total_count,
4746 SUM( conts.total_amount ) as total_amount,
4747 AVG( conts.total_amount ) as total_avg,
4748 conts.currency as currency";
4749 if ($this->_permissionWhereClause
) {
4750 $where .= " AND " . $this->_permissionWhereClause
;
4752 if ($context == 'search') {
4753 $where .= " AND contact_a.is_deleted = 0 ";
4756 // make sure contribution is completed - CRM-4989
4757 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4761 $summary['total'] = array();
4762 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4764 $query = "$select FROM (
4765 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $completedWhere
4766 GROUP BY civicrm_contribution.id
4770 $dao = CRM_Core_DAO
::executeQuery($query);
4772 $summary['total']['count'] = 0;
4773 $summary['total']['amount'] = $summary['total']['avg'] = array();
4774 while ($dao->fetch()) {
4775 $summary['total']['count'] +
= $dao->total_count
;
4776 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4777 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4779 if (!empty($summary['total']['amount'])) {
4780 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4781 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4784 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4787 // soft credit summary
4788 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
4789 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
4792 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
4793 GROUP BY civicrm_contribution_soft.id
4796 $dao = CRM_Core_DAO
::executeQuery($query);
4797 $summary['soft_credit']['count'] = 0;
4798 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
4799 while ($dao->fetch()) {
4800 $summary['soft_credit']['count'] +
= $dao->total_count
;
4801 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4802 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4804 if (!empty($summary['soft_credit']['amount'])) {
4805 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
4806 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
4809 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
4814 //@todo - this could be one query using the IF in mysql - eg
4815 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
4816 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
4817 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
4818 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
4819 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
4820 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
4821 // FROM civicrm_contact contact_a
4822 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
4823 // WHERE ( ... where clause....
4824 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
4828 SELECT COUNT( conts.total_amount ) as cancel_count,
4829 SUM( conts.total_amount ) as cancel_amount,
4830 AVG( conts.total_amount ) as cancel_avg,
4831 conts.currency as currency";
4833 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4834 if ($context == 'search') {
4835 $where .= " AND contact_a.is_deleted = 0 ";
4838 $query = "$select FROM (
4839 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
4840 GROUP BY civicrm_contribution.id
4844 $dao = CRM_Core_DAO
::executeQuery($query);
4847 if ($dao->fetch()) {
4848 $summary['cancel']['count'] = $dao->cancel_count
;
4849 $summary['cancel']['amount'] = $dao->cancel_amount
;
4850 $summary['cancel']['avg'] = $dao->cancel_avg
;
4854 $summary['cancel']['count'] = 0;
4855 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4856 while ($dao->fetch()) {
4857 $summary['cancel']['count'] +
= $dao->cancel_count
;
4858 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4859 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4861 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4862 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
4869 * getter for the qill object
4875 return $this->_qill
;
4879 * default set of return default hier return properties
4884 static function &defaultHierReturnProperties() {
4885 if (!isset(self
::$_defaultHierReturnProperties)) {
4886 self
::$_defaultHierReturnProperties = array(
4889 'legal_identifier' => 1,
4890 'external_identifier' => 1,
4891 'contact_type' => 1,
4892 'contact_sub_type' => 1,
4894 'display_name' => 1,
4901 'formal_title' => 1,
4902 'communication_style_id' => 1,
4903 'email_greeting' => 1,
4904 'postal_greeting' => 1,
4908 'preferred_communication_method' => 1,
4909 'do_not_phone' => 1,
4910 'do_not_email' => 1,
4913 'do_not_trade' => 1,
4916 '1' => array('location_type' => 1,
4917 'street_address' => 1,
4919 'state_province' => 1,
4921 'postal_code_suffix' => 1,
4924 'phone-Mobile' => 1,
4937 'location_type' => 1,
4938 'street_address' => 1,
4940 'state_province' => 1,
4942 'postal_code_suffix' => 1,
4945 'phone-Mobile' => 1,
4959 return self
::$_defaultHierReturnProperties;
4966 * @param $dbFieldName
4967 * @param $fieldTitle
4968 * @param bool $appendTimeStamp
4970 function dateQueryBuilder(
4971 &$values, $tableName, $fieldName,
4972 $dbFieldName, $fieldTitle,
4973 $appendTimeStamp = TRUE
4975 list($name, $op, $value, $grouping, $wildcard) = $values;
4981 if ($name == "{$fieldName}_low" ||
4982 $name == "{$fieldName}_high"
4984 if (isset($this->_rangeCache
[$fieldName])) {
4987 $this->_rangeCache
[$fieldName] = 1;
4989 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4991 if ($name == $fieldName . '_low') {
4993 $firstPhrase = ts('greater than or equal to');
4994 $firstDate = CRM_Utils_Date
::processDate($value);
4996 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4997 if (!empty($secondValues) && $secondValues[2]) {
4999 $secondPhrase = ts('less than or equal to');
5000 $secondValue = $secondValues[2];
5002 if ($appendTimeStamp && strlen($secondValue) == 10) {
5003 $secondValue .= ' 23:59:59';
5005 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5008 elseif ($name == $fieldName . '_high') {
5010 $firstPhrase = ts('less than or equal to');
5012 if ($appendTimeStamp && strlen($value) == 10) {
5013 $value .= ' 23:59:59';
5015 $firstDate = CRM_Utils_Date
::processDate($value);
5017 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5018 if (!empty($secondValues) && $secondValues[2]) {
5020 $secondPhrase = ts('greater than or equal to');
5021 $secondValue = $secondValues[2];
5022 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5026 if (!$appendTimeStamp) {
5027 $firstDate = substr($firstDate, 0, 8);
5029 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5032 if (!$appendTimeStamp) {
5033 $secondDate = substr($secondDate, 0, 8);
5035 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5038 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5040 $this->_where
[$grouping][] = "
5041 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5042 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5044 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5047 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5048 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5052 if ($name == $fieldName) {
5056 $date = CRM_Utils_Date
::processDate($value);
5058 if (!$appendTimeStamp) {
5059 $date = substr($date, 0, 8);
5062 $format = CRM_Utils_Date
::customFormat($date);
5065 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'";
5068 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op";
5070 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5071 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$format\"";
5079 * @param $dbFieldName
5080 * @param $fieldTitle
5081 * @param null $options
5083 function numberRangeBuilder(&$values,
5084 $tableName, $fieldName,
5085 $dbFieldName, $fieldTitle,
5088 list($name, $op, $value, $grouping, $wildcard) = $values;
5090 if ($name == "{$fieldName}_low" ||
5091 $name == "{$fieldName}_high"
5093 if (isset($this->_rangeCache
[$fieldName])) {
5096 $this->_rangeCache
[$fieldName] = 1;
5098 $secondOP = $secondPhrase = $secondValue = NULL;
5100 if ($name == "{$fieldName}_low") {
5102 $firstPhrase = ts('greater than');
5104 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5105 if (!empty($secondValues)) {
5107 $secondPhrase = ts('less than');
5108 $secondValue = $secondValues[2];
5113 $firstPhrase = ts('less than');
5115 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5116 if (!empty($secondValues)) {
5118 $secondPhrase = ts('greater than');
5119 $secondValue = $secondValues[2];
5124 $this->_where
[$grouping][] = "
5125 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5126 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5128 $displayValue = $options ?
$options[$value] : $value;
5129 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5131 $this->_qill
[$grouping][] =
5132 "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5135 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5136 $displayValue = $options ?
$options[$value] : $value;
5137 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5139 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5144 if ($name == $fieldName) {
5148 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5150 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5151 $displayValue = $options ?
$options[$value] : $value;
5152 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5159 * Given the field name, operator, value & its data type
5160 * builds the where Clause for the query
5161 * used for handling 'IS NULL'/'IS NOT NULL' operators
5163 * @param string $field fieldname
5164 * @param string $op operator
5165 * @param string $value value
5166 * @param string $dataType data type of the field
5168 * @return string where clause for the query
5171 static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5173 $clause = "$field $op";
5181 $clause = " (NULLIF($field, '') IS NULL) ";
5184 case 'IS NOT EMPTY':
5185 $clause = " (NULLIF($field, '') IS NOT NULL) ";
5190 if (isset($dataType)) {
5191 if (is_array($value)) {
5195 $value = CRM_Utils_Type
::escape($value, "String");
5196 $values = explode(',', CRM_Utils_Array
::value(0, explode(')', CRM_Utils_Array
::value(1, explode('(', $value)))));
5198 // supporting multiple values in IN clause
5200 foreach ($values as $v) {
5202 $val[] = "'" . CRM_Utils_Type
::escape($v, $dataType) . "'";
5204 $value = "(" . implode($val, ",") . ")";
5206 return "$clause $value";
5209 if (empty($dataType)) {
5210 $dataType = 'String';
5212 if (is_array($value)) {
5213 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5214 // widely used and consistent across the codebase
5215 // adding this here won't accept the search functions which don't submit an array
5216 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, $value, $dataType)) != FALSE) {
5217 return $queryString;
5220 $value = CRM_Utils_Type
::escape($value, $dataType);
5221 // if we don't have a dataType we should assume
5222 if ($dataType == 'String' ||
$dataType == 'Text') {
5223 $value = "'" . strtolower($value) . "'";
5225 return "$clause $value";
5230 * @param bool $reset
5234 function openedSearchPanes($reset = FALSE) {
5235 if (!$reset ||
empty($this->_whereTables
)) {
5236 return self
::$_openedPanes;
5239 // pane name to table mapper
5240 $panesMapper = array(
5241 ts('Contributions') => 'civicrm_contribution',
5242 ts('Memberships') => 'civicrm_membership',
5243 ts('Events') => 'civicrm_participant',
5244 ts('Relationships') => 'civicrm_relationship',
5245 ts('Activities') => 'civicrm_activity',
5246 ts('Pledges') => 'civicrm_pledge',
5247 ts('Cases') => 'civicrm_case',
5248 ts('Grants') => 'civicrm_grant',
5249 ts('Address Fields') => 'civicrm_address',
5250 ts('Notes') => 'civicrm_note',
5251 ts('Change Log') => 'civicrm_log',
5252 ts('Mailings') => 'civicrm_mailing_event_queue',
5254 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5256 foreach (array_keys($this->_whereTables
) as $table) {
5257 if ($panName = array_search($table, $panesMapper)) {
5258 self
::$_openedPanes[$panName] = TRUE;
5262 return self
::$_openedPanes;
5268 function setOperator($operator) {
5269 $validOperators = array('AND', 'OR');
5270 if (!in_array($operator, $validOperators)) {
5273 $this->_operator
= $operator;
5279 function getOperator() {
5280 return $this->_operator
;
5288 function filterRelatedContacts(&$from, &$where, &$having) {
5289 static $_rTypeProcessed = NULL;
5290 static $_rTypeFrom = NULL;
5291 static $_rTypeWhere = NULL;
5293 if (!$_rTypeProcessed) {
5294 $_rTypeProcessed = TRUE;
5296 // create temp table with contact ids
5297 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5298 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5299 CRM_Core_DAO
::executeQuery($sql);
5302 REPLACE INTO $tableName ( contact_id )
5308 CRM_Core_DAO
::executeQuery($sql);
5310 $qillMessage = ts('Contacts with a Relationship Type of: ');
5311 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5313 if (is_numeric($this->_displayRelationshipType
)) {
5314 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5316 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5317 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5320 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5321 AND displayRelType.is_active = 1
5325 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5326 if ($dirOne == 'a') {
5327 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5329 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5330 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5334 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5336 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5337 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5341 WHERE displayRelType.relationship_type_id = $relType
5342 AND displayRelType.is_active = 1
5345 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5348 if (strpos($from, $_rTypeFrom) === FALSE) {
5349 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5350 // this happens when we have an event_type in the quert (CRM-7969)
5351 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5352 $from .= $_rTypeFrom;
5353 $where = $_rTypeWhere;
5364 static function caseImportant( $op ) {
5366 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5370 * @param $returnProperties
5375 static function componentPresent( &$returnProperties, $prefix ) {
5376 foreach ($returnProperties as $name => $dontCare ) {
5377 if (substr($name, 0, strlen($prefix)) == $prefix) {
5385 * Builds the necessary structures for all fields that are similar to option value lookups
5387 * @param $name string the name of the field
5388 * @param $op string the sql operator, this function should handle ALL SQL operators
5389 * @param $value string|integer|array depends on the operator and who's calling the query builder
5390 * @param $grouping int the index where to place the where clause
5391 * @param $selectValues
5392 * @param $field array an array that contains various properties of the field identified by $name
5393 * @param $label string The label for this field element
5394 * @param $dataType string The data type for this element
5396 * @param bool $useIDsOnly
5398 * @internal param array $selectValue the key value pairs for this element. This allows us to use this function for things besides option-value pairs
5399 * @return void adds the where clause and qill to the query object
5401 function optionValueQuery(
5409 $dataType = 'String',
5413 if (!empty($selectValues) && !is_array($value) && !empty($selectValues[$value])) {
5414 $qill = $selectValues[$value];
5420 $pseudoFields = array('email_greeting', 'postal_greeting', 'addressee', 'gender_id', 'prefix_id', 'suffix_id', 'communication_style_id');
5422 if (is_numeric($value)) {
5423 $qill = $selectValues[(int ) $value];
5425 elseif ($op == 'IN' ||
$op == 'NOT IN') {
5426 if (is_array($value)) {
5428 $newValues = array();
5429 foreach ($value as $k => $v) {
5430 $intVals[$k] = (int) $k;
5431 $newValues[] = $selectValues[(int) $k];
5434 $value = (in_array($name, $pseudoFields)) ?
$intVals : $newValues;
5435 $qill = implode(', ', $newValues);
5438 elseif (!array_key_exists($value, $selectValues)) {
5439 // its a string, lets get the int value
5440 $value = array_search($value, $selectValues);
5443 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5444 if ($tableName == 'civicrm_contact') {
5445 $wc = "contact_a.$fieldName";
5448 $wc = "$tableName.id";
5452 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5455 if (in_array($name, $pseudoFields)) {
5456 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5457 $wc = "contact_a.{$name}_id";
5459 $dataType = 'Positive';
5460 $value = (!$value) ?
0 : $value;
5463 $this->_qill
[$grouping][] = $label . " $op '$qill'";
5464 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' ||
$op == 'RLIKE')) ?
'=' : $op;
5465 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5469 * function to check and explode a user defined numeric string into an array
5470 * this was the protocol used by search builder in the old old days before we had
5471 * super nice js widgets to do the hard work
5473 * @param string $string
5474 * @param string $dataType the dataType we should check for the values, default integer
5476 * @return bool|array if string does not match the patter
5477 * array of numeric values if string does match the pattern
5480 static function parseSearchBuilderString($string, $dataType = 'Integer') {
5481 $string = trim($string);
5482 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5486 $string = substr($string, 1, -1);
5487 $values = explode(',', $string);
5488 if (empty($values)) {
5492 $returnValues = array();
5493 foreach ($values as $v) {
5494 if ($dataType == 'Integer' && ! is_numeric($v)) {
5497 else if ($dataType == 'String' && ! is_string($v)) {
5500 $returnValues[] = trim($v);
5503 if (empty($returnValues)) {
5507 return $returnValues;
5511 * convert the pseudo constants id's to their names
5513 * @param CRM_Core_DAO dao
5514 * @param bool $return
5518 function convertToPseudoNames(&$dao, $return = FALSE) {
5519 if (empty($this->_pseudoConstantsSelect
)) {
5523 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5524 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5528 if (property_exists($dao, $value['idCol'])) {
5529 $val = $dao->$value['idCol'];
5531 if (CRM_Utils_System
::isNull($val)) {
5534 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5536 $idColumn = "{$key}_id";
5537 $dao->$idColumn = $val;
5539 if ($key == 'state_province_name') {
5540 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5543 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5546 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5547 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5549 // FIX ME: we should potentially move this to component Query and write a wrapper function that
5550 // handles pseudoconstant fixes for all component
5551 elseif ($value['pseudoField'] == 'participant_role') {
5552 $viewRoles = array();
5553 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val) as $k => $v) {
5554 $viewRoles[] = CRM_Event_PseudoConstant
::participantRole($v);
5556 $dao->$key = implode(', ', $viewRoles);
5559 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5560 $dao->$key = $labels[$val];
5563 // return converted values in array format
5565 if (strpos($key, '-') !== FALSE) {
5566 $keyVal = explode('-', $key);
5567 $current = &$values;
5568 $lastElement = array_pop($keyVal);
5569 foreach ($keyVal as $v) {
5570 if (!array_key_exists($v, $current)) {
5571 $current[$v] = array();
5573 $current = &$current[$v];
5575 $current[$lastElement] = $dao->$key;
5578 $values[$key] = $dao->$key;
5587 * include pseudo fields LEFT JOIN
5588 * @param string|array $sort can be a object or string
5592 function includePseudoFieldsJoin($sort) {
5593 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5596 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5599 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5600 if (!empty($value['table'])) {
5601 $regex = "/({$value['table']}\.|{$name})/";
5602 if (preg_match($regex, $sort)) {
5603 $this->_elemnt
[$value['element']] = 1;
5604 $this->_select
[$value['element']] = $value['select'];
5605 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5606 $present[$value['table']] = $value['join'];
5610 $presentSimpleFrom = $present;
5612 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5613 array_key_exists('civicrm_country', $presentSimpleFrom)) {
5614 unset($presentSimpleFrom['civicrm_country']);
5616 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5617 array_key_exists('civicrm_country', $present)) {
5618 unset($present['civicrm_country']);
5621 $presentClause = $presentSimpleFromClause = NULL;
5622 if (!empty($present)) {
5623 $presentClause = implode(' ', $present);
5625 if (!empty($presentSimpleFrom)) {
5626 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5629 $this->_fromClause
= $this->_fromClause
. $presentClause;
5630 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5632 return array($presentClause, $presentSimpleFromClause);