3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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
88 * the set of output params
92 public $_returnProperties;
102 * the name of the elements that are in the select clause
103 * used to extract the values
110 * the tables involved in the query
117 * the table involved in the where clause
121 public $_whereTables;
136 public $_whereClause;
139 * additional permission Where Clause
144 public $_permissionWhereClause;
154 * additional permission from clause
159 public $_permissionFromClause;
162 * the from clause for the simple select and alphabetical
167 public $_simpleFromClause;
178 * The english language version of the query
185 * All the fields that could potentially be involved in
193 * The cache to translate the option values into labels
200 * are we in search mode
204 public $_search = TRUE;
207 * should we skip permission checking
211 public $_skipPermission = FALSE;
214 * should we skip adding of delete clause
218 public $_skipDeleteClause = FALSE;
221 * are we in strict mode (use equality over LIKE)
225 public $_strict = FALSE;
228 * What operator to use to group the clauses
232 public $_operator = 'AND';
237 * Should we only search on primary location
241 public $_primaryLocation = TRUE;
244 * are contact ids part of the query
248 public $_includeContactIds = FALSE;
251 * Should we use the smart group cache
255 public $_smartGroupCache = TRUE;
258 * Should we display contacts with a specific relationship type
262 public $_displayRelationshipType = NULL;
265 * reference to the query object for custom values
269 public $_customQuery;
272 * should we enable the distinct clause, used if we are including
273 * more than one group
277 public $_useDistinct = FALSE;
280 * Should we just display one contact record
282 public $_useGroupBy = FALSE;
285 * the relationship type direction
298 static $_activityRole;
301 * Consider the component activity type
302 * during activity search.
307 static $_considerCompActivities;
310 * Consider with contact activities only,
311 * during activity search.
316 static $_withContactActivitiesOnly;
319 * use distinct component clause for component searches
323 public $_distinctComponentClause;
326 * use groupBy component clause for component searches
330 public $_groupByComponentClause;
333 * Track open panes, useful in advance search
338 public static $_openedPanes = array();
341 * The tables which have a dependency on location and/or address
346 static $_dependencies = array(
347 'civicrm_state_province' => 1,
348 'civicrm_country' => 1,
349 'civicrm_county' => 1,
350 'civicrm_address' => 1,
351 'civicrm_location_type' => 1,
355 * List of location specific fields
357 static $_locationSpecificFields = array(
362 'supplemental_address_1',
363 'supplemental_address_2',
366 'postal_code_suffix',
379 * Rememeber if we handle either end of a number or date range
380 * so we can skip the other
382 protected $_rangeCache = array();
385 * class constructor which also does all the work
387 * @param array $params
388 * @param array $returnProperties
389 * @param array $fields
390 * @param boolean $includeContactIds
391 * @param boolean $strict
392 * @param boolean $mode - mode the search is operating on
397 function __construct(
398 $params = NULL, $returnProperties = NULL, $fields = NULL,
399 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
400 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
401 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
404 $this->_params
= &$params;
405 if ($this->_params
== NULL) {
406 $this->_params
= array();
409 if (empty($returnProperties)) {
410 $this->_returnProperties
= self
::defaultReturnProperties($mode);
413 $this->_returnProperties
= &$returnProperties;
416 $this->_includeContactIds
= $includeContactIds;
417 $this->_strict
= $strict;
418 $this->_mode
= $mode;
419 $this->_skipPermission
= $skipPermission;
420 $this->_smartGroupCache
= $smartGroupCache;
421 $this->_displayRelationshipType
= $displayRelationshipType;
422 $this->setOperator($operator);
425 $this->_fields
= &$fields;
426 $this->_search
= FALSE;
427 $this->_skipPermission
= TRUE;
430 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE);
432 $fields = CRM_Core_Component
::getQueryFields();
433 unset($fields['note']);
434 $this->_fields
= array_merge($this->_fields
, $fields);
436 // add activity fields
437 $fields = CRM_Activity_BAO_Activity
::exportableFields();
438 $this->_fields
= array_merge($this->_fields
, $fields);
441 // basically do all the work once, and then reuse it
446 * function which actually does all the work for the constructor
451 function initialize() {
452 $this->_select
= array();
453 $this->_element
= array();
454 $this->_tables
= array();
455 $this->_whereTables
= array();
456 $this->_where
= array();
457 $this->_qill
= array();
458 $this->_options
= array();
459 $this->_cfIDs
= array();
460 $this->_paramLookup
= array();
461 $this->_having
= array();
463 $this->_customQuery
= NULL;
465 // reset cached static variables - CRM-5803
466 self
::$_activityRole = NULL;
467 self
::$_considerCompActivities = NULL;
468 self
::$_withContactActivitiesOnly = NULL;
470 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
471 $this->_element
['contact_id'] = 1;
472 $this->_tables
['civicrm_contact'] = 1;
474 if (!empty($this->_params
)) {
475 $this->buildParamsLookup();
478 $this->_whereTables
= $this->_tables
;
480 $this->selectClause();
481 $this->_whereClause
= $this->whereClause();
483 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
484 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
486 $this->openedSearchPanes(TRUE);
489 function buildParamsLookup() {
490 // first fix and handle contact deletion nicely
491 // this code is primarily for search builder use case
492 // where different clauses can specify if they want deleted
495 $trashParamExists = FALSE;
496 $paramByGroup = array();
497 foreach ( $this->_params
as $k => $param ) {
498 if ( $param[0] == 'contact_is_deleted' ) {
499 $trashParamExists = TRUE;
501 $paramByGroup[$param[3]][$k] = $param;
504 if ( $trashParamExists ) {
505 $this->_skipDeleteClause
= TRUE;
507 //cycle through group sets and explicitly add trash param if not set
508 foreach ( $paramByGroup as $setID => $set ) {
510 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params
) &&
511 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params
) ) {
512 $this->_params
[] = array(
513 'contact_is_deleted',
523 foreach ($this->_params
as $value) {
524 if (!CRM_Utils_Array
::value(0, $value)) {
527 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
529 if (!array_key_exists($cfID, $this->_cfIDs
)) {
530 $this->_cfIDs
[$cfID] = array();
532 $this->_cfIDs
[$cfID][] = $value;
535 if (!array_key_exists($value[0], $this->_paramLookup
)) {
536 $this->_paramLookup
[$value[0]] = array();
538 $this->_paramLookup
[$value[0]][] = $value;
543 * Some composite fields do not appear in the fields array
544 * hack to make them part of the query
549 function addSpecialFields() {
550 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
551 foreach ($special as $name) {
552 if (CRM_Utils_Array
::value($name, $this->_returnProperties
)) {
553 $this->_select
[$name] = "contact_a.{$name} as $name";
554 $this->_element
[$name] = 1;
560 * Given a list of conditions in params and a list of desired
561 * return Properties generate the required select and from
562 * clauses. Note that since the where clause introduces new
563 * tables, the initial attempt also retrieves all variables used
569 function selectClause() {
570 $properties = array();
572 $this->addSpecialFields();
574 foreach ($this->_fields
as $name => $field) {
576 // skip component fields
577 // there are done by the alter query below
578 // and need not be done on every field
579 if ((substr($name, 0, 12) == 'participant_') ||
580 (substr($name, 0, 7) == 'pledge_') ||
581 (substr($name, 0, 5) == 'case_')
586 // redirect to activity select clause
587 if (substr($name, 0, 9) == 'activity_') {
588 CRM_Activity_BAO_Query
::select($this);
592 // if this is a hierarchical name, we ignore it
593 $names = explode('-', $name);
594 if (count($names > 1) && isset($names[1]) && is_numeric($names[1])) {
598 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
600 if (CRM_Utils_Array
::value($name, $this->_paramLookup
) ||
601 CRM_Utils_Array
::value($name, $this->_returnProperties
)
605 // add to cfIDs array if not present
606 if (!array_key_exists($cfID, $this->_cfIDs
)) {
607 $this->_cfIDs
[$cfID] = array();
610 elseif (isset($field['where'])) {
611 list($tableName, $fieldName) = explode('.', $field['where'], 2);
612 if (isset($tableName)) {
614 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
615 $this->_tables
['civicrm_address'] = 1;
616 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
617 $this->_element
['address_id'] = 1;
620 if ($tableName == 'gender' ||
$tableName == 'individual_prefix'
621 ||
$tableName == 'individual_suffix' ||
$tableName == 'im_provider'
622 ||
$tableName == 'email_greeting' ||
$tableName == 'postal_greeting'
623 ||
$tableName == 'addressee'
625 CRM_Core_OptionValue
::select($this);
626 if (in_array($tableName, array(
627 'email_greeting', 'postal_greeting', 'addressee'))) {
629 $greetField = "{$name}_display";
630 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
631 $this->_element
[$greetField] = 1;
633 $greetField = "{$name}_custom";
634 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
635 $this->_element
[$greetField] = 1;
639 $this->_tables
[$tableName] = 1;
641 // also get the id of the tableName
642 $tName = substr($tableName, 8);
644 if ($tName != 'contact') {
645 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
646 $this->_element
["{$tName}_id"] = 1;
649 //special case for phone
650 if ($name == 'phone') {
651 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
652 $this->_element
['phone_type_id'] = 1;
655 // if IM then select provider_id also
656 // to get "IM Service Provider" in a file to be exported, CRM-3140
658 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
659 $this->_element
['provider_id'] = 1;
662 if ($name == 'state_province') {
663 $this->_select
[$name] = "civicrm_state_province.abbreviation as `$name`, civicrm_state_province.name as state_province_name";
664 $this->_element
['state_province_name'] = 1;
666 elseif ($tName == 'contact') {
667 // special case, when current employer is set for Individual contact
668 if ($fieldName == 'organization_name') {
669 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
671 elseif ($fieldName != 'id') {
672 $this->_select
[$name] = "contact_a.{$fieldName} as `$name`";
676 $this->_select
[$name] = "{$field['where']} as `$name`";
678 $this->_element
[$name] = 1;
682 elseif ($name === 'tags') {
683 $this->_useGroupBy
= TRUE;
684 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
685 $this->_element
[$name] = 1;
686 $this->_tables
['civicrm_tag'] = 1;
687 $this->_tables
['civicrm_entity_tag'] = 1;
689 elseif ($name === 'groups') {
690 $this->_useGroupBy
= TRUE;
691 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
692 $this->_element
[$name] = 1;
693 $this->_tables
['civicrm_group'] = 1;
695 elseif ($name === 'notes') {
696 $this->_useGroupBy
= TRUE;
697 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.note)) as notes";
698 $this->_element
[$name] = 1;
699 $this->_tables
['civicrm_note'] = 1;
701 elseif ($name === 'current_employer') {
702 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
703 $this->_element
[$name] = 1;
708 CRM_Utils_Array
::value('is_search_range', $field)
710 // this is a custom field with range search enabled, so we better check for two/from values
711 if (CRM_Utils_Array
::value($name . '_from', $this->_paramLookup
)) {
712 if (!array_key_exists($cfID, $this->_cfIDs
)) {
713 $this->_cfIDs
[$cfID] = array();
715 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
716 // search in the cdID array for the same grouping
718 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
719 if ($c[3] == $p[3]) {
720 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
725 $p[2] = array('from' => $p[2]);
726 $this->_cfIDs
[$cfID][] = $p;
730 if (CRM_Utils_Array
::value($name . '_to', $this->_paramLookup
)) {
731 if (!array_key_exists($cfID, $this->_cfIDs
)) {
732 $this->_cfIDs
[$cfID] = array();
734 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
735 // search in the cdID array for the same grouping
737 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
738 if ($c[4] == $p[4]) {
739 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
744 $p[2] = array('to' => $p[2]);
745 $this->_cfIDs
[$cfID][] = $p;
752 // add location as hierarchical elements
753 $this->addHierarchicalElements();
755 // add multiple field like website
756 $this->addMultipleElements();
759 CRM_Core_Component
::alterQuery($this, 'select');
761 if (!empty($this->_cfIDs
)) {
762 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE);
763 $this->_customQuery
->query();
764 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
765 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
766 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
767 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
768 $this->_options
= $this->_customQuery
->_options
;
773 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
779 function addHierarchicalElements() {
780 if (!CRM_Utils_Array
::value('location', $this->_returnProperties
)) {
783 if (!is_array($this->_returnProperties
['location'])) {
787 $locationTypes = CRM_Core_PseudoConstant
::locationType();
788 $processed = array();
791 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
792 $addressCustomFieldIds = array();
794 foreach ($this->_returnProperties
['location'] as $name => $elements) {
795 $lCond = self
::getPrimaryCondition($name);
798 $locationTypeId = array_search($name, $locationTypes);
799 if ($locationTypeId === FALSE) {
802 $lCond = "location_type_id = $locationTypeId";
803 $this->_useDistinct
= TRUE;
805 //commented for CRM-3256
806 $this->_useGroupBy
= TRUE;
809 $name = str_replace(' ', '_', $name);
811 $tName = "$name-location_type";
812 $ltName = "`$name-location_type`";
813 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
814 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
815 $this->_element
["{$tName}_id"] = 1;
816 $this->_element
["{$tName}"] = 1;
818 $locationTypeName = $tName;
819 $locationTypeJoin = array();
823 foreach ($elements as $elementFullName => $dontCare) {
825 $elementName = $elementCmpName = $elementFullName;
827 if (substr($elementCmpName, 0, 5) == 'phone') {
828 $elementCmpName = 'phone';
831 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
832 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
833 $addressCustomFieldIds[$cfID][$name] = 1;
836 //add address table only once
837 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
839 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
841 $tName = "$name-address";
842 $aName = "`$name-address`";
843 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
844 $this->_element
["{$tName}_id"] = 1;
845 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
846 $this->_tables
[$tName] = $addressJoin;
847 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
848 $processed[$aName] = 1;
852 $cond = $elementType = '';
853 if (strpos($elementName, '-') !== FALSE) {
854 // this is either phone, email or IM
855 list($elementName, $elementType) = explode('-', $elementName);
858 if (($elementName != 'phone') && ($elementName != 'im')) {
859 $cond = self
::getPrimaryCondition($elementType);
861 if ((!$cond) && ($elementName == 'phone')) {
862 $cond = "phone_type_id = '$elementType'";
864 elseif ((!$cond) && ($elementName == 'im')) {
865 // IM service provider id, CRM-3140
866 $cond = "provider_id = '$elementType'";
868 $elementType = '-' . $elementType;
871 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
873 // hack for profile, add location id
876 // fix for CRM-882( to handle phone types )
877 !is_numeric($elementType)
879 if (is_numeric($name)) {
880 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
883 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
886 elseif (is_numeric($name)) {
887 //this for phone type to work
888 if (in_array($elementName, array('phone', 'phone_ext'))) {
889 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
892 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
896 //this is for phone type to work for profile edit
897 if (in_array($elementName, array('phone', 'phone_ext'))) {
898 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
901 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
906 // check if there is a value, if so also add to where Clause
908 if ($this->_params
) {
910 if (isset($locationTypeId)) {
911 $nm .= "-$locationTypeId";
913 if (!is_numeric($elementType)) {
914 $nm .= "$elementType";
917 foreach ($this->_params
as $id => $values) {
918 if ($values[0] == $nm ||
919 (in_array($elementName, array('phone', 'im'))
920 && (strpos($values[0], $nm) !== FALSE)
930 if ($field && isset($field['where'])) {
931 list($tableName, $fieldName) = explode('.', $field['where'], 2);
932 $tName = $name . '-' . substr($tableName, 8) . $elementType;
933 if (isset($tableName)) {
934 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
935 $this->_element
["{$tName}_id"] = 1;
936 if (substr($tName, -15) == '-state_province') {
937 // FIXME: hack to fix CRM-1900
938 $a = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
942 if (substr_count($a, 'state_province_name') > 0) {
943 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.name as `{$name}-{$elementFullName}`";
946 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
950 if (substr($elementFullName, 0, 2) == 'im') {
951 $provider = "{$name}-{$elementFullName}-provider_id";
952 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
953 $this->_element
[$provider] = 1;
956 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
959 $this->_element
["{$name}-{$elementFullName}"] = 1;
960 if (!CRM_Utils_Array
::value("`$tName`", $processed)) {
961 $processed["`$tName`"] = 1;
962 $newName = $tableName . '_' . $index;
963 switch ($tableName) {
964 case 'civicrm_phone':
965 case 'civicrm_email':
967 case 'civicrm_openid':
969 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id AND `$tName`.$lCond";
970 // this special case to add phone type
972 $phoneTypeCondition = " AND `$tName`.$cond ";
973 //gross hack to pickup corrupted data also, CRM-7603
974 if (strpos($cond, 'phone_type_id') !== FALSE) {
975 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
977 $this->_tables
[$tName] .= $phoneTypeCondition;
980 //build locationType join
981 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
984 $this->_whereTables
[$tName] = $this->_tables
[$tName];
988 case 'civicrm_state_province':
989 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
991 $this->_whereTables
["{$name}-address"] = $addressJoin;
992 $this->_whereTables
[$tName] = $this->_tables
[$tName];
996 case 'civicrm_country':
997 $this->_tables
[$newName] = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
999 $this->_whereTables
["{$name}-address"] = $addressJoin;
1000 $this->_whereTables
[$newName] = $this->_tables
[$newName];
1004 case 'civicrm_county':
1005 $this->_tables
[$newName] = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1007 $this->_whereTables
["{$name}-address"] = $addressJoin;
1008 $this->_whereTables
[$newName] = $this->_tables
[$newName];
1014 $this->_whereTables
["{$name}-address"] = $addressJoin;
1023 // add location type join
1024 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1025 $this->_tables
[$locationTypeName] = $ltypeJoin;
1027 // table should be present in $this->_whereTables,
1028 // to add its condition in location type join, CRM-3939.
1029 if ($addWhereCount) {
1030 $locClause = array();
1031 foreach ($this->_whereTables
as $tableName => $clause) {
1032 if (CRM_Utils_Array
::value($tableName, $locationTypeJoin)) {
1033 $locClause[] = $locationTypeJoin[$tableName];
1037 if (!empty($locClause)) {
1038 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1043 if (!empty($addressCustomFieldIds)) {
1044 $cfIDs = $addressCustomFieldIds;
1045 $customQuery = new CRM_Core_BAO_CustomQuery($cfIDs);
1046 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1047 foreach ($locTypeName as $name => $dnc) {
1048 $fieldName = "$name-custom_{$cfID}";
1049 $tName = "$name-address-custom-{$cfID}";
1050 $aName = "`$name-address-custom-{$cfID}`";
1051 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1052 $this->_element
["{$tName}_id"] = 1;
1053 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1054 $this->_element
[$fieldName] = 1;
1055 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1062 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
1068 function addMultipleElements() {
1069 if (!CRM_Utils_Array
::value('website', $this->_returnProperties
)) {
1072 if (!is_array($this->_returnProperties
['website'])) {
1076 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1077 foreach ($elements as $elementFullName => $dontCare) {
1078 $tName = "website-{$key}-{$elementFullName}";
1079 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1080 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1081 $this->_element
["{$tName}_id"] = 1;
1082 $this->_element
["{$tName}"] = 1;
1084 $type = "website-{$key}-website_type_id";
1085 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1086 $this->_element
[$type] = 1;
1087 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id )";
1093 * generate the query based on what type of query we need
1095 * @param boolean $count
1096 * @param boolean $sortByChar
1097 * @param boolean $groupContacts
1099 * @return the sql string for that query (this will most likely
1103 function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE) {
1105 if (isset($this->_distinctComponentClause
)) {
1106 // we add distinct to get the right count for components
1107 // for the more complex result set, we use GROUP BY the same id
1109 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1112 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1114 $from = $this->_simpleFromClause
;
1115 if ($this->_useDistinct
) {
1116 $this->_useGroupBy
= TRUE;
1119 elseif ($sortByChar) {
1120 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1121 $from = $this->_simpleFromClause
;
1123 elseif ($groupContacts) {
1124 $select = 'SELECT contact_a.id as id';
1125 if ($this->_useDistinct
) {
1126 $this->_useGroupBy
= TRUE;
1128 $from = $this->_simpleFromClause
;
1131 if (CRM_Utils_Array
::value('group', $this->_paramLookup
)) {
1132 // make sure there is only one element
1133 // this is used when we are running under smog and need to know
1134 // how the contact was added (CRM-1203)
1135 if ((count($this->_paramLookup
['group']) == 1) &&
1136 (count($this->_paramLookup
['group'][0][2]) == 1)
1138 $groups = array_keys($this->_paramLookup
['group'][0][2]);
1139 $groupId = $groups[0];
1141 //check if group is saved search
1142 $group = new CRM_Contact_BAO_Group();
1143 $group->id
= $groupId;
1146 if (!isset($group->saved_search_id
)) {
1147 $tbName = "`civicrm_group_contact-{$groupId}`";
1148 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1149 $this->_element
['group_contact_id'] = 1;
1150 $this->_select
['status'] = "$tbName.status as status";
1151 $this->_element
['status'] = 1;
1152 $this->_tables
[$tbName] = 1;
1155 $this->_useGroupBy
= TRUE;
1157 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1158 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1160 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1161 $this->_useDistinct
= FALSE;
1162 $this->_useGroupBy
= TRUE;
1166 $select = "SELECT ";
1167 if (isset($this->_distinctComponentClause
)) {
1168 $select .= "{$this->_distinctComponentClause}, ";
1170 $select .= implode(', ', $this->_select
);
1171 $from = $this->_fromClause
;
1175 if (!empty($this->_whereClause
)) {
1176 $where = "WHERE {$this->_whereClause}";
1180 if (!empty($this->_having
)) {
1181 foreach ($this->_having
as $havingsets) {
1182 foreach ($havingsets as $havingset) {
1183 $havingvalue[] = $havingset;
1186 $having = ' HAVING ' . implode(' AND ', $havingvalue);
1189 // if we are doing a transform, do it here
1190 // use the $from, $where and $having to get the contact ID
1191 if ($this->_displayRelationshipType
) {
1192 $this->filterRelatedContacts($from, $where, $having);
1195 return array($select, $from, $where, $having);
1198 function &getWhereValues($name, $grouping) {
1200 foreach ($this->_params
as $id => $values) {
1201 if ($values[0] == $name && $values[3] == $grouping) {
1209 static function fixDateValues($relative, &$from, &$to) {
1211 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1215 static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE) {
1217 if (empty($formValues)) {
1221 foreach ($formValues as $id => $values) {
1222 if ($id == 'privacy') {
1223 if (is_array($formValues['privacy'])) {
1224 $op = CRM_Utils_Array
::value('do_not_toggle', $formValues['privacy']) ?
'=' : '!=';
1225 foreach ($formValues['privacy'] as $key => $value) {
1227 $params[] = array($key, $op, $value, 0, 0);
1232 elseif ($id == 'email_on_hold') {
1233 if ($formValues['email_on_hold']['on_hold']) {
1234 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1237 elseif (preg_match('/_date_relative$/', $id) ||
1238 $id == 'event_relative' ||
1239 $id == 'case_from_relative' ||
1240 $id == 'case_to_relative'
1242 if ($id == 'event_relative') {
1243 $fromRange = 'event_start_date_low';
1244 $toRange = 'event_end_date_high';
1246 else if ($id == 'case_from_relative') {
1247 $fromRange = 'case_from_start_date_low';
1248 $toRange = 'case_from_start_date_high';
1250 else if ($id == 'case_to_relative') {
1251 $fromRange = 'case_to_end_date_low';
1252 $toRange = 'case_to_end_date_high';
1255 $dateComponent = explode('_date_relative', $id);
1256 $fromRange = "{$dateComponent[0]}_date_low";
1257 $toRange = "{$dateComponent[0]}_date_high";
1260 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1261 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1266 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals);
1271 $params[] = $values;
1277 static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE) {
1278 // skip a few search variables
1279 static $skipWhere = NULL;
1280 static $arrayValues = NULL;
1281 static $likeNames = NULL;
1284 if (CRM_Utils_System
::isNull($values)) {
1290 'task', 'radio_ts', 'uf_group_id',
1291 'component_mode', 'qfKey', 'operator',
1292 'display_relationship_type',
1296 if (in_array($id, $skipWhere) ||
1297 substr($id, 0, 4) == '_qf_' ||
1298 substr($id, 0, 7) == 'hidden_'
1304 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1307 // email comes in via advanced search
1308 // so use wildcard always
1309 if ($id == 'email') {
1313 if (!$useEquals && in_array($id, $likeNames)) {
1314 $result = array($id, 'LIKE', $values, 0, 1);
1316 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1317 $result = array($id, 'LIKE', $values, 0, 0);
1319 elseif ($id == 'group') {
1320 if (is_array($values)) {
1321 foreach ($values as $groupIds => $val) {
1323 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1324 if (strlen($matches[1]) > 0) {
1325 $values[$matches[1]] = 1;
1326 unset($values[$groupIds]);
1332 $groupIds = explode(',', $values);
1334 foreach ($groupIds as $groupId) {
1335 $values[$groupId] = 1;
1339 $result = array($id, 'IN', $values, 0, 0);
1341 elseif ($id == 'contact_tags' ||
$id == 'tag') {
1342 if (!is_array($values)) {
1343 $tagIds = explode(',', $values);
1345 foreach ($tagIds as $tagId) {
1346 $values[$tagId] = 1;
1349 $result = array($id, 'IN', $values, 0, 0);
1352 $result = array($id, '=', $values, 0, $wildcard);
1358 function whereClauseSingle(&$values) {
1359 // do not process custom fields or prefixed contact ids or component params
1360 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1361 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1362 (substr($values[0], 0, 13) == 'contribution_') ||
1363 (substr($values[0], 0, 6) == 'event_') ||
1364 (substr($values[0], 0, 12) == 'participant_') ||
1365 (substr($values[0], 0, 7) == 'member_') ||
1366 (substr($values[0], 0, 6) == 'grant_') ||
1367 (substr($values[0], 0, 7) == 'pledge_') ||
1368 (substr($values[0], 0, 5) == 'case_') ||
1369 (substr($values[0], 0, 10) == 'financial_')
1374 switch ($values[0]) {
1375 case 'deleted_contacts':
1376 $this->deletedContacts($values);
1379 case 'contact_type':
1380 $this->contactType($values);
1383 case 'contact_sub_type':
1384 $this->contactSubType($values);
1388 list($name, $op, $value, $grouping, $wildcard) = $values;
1389 $this->group($values);
1392 // so we resolve this into a list of groups & proceed as if they had been
1394 list($name, $op, $value, $grouping, $wildcard) = $values;
1395 $values[0] = 'group';
1397 $this->_paramLookup
['group'][0][0] ='group';
1398 $this->_paramLookup
['group'][0][1] = 'IN';
1399 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1400 $this->group($values);
1402 // case tag comes from find contacts
1405 $this->tagSearch($values);
1409 case 'contact_tags':
1410 $this->tag($values);
1415 case 'note_subject':
1416 $this->notes($values);
1420 $this->ufUser($values);
1424 case 'display_name':
1425 $this->sortName($values);
1426 //force civicrm_activity_target, CRM-7812
1427 self
::$_withContactActivitiesOnly = TRUE;
1431 $this->email($values);
1434 case 'phone_numeric':
1435 $this->phone_numeric($values);
1438 case 'phone_phone_type_id':
1439 case 'phone_location_type_id':
1440 $this->phone_option_group($values);
1443 case 'street_address':
1444 $this->street_address($values);
1447 case 'street_number':
1448 $this->street_number($values);
1451 case 'sortByCharacter':
1452 $this->sortByCharacter($values);
1455 case 'location_type':
1456 $this->locationType($values);
1460 $this->county($values);
1463 case 'state_province':
1464 $this->stateProvince($values);
1468 $this->country($values, FALSE);
1472 case 'postal_code_low':
1473 case 'postal_code_high':
1474 $this->postalCode($values);
1477 case 'activity_date':
1478 case 'activity_date_low':
1479 case 'activity_date_high':
1480 case 'activity_role':
1481 case 'activity_status':
1482 case 'activity_subject':
1483 case 'test_activities':
1484 case 'activity_type_id':
1485 case 'activity_survey_id':
1486 case 'activity_tags':
1487 case 'activity_taglist':
1488 case 'activity_test':
1489 case 'activity_contact_name':
1490 case 'activity_campaign_id':
1491 case 'activity_engagement_level':
1493 case 'source_contact':
1494 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1497 case 'birth_date_low':
1498 case 'birth_date_high':
1499 case 'deceased_date_low':
1500 case 'deceased_date_high':
1501 $this->demographics($values);
1504 case 'log_date_low':
1505 case 'log_date_high':
1506 $this->modifiedDates($values);
1510 $this->changeLog($values);
1513 case 'do_not_phone':
1514 case 'do_not_email':
1517 case 'do_not_trade':
1519 $this->privacy($values);
1522 case 'privacy_options':
1523 $this->privacyOptions($values);
1526 case 'privacy_operator':
1527 case 'privacy_toggle':
1528 // these are handled by privacy options
1531 case 'preferred_communication_method':
1532 $this->preferredCommunication($values);
1535 case 'relation_type_id':
1536 $this->relationship($values);
1539 case 'relation_target_name':
1540 case 'relation_status':
1541 case 'relation_date_low':
1542 case 'relation_date_high':
1543 // since this case is handled with the above
1546 case 'task_status_id':
1547 $this->task($values);
1551 // since this case is handled with the above
1554 case 'prox_distance':
1555 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1558 case 'prox_street_address':
1560 case 'prox_postal_code':
1561 case 'prox_state_province_id':
1562 case 'prox_country_id':
1563 // handled by the proximity_distance clause
1567 $this->restWhere($values);
1573 * Given a list of conditions in params generate the required
1579 function whereClause() {
1580 $this->_where
[0] = array();
1581 $this->_qill
[0] = array();
1583 $config = CRM_Core_Config
::singleton();
1585 $this->includeContactIds();
1586 if (!empty($this->_params
)) {
1588 foreach (array_keys($this->_params
) as $id) {
1589 if (!CRM_Utils_Array
::value(0, $this->_params
[$id])) {
1592 // check for both id and contact_id
1593 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
1595 $this->_params
[$id][1] == 'IS NULL' ||
1596 $this->_params
[$id][1] == 'IS NOT NULL'
1598 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]}";
1600 elseif (is_array($this->_params
[$id][2])) {
1601 $idList = implode("','", $this->_params
[$id][2]);
1602 $this->_where
[0][] = "contact_a.id IN ({$idList})";
1605 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]} {$this->_params[$id][2]}";
1609 $this->whereClauseSingle($this->_params
[$id]);
1613 CRM_Core_Component
::alterQuery($this, 'where');
1616 if ($this->_customQuery
) {
1617 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1618 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1619 if (!empty($this->_customQuery
->_where
)) {
1620 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
1623 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
1627 $andClauses = array();
1630 if (!empty($this->_where
)) {
1631 foreach ($this->_where
as $grouping => $values) {
1632 if ($grouping > 0 && !empty($values)) {
1633 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1638 if (!empty($this->_where
[0])) {
1639 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
1641 if (!empty($clauses)) {
1642 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1645 if ($validClauses > 1) {
1646 $this->_useDistinct
= TRUE;
1650 return implode(' AND ', $andClauses);
1653 function restWhere(&$values) {
1654 $name = CRM_Utils_Array
::value(0, $values);
1655 $op = CRM_Utils_Array
::value(1, $values);
1656 $value = CRM_Utils_Array
::value(2, $values);
1657 $grouping = CRM_Utils_Array
::value(3, $values);
1658 $wildcard = CRM_Utils_Array
::value(4, $values);
1660 if (isset($grouping) && !CRM_Utils_Array
::value($grouping, $this->_where
)) {
1661 $this->_where
[$grouping] = array();
1664 $multipleFields = array('url');
1666 //check if the location type exits for fields
1668 $locType = explode('-', $name);
1670 if (!in_array($locType[0], $multipleFields)) {
1671 //add phone type if exists
1672 if (isset($locType[2]) && $locType[2]) {
1673 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
1677 $field = CRM_Utils_Array
::value($name, $this->_fields
);
1680 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
1689 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
1691 if (substr($name, 0, 14) === 'state_province') {
1692 if (isset($locType[1]) && is_numeric($locType[1])) {
1695 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
1696 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1697 $where = "`$tName`.$fldName";
1700 $where = $field['where'];
1703 if (is_numeric($value)) {
1704 $where = str_replace('.name', '.id', $where);
1705 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1706 $states = CRM_Core_PseudoConstant
::stateProvince();
1707 $value = $states[(int ) $value];
1710 $wc = self
::caseImportant($op) ?
"LOWER($where)" : $where;
1711 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, 'String');
1714 $this->_qill
[$grouping][] = ts('State') . " $op '$value'";
1717 $this->_qill
[$grouping][] = ts('State') . " ($lType) $op '$value'";
1720 elseif (substr($name, 0, 7) === 'country') {
1721 if (isset($locType[1]) && is_numeric($locType[1])) {
1724 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
1725 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1726 $where = "`$tName`.$fldName";
1729 $where = $field['where'];
1732 if (is_numeric($value)) {
1733 $where = str_replace('.name', '.id', $where);
1734 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1735 $countries = CRM_Core_PseudoConstant
::country();
1736 $value = $countries[(int ) $value];
1739 $wc = self
::caseImportant($op) ?
"LOWER($where)" : $where;
1740 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, 'String');
1743 $this->_qill
[$grouping][] = ts('Country') . " $op '$value'";
1746 $this->_qill
[$grouping][] = ts('Country') . " ($lType) $op '$value'";
1749 elseif (substr($name, 0, 6) === 'county') {
1750 if (isset($locType[1]) && is_numeric($locType[1])) {
1753 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
1754 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1755 $where = "`$tName`.$fldName";
1758 $where = $field['where'];
1760 if (is_numeric($value)) {
1761 $where = str_replace('.name', '.id', $where);
1762 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1763 $counties = CRM_Core_PseudoConstant
::county();
1764 $value = $counties[(int ) $value];
1767 $wc = self
::caseImportant($op) ?
"LOWER($where)" : $where;
1768 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, 'String');
1772 $this->_qill
[$grouping][] = ts('County') . " $op '$value'";
1775 $this->_qill
[$grouping][] = ts('County') . " ($lType) $op '$value'";
1778 elseif ($name === 'world_region') {
1779 $this->optionValueQuery(
1780 $name, $op, $value, $grouping,
1781 CRM_Core_PseudoConstant
::worldRegion(),
1786 elseif ($name === 'individual_prefix') {
1787 $this->optionValueQuery(
1788 $name, $op, $value, $grouping,
1789 CRM_Core_PseudoConstant
::individualPrefix(),
1791 ts('Individual Prefix')
1794 elseif ($name === 'individual_suffix') {
1795 $this->optionValueQuery(
1796 $name, $op, $value, $grouping,
1797 CRM_Core_PseudoConstant
::individualSuffix(),
1799 ts('Individual Suffix')
1802 elseif ($name === 'gender') {
1803 $this->optionValueQuery(
1804 $name, $op, $value, $grouping,
1805 CRM_Core_PseudoConstant
::gender(),
1809 self
::$_openedPanes[ts('Demographics')] = TRUE;
1811 elseif ($name === 'birth_date') {
1812 $date = CRM_Utils_Date
::processDate($value);
1813 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
1816 $date = CRM_Utils_Date
::customFormat($date);
1817 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
1820 $this->_qill
[$grouping][] = "$field[title] $op";
1822 self
::$_openedPanes[ts('Demographics')] = TRUE;
1824 elseif ($name === 'deceased_date') {
1825 $date = CRM_Utils_Date
::processDate($value);
1826 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
1828 $date = CRM_Utils_Date
::customFormat($date);
1829 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
1832 $this->_qill
[$grouping][] = "$field[title] $op";
1834 self
::$_openedPanes[ts('Demographics')] = TRUE;
1836 elseif ($name === 'is_deceased') {
1837 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
1838 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
1839 self
::$_openedPanes[ts('Demographics')] = TRUE;
1841 elseif ($name === 'contact_id') {
1842 if (is_int($value)) {
1843 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
1844 $this->_qill
[$grouping][] = "$field[title] $op $value";
1847 elseif ($name === 'name') {
1848 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
1850 $value = "%$value%";
1853 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
1854 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
1855 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
1857 elseif ($name === 'current_employer') {
1858 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
1860 $value = "%$value%";
1863 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
1864 $this->_where
[$grouping][] = self
::buildClause($wc, $op,
1865 "'$value' AND contact_a.contact_type ='Individual'"
1867 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
1869 elseif ($name === 'email_greeting') {
1870 $filterCondition = array('greeting_type' => 'email_greeting');
1871 $this->optionValueQuery(
1872 $name, $op, $value, $grouping,
1873 CRM_Core_PseudoConstant
::greeting($filterCondition),
1875 ts('Email Greeting')
1878 elseif ($name === 'postal_greeting') {
1879 $filterCondition = array('greeting_type' => 'postal_greeting');
1880 $this->optionValueQuery(
1881 $name, $op, $value, $grouping,
1882 CRM_Core_PseudoConstant
::greeting($filterCondition),
1884 ts('Postal Greeting')
1887 elseif ($name === 'addressee') {
1888 $filterCondition = array('greeting_type' => 'addressee');
1889 $this->optionValueQuery(
1890 $name, $op, $value, $grouping,
1891 CRM_Core_PseudoConstant
::greeting($filterCondition),
1896 elseif (substr($name, 0, 4) === 'url-') {
1897 $tName = 'civicrm_website';
1898 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
1899 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
1901 $value = "%$value%";
1905 $wc = 'civicrm_website.url';
1906 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
1907 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
1909 elseif ($name === 'contact_is_deleted') {
1910 $this->_where
[$grouping][] = self
::buildClause("contact_a.is_deleted", $op, $value);
1911 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
1914 // sometime the value is an array, need to investigate and fix
1915 if (is_array($value)) {
1916 CRM_Core_Error
::fatal();
1919 if (!empty($field['where'])) {
1921 $value = $strtolower($value);
1924 $value = "%$value%";
1928 if (isset($locType[1]) &&
1929 is_numeric($locType[1])
1933 //get the location name
1934 $locationType = CRM_Core_PseudoConstant
::locationType();
1935 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
1937 $where = "`$tName`.$fldName";
1939 $this->_where
[$grouping][] = self
::buildClause("LOWER($where)", $op, $value);
1940 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1941 $this->_qill
[$grouping][] = "$field[title] $op '$value'";
1944 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1945 if ($tableName == 'civicrm_contact') {
1946 $fieldName = "LOWER(contact_a.{$fieldName})";
1949 if ($op != 'IN' && !is_numeric($value)) {
1950 $fieldName = "LOWER({$field['where']})";
1953 $fieldName = "{$field['where']}";
1958 if (CRM_Utils_Array
::value('type', $field)) {
1959 $type = CRM_Utils_Type
::typeToString($field['type']);
1962 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
1963 $this->_qill
[$grouping][] = "$field[title] $op $value";
1968 if ($setTables && isset($field['where'])) {
1969 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1970 if (isset($tableName)) {
1971 $this->_tables
[$tableName] = 1;
1972 $this->_whereTables
[$tableName] = 1;
1978 static function getLocationTableName(&$where, &$locType) {
1979 if (isset($locType[1]) && is_numeric($locType[1])) {
1980 list($tbName, $fldName) = explode(".", $where);
1982 //get the location name
1983 $locationType = CRM_Core_PseudoConstant
::locationType();
1984 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
1985 if (in_array($locType[0], $specialFields)) {
1986 //hack to fix / special handing for phone_ext
1987 if ($locType[0] == 'phone_ext') {
1988 $locType[0] = 'phone';
1990 if (isset($locType[2]) && $locType[2]) {
1991 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
1994 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
1997 elseif (in_array($locType[0],
1999 'address_name', 'street_address', 'supplemental_address_1', 'supplemental_address_2',
2000 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
2003 //fix for search by profile with address fields.
2004 $tName = "{$locationType[$locType[1]]}-address";
2006 elseif ($locType[0] == 'on_hold') {
2007 $tName = "{$locationType[$locType[1]]}-email";
2010 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2012 $tName = str_replace(' ', '_', $tName);
2013 return array($tName, $fldName);
2015 CRM_Core_Error
::fatal();
2019 * Given a result dao, extract the values and return that array
2021 * @param Object $dao
2023 * @return array values for this query
2025 function store($dao) {
2028 foreach ($this->_element
as $key => $dontCare) {
2029 if (property_exists($dao, $key)) {
2030 if (strpos($key, '-') !== FALSE) {
2031 $values = explode('-', $key);
2032 $lastElement = array_pop($values);
2034 $cnt = count($values);
2036 foreach ($values as $v) {
2037 if (!array_key_exists($v, $current)) {
2038 $current[$v] = array();
2040 //bad hack for im_provider
2041 if ($lastElement == 'provider_id') {
2042 if ($count < $cnt) {
2043 $current = &$current[$v];
2046 $lastElement = "{$v}_{$lastElement}";
2050 $current = &$current[$v];
2055 $current[$lastElement] = $dao->$key;
2058 $value[$key] = $dao->$key;
2066 * getter for tables array
2072 return $this->_tables
;
2075 function whereTables() {
2076 return $this->_whereTables
;
2080 * generate the where clause (used in match contacts and permissions)
2082 * @param array $params
2083 * @param array $fields
2084 * @param array $tables
2085 * @param boolean $strict
2091 static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2092 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2096 $tables = array_merge($query->tables(), $tables);
2097 $whereTables = array_merge($query->whereTables(), $whereTables);
2099 return $query->_whereClause
;
2103 * create the from clause
2105 * @param array $tables tables that need to be included in this from clause
2106 * if null, return mimimal from clause (i.e. civicrm_contact)
2107 * @param array $inner tables that should be inner-joined
2108 * @param array $right tables that should be right-joined
2110 * @return string the from clause
2114 static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2116 $from = ' FROM civicrm_contact contact_a';
2117 if (empty($tables)) {
2121 if (CRM_Utils_Array
::value('civicrm_worldregion', $tables)) {
2122 $tables = array_merge(array('civicrm_country' => 1), $tables);
2125 if ((CRM_Utils_Array
::value('civicrm_state_province', $tables) ||
2126 CRM_Utils_Array
::value('civicrm_country', $tables) ||
2127 CRM_Utils_Array
::value('civicrm_county', $tables)
2129 !CRM_Utils_Array
::value('civicrm_address', $tables)
2131 $tables = array_merge(array('civicrm_address' => 1),
2136 // add group_contact table if group table is present
2137 if (CRM_Utils_Array
::value('civicrm_group', $tables) &&
2138 !CRM_Utils_Array
::value('civicrm_group_contact', $tables)
2140 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
2143 // add group_contact and group table is subscription history is present
2144 if (CRM_Utils_Array
::value('civicrm_subscription_history', $tables)
2145 && !CRM_Utils_Array
::value('civicrm_group', $tables)
2147 $tables = array_merge(array(
2148 'civicrm_group' => 1,
2149 'civicrm_group_contact' => 1,
2155 // to handle table dependencies of components
2156 CRM_Core_Component
::tableNames($tables);
2158 //format the table list according to the weight
2159 $info = CRM_Core_TableHierarchy
::info();
2161 foreach ($tables as $key => $value) {
2163 if (strpos($key, '-') !== FALSE) {
2164 $keyArray = explode('-', $key);
2165 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2167 elseif (strpos($key, '_') !== FALSE) {
2168 $keyArray = explode('_', $key);
2169 if (is_numeric(array_pop($keyArray))) {
2170 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2173 $k = CRM_Utils_Array
::value($key, $info, 99);
2177 $k = CRM_Utils_Array
::value($key, $info, 99);
2179 $tempTable[$k . ".$key"] = $key;
2182 $newTables = array();
2183 foreach ($tempTable as $key) {
2184 $newTables[$key] = $tables[$key];
2187 $tables = $newTables;
2189 foreach ($tables as $name => $value) {
2194 if (CRM_Utils_Array
::value($name, $inner)) {
2197 elseif (CRM_Utils_Array
::value($name, $right)) {
2205 // if there is already a join statement in value, use value itself
2206 if (strpos($value, 'JOIN')) {
2207 $from .= " $value ";
2210 $from .= " $side JOIN $name ON ( $value ) ";
2215 case 'civicrm_address':
2216 if ($primaryLocation) {
2217 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2220 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2224 case 'civicrm_phone':
2225 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2228 case 'civicrm_email':
2229 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2233 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2237 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2238 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2239 $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)";
2242 case 'civicrm_openid':
2243 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2246 case 'civicrm_state_province':
2247 $from .= " $side JOIN civicrm_state_province ON civicrm_address.state_province_id = civicrm_state_province.id ";
2250 case 'civicrm_country':
2251 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2254 case 'civicrm_worldregion':
2255 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2258 case 'civicrm_county':
2259 $from .= " $side JOIN civicrm_county ON civicrm_address.county_id = civicrm_county.id ";
2262 case 'civicrm_location_type':
2263 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2266 case 'civicrm_group':
2267 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2270 case 'civicrm_group_contact':
2271 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2274 case 'civicrm_activity':
2275 case 'civicrm_activity_tag':
2276 case 'activity_type':
2277 case 'activity_status':
2278 case 'civicrm_activity_contact':
2279 case 'source_contact':
2280 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2283 case 'civicrm_entity_tag':
2284 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2285 civicrm_entity_tag.entity_id = contact_a.id ) ";
2288 case 'civicrm_note':
2289 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2290 contact_a.id = civicrm_note.entity_id ) ";
2293 case 'civicrm_subscription_history':
2294 $from .= " $side JOIN civicrm_subscription_history
2295 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2296 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2299 case 'individual_prefix':
2300 $from .= " $side JOIN civicrm_option_group option_group_prefix ON (option_group_prefix.name = 'individual_prefix')";
2301 $from .= " $side JOIN civicrm_option_value individual_prefix ON (contact_a.prefix_id = individual_prefix.value AND option_group_prefix.id = individual_prefix.option_group_id ) ";
2304 case 'individual_suffix':
2305 $from .= " $side JOIN civicrm_option_group option_group_suffix ON (option_group_suffix.name = 'individual_suffix')";
2306 $from .= " $side JOIN civicrm_option_value individual_suffix ON (contact_a.suffix_id = individual_suffix.value AND option_group_suffix.id = individual_suffix.option_group_id ) ";
2310 $from .= " $side JOIN civicrm_option_group option_group_gender ON (option_group_gender.name = 'gender')";
2311 $from .= " $side JOIN civicrm_option_value gender ON (contact_a.gender_id = gender.value AND option_group_gender.id = gender.option_group_id) ";
2314 case 'civicrm_relationship':
2315 if (self
::$_relType == 'reciprocal') {
2316 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2317 $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)";
2319 elseif (self
::$_relType == 'b') {
2320 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2321 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2324 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2325 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2330 $from .= " $side JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2331 $from .= " $side JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2335 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2338 case 'civicrm_task_status':
2339 $from .= " $side JOIN civicrm_task_status ON ( civicrm_task_status.responsible_entity_table = 'civicrm_contact'
2340 AND contact_a.id = civicrm_task_status.responsible_entity_id )";
2343 case 'civicrm_grant':
2344 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2347 //build fromClause for email greeting, postal greeting, addressee CRM-4575
2349 case 'email_greeting':
2350 $from .= " $side JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
2351 $from .= " $side 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 ) ";
2354 case 'postal_greeting':
2355 $from .= " $side JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
2356 $from .= " $side 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 ) ";
2360 $from .= " $side JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
2361 $from .= " $side JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
2364 case 'civicrm_website':
2365 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2369 $from .= CRM_Core_Component
::from($name, $mode, $side);
2378 * WHERE / QILL clause for deleted_contacts
2382 function deletedContacts($values) {
2383 list($_, $_, $value, $grouping, $_) = $values;
2385 // *prepend* to the relevant grouping as this is quite an important factor
2386 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2391 * where / qill clause for contact_type
2396 function contactType(&$values) {
2397 list($name, $op, $value, $grouping, $wildcard) = $values;
2399 $subTypes = array();
2402 // account for search builder mapping multiple values
2403 if (!is_array($value)) {
2404 $values = self
::parseSearchBuilderString($value, 'String');
2405 if (is_array($values)) {
2406 $value = array_flip($values);
2410 if (is_array($value)) {
2411 foreach ($value as $k => $v) {
2416 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2417 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2420 if (!empty($subType)) {
2421 $subTypes[$subType] = 1;
2423 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2428 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2429 $contactType = $contactTypeANDSubType[0];
2430 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2431 if (!empty($subType)) {
2432 $subTypes[$subType] = 1;
2434 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2438 if (!empty($clause)) {
2439 $this->_where
[$grouping][] = 'contact_a.contact_type IN (' . implode(',', $clause) . ')';
2440 $this->_qill
[$grouping][] = ts('Contact Type') . ' - ' . implode(' ' . ts('or') . ' ', $clause);
2442 if (!empty($subTypes)) {
2443 $this->includeContactSubTypes($subTypes, $grouping);
2449 * where / qill clause for contact_sub_type
2454 function contactSubType(&$values) {
2455 list($name, $op, $value, $grouping, $wildcard) = $values;
2456 $this->includeContactSubTypes($value, $grouping);
2459 function includeContactSubTypes($value, $grouping) {
2462 $alias = "contact_a.contact_sub_type";
2464 if (is_array($value)) {
2465 foreach ($value as $k => $v) {
2467 $clause[$k] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($k, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2472 $clause[$value] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2475 if (!empty($clause)) {
2476 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2477 $this->_qill
[$grouping][] = ts('Contact Subtype') . ' - ' . implode(' ' . ts('or') . ' ', array_keys($clause));
2482 * where / qill clause for groups
2487 function group(&$values) {
2488 list($name, $op, $value, $grouping, $wildcard) = $values;
2490 if (count($value) > 1) {
2491 $this->_useDistinct
= TRUE;
2494 $groupNames = CRM_Core_PseudoConstant
::group();
2495 $groupIds = implode(',', array_keys($value));
2498 foreach ($value as $id => $dontCare) {
2499 if (array_key_exists($id, $groupNames) && $dontCare) {
2500 $names[] = $groupNames[$id];
2506 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2508 is_array($gcsValues[2])
2510 foreach ($gcsValues[2] as $k => $v) {
2512 if ($k == 'Added') {
2515 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2520 $statii[] = '"Added"';
2525 if (count($value) == 1 &&
2526 count($statii) == 1 &&
2527 $statii[0] == '"Added"'
2529 // check if smart group, if so we can get rid of that one additional
2531 $groupIDs = array_keys($value);
2533 if (CRM_Utils_Array
::value(0, $groupIDs) &&
2534 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
2544 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2545 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON contact_a.id = {$gcTable}.contact_id ";
2548 $qill = ts('Contacts %1', array(1 => $op));
2549 $qill .= ' ' . implode(' ' . ts('or') . ' ', $names);
2551 $groupClause = NULL;
2554 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2555 if (!empty($statii)) {
2556 $groupClause .= " AND {$gcTable}.status IN (" . implode(', ', $statii) . ")";
2557 $qill .= " " . ts('AND') . " " . ts('Group Status') . ' - ' . implode(' ' . ts('or') . ' ', $statii);
2562 $ssClause = $this->savedSearch($values);
2565 $groupClause = "( ( $groupClause ) OR ( $ssClause ) )";
2568 $groupClause = $ssClause;
2573 $this->_where
[$grouping][] = $groupClause;
2574 $this->_qill
[$grouping][] = $qill;
2577 * Function translates selection of group type into a list of groups
2579 function getGroupsFromTypeCriteria($value){
2580 $groupIds = array();
2581 foreach ($value as $groupTypeValue) {
2582 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2583 $groupIds = ($groupIds +
$groupList);
2589 * where / qill clause for smart groups
2594 function savedSearch(&$values) {
2595 list($name, $op, $value, $grouping, $wildcard) = $values;
2596 return $this->addGroupContactCache(array_keys($value));
2599 function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
2600 $config = CRM_Core_Config
::singleton();
2602 // find all the groups that are part of a saved search
2603 $groupIDs = implode(',', $groups);
2604 if (empty($groupIDs)) {
2609 SELECT id, cache_date, saved_search_id, children
2611 WHERE id IN ( $groupIDs )
2612 AND ( saved_search_id != 0
2613 OR saved_search_id IS NOT NULL
2614 OR children IS NOT NULL )
2616 $group = CRM_Core_DAO
::executeQuery($sql);
2618 while ($group->fetch()) {
2619 if ($tableAlias == NULL) {
2620 $alias = "`civicrm_group_contact_cache_{$group->id}`";
2623 $alias = $tableAlias;
2626 $this->_useDistinct
= TRUE;
2628 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
2629 CRM_Contact_BAO_GroupContactCache
::load($group);
2632 $this->_tables
[$alias] = $this->_whereTables
[$alias] = " LEFT JOIN civicrm_group_contact_cache {$alias} ON {$joinTable}.id = {$alias}.contact_id ";
2633 $ssWhere[] = "{$alias}.group_id = {$group->id}";
2636 if (!empty($ssWhere)) {
2637 return implode(' OR ', $ssWhere);
2643 * where / qill clause for cms users
2648 function ufUser(&$values) {
2649 list($name, $op, $value, $grouping, $wildcard) = $values;
2652 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2654 $this->_qill
[$grouping][] = ts('CMS User');
2656 elseif ($value == 0) {
2657 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2659 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2660 $this->_qill
[$grouping][] = ts('Not a CMS User');
2665 * all tag search specific
2670 function tagSearch(&$values) {
2671 list($name, $op, $value, $grouping, $wildcard) = $values;
2674 $value = "%{$value}%";
2677 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2678 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2680 $etTable = "`civicrm_entity_tag-" . $value . "`";
2681 $tTable = "`civicrm_tag-" . $value . "`";
2683 if ($useAllTagTypes[2]) {
2684 $this->_tables
[$etTable] =
2685 $this->_whereTables
[$etTable] =
2686 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
2687 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
2689 // search tag in cases
2690 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2691 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
2692 $this->_tables
[$etCaseTable] =
2693 $this->_whereTables
[$etCaseTable] =
2694 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2695 LEFT JOIN civicrm_case
2696 ON (civicrm_case_contact.case_id = civicrm_case.id
2697 AND civicrm_case.is_deleted = 0 )
2698 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
2699 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
2700 // search tag in activities
2701 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2702 $tActTable = "`civicrm_act_tag-" . $value . "`";
2703 $this->_tables
[$etActTable] =
2704 $this->_whereTables
[$etActTable] =
2705 " LEFT JOIN civicrm_activity_target
2706 ON ( civicrm_activity_target.target_contact_id = contact_a.id )
2707 LEFT JOIN civicrm_activity
2708 ON ( civicrm_activity.id = civicrm_activity_target.activity_id
2709 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2710 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
2711 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
2713 $this->_where
[$grouping][] = "({$tTable}.name $op '". $value . "' OR {$tCaseTable}.name $op '". $value . "' OR {$tActTable}.name $op '". $value . "')";
2714 $this->_qill
[$grouping][] = ts('Tag %1 %2 ', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
2716 $etTable = "`civicrm_entity_tag-" . $value . "`";
2717 $tTable = "`civicrm_tag-" . $value . "`";
2718 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
2719 {$etTable}.entity_table = 'civicrm_contact' )
2720 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
2722 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
2723 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
2728 * where / qill clause for tag
2733 function tag(&$values) {
2734 list($name, $op, $value, $grouping, $wildcard) = $values;
2736 $tagNames = CRM_Core_PseudoConstant
::tag();
2737 if (is_array($value)) {
2738 if (count($value) > 1) {
2739 $this->_useDistinct
= TRUE;
2741 foreach ($value as $id => $dontCare) {
2742 $names[] = CRM_Utils_Array
::value($id, $tagNames);
2744 $names = implode(' ' . ts('or') . ' ', $names);
2745 $value = implode(',', array_keys($value));
2748 $names = CRM_Utils_Array
::value($value, $tagNames);
2752 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2753 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2755 $etTable = "`civicrm_entity_tag-" . $value . "`";
2757 if ($useAllTagTypes[2]) {
2758 $this->_tables
[$etTable] =
2759 $this->_whereTables
[$etTable] =
2760 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2762 // search tag in cases
2763 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2764 $this->_tables
[$etCaseTable] =
2765 $this->_whereTables
[$etCaseTable] =
2766 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2767 LEFT JOIN civicrm_case
2768 ON (civicrm_case_contact.case_id = civicrm_case.id
2769 AND civicrm_case.is_deleted = 0 )
2770 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
2771 // search tag in activities
2772 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2773 $this->_tables
[$etActTable] =
2774 $this->_whereTables
[$etActTable] =
2775 " LEFT JOIN civicrm_activity_target
2776 ON ( civicrm_activity_target.target_contact_id = contact_a.id )
2777 LEFT JOIN civicrm_activity
2778 ON ( civicrm_activity.id = civicrm_activity_target.activity_id
2779 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2780 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
2783 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
2784 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
2787 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (". $value . ") OR {$etCaseTable}.tag_id $op (". $value . ") OR {$etActTable}.tag_id $op (". $value . "))";
2789 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
2791 $this->_tables
[$etTable] =
2792 $this->_whereTables
[$etTable] =
2793 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2796 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
2797 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
2798 $op = str_replace('EMPTY', 'NULL', $op);
2799 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
2802 $this->_where
[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
2804 $this->_qill
[$grouping][] = ts('Tagged %1', array( 1 => $op)) . ' ' . $names;
2810 * where/qill clause for notes
2815 function notes(&$values) {
2816 list($name, $op, $value, $grouping, $wildcard) = $values;
2818 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
2819 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
2820 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
2822 $this->_useDistinct
= TRUE;
2824 $this->_tables
['civicrm_note'] =
2825 $this->_whereTables
['civicrm_note'] =
2826 " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
2828 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2830 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
2831 if ($wildcard ||
$op == 'LIKE') {
2832 if (strpos($value, '%') === FALSE) {
2833 $value = "%$value%";
2837 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
2843 if ( $noteOption %
2 == 0 ) {
2844 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
2845 $label = ts('Note: Body Only');
2847 if ( $noteOption %
3 == 0 ) {
2848 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
2849 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
2851 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
2852 $this->_qill
[$grouping][] = $label . " $op - '$n'";
2855 function nameNullOrEmptyOp($name, $op, $grouping) {
2859 $this->_where
[$grouping][] = "contact_a.$name $op";
2860 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
2864 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
2865 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
2868 case 'IS NOT EMPTY':
2869 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
2870 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
2879 * where / qill clause for sort_name
2884 function sortName(&$values) {
2885 list($name, $op, $value, $grouping, $wildcard) = $values;
2887 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
2888 if ( $this->nameNullOrEmptyOp( $name, $op, $grouping ) ) {
2893 $name = trim($value);
2899 $config = CRM_Core_Config
::singleton();
2903 //By default, $sub elements should be joined together with OR statements (don't change this variable).
2906 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2908 if (substr($name, 0, 1) == '"' &&
2909 substr($name, -1, 1) == '"'
2911 //If name is encased in double quotes, the value should be taken to be the string in entirety and the
2912 $value = substr($name, 1, -1);
2913 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2914 $wc = ($newName == 'sort_name') ?
'LOWER(contact_a.sort_name)' : 'LOWER(contact_a.display_name)';
2915 $sub[] = " ( $wc = '$value' ) ";
2916 if ($config->includeEmailInName
) {
2917 $sub[] = " ( civicrm_email.email = '$value' ) ";
2920 elseif (strpos($name, ',') !== FALSE) {
2921 // if we have a comma in the string, search for the entire string
2922 $value = $strtolower(CRM_Core_DAO
::escapeString($name));
2924 if ($config->includeWildCardInName
) {
2925 $value = "'%$value%'";
2928 $value = "'$value%'";
2933 $value = "'$value'";
2935 if ($newName == 'sort_name') {
2936 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
2939 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
2941 $sub[] = " ( $wc $op $value )";
2942 if ($config->includeNickNameInName
) {
2943 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
2944 $sub[] = " ( $wc $op $value )";
2946 if ($config->includeEmailInName
) {
2947 $sub[] = " ( civicrm_email.email $op $value ) ";
2951 // the string should be treated as a series of keywords to be matched with match ANY OR
2952 // match ALL depending on Civi config settings (see CiviAdmin)
2954 // The Civi configuration setting can be overridden if the string *starts* with the case
2955 // insenstive strings 'AND:' or 'OR:'TO THINK ABOUT: what happens when someone searches
2956 // for the following "AND: 'a string in quotes'"? - probably nothing - it would make the
2957 // AND OR variable reduntant because there is only one search string?
2959 // Check to see if the $subGlue is overridden in the search text
2960 if (strtolower(substr($name, 0, 4)) == 'and:') {
2961 $name = substr($name, 4);
2964 if (strtolower(substr($name, 0, 3)) == 'or:') {
2965 $name = substr($name, 3);
2969 $firstChar = substr($name, 0, 1);
2970 $lastChar = substr($name, -1, 1);
2971 $quotes = array("'", '"');
2972 if ((strlen($name) > 2) && in_array($firstChar, $quotes) &&
2973 in_array($lastChar, $quotes)
2975 $name = substr($name, 1);
2976 $name = substr($name, 0, -1);
2977 $pieces = array($name);
2980 $pieces = explode(' ', $name);
2982 foreach ($pieces as $piece) {
2983 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($piece)));
2984 if (strlen($value)) {
2985 // Added If as a sanitization - without it, when you do an OR search, any string with
2986 // double spaces (i.e. " ") or that has a space after the keyword (e.g. "OR: ") will
2987 // return all contacts because it will include a condition similar to "OR contact
2988 // name LIKE '%'". It might be better to replace this with array_filter.
2989 $fieldsub = array();
2991 if ($config->includeWildCardInName
) {
2992 $value = "'%$value%'";
2995 $value = "'$value%'";
3000 $value = "'$value'";
3002 if ($newName == 'sort_name') {
3003 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3006 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3008 $fieldsub[] = " ( $wc $op $value )";
3009 if ($config->includeNickNameInName
) {
3010 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3011 $fieldsub[] = " ( $wc $op $value )";
3013 if ($config->includeEmailInName
) {
3014 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3016 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3017 // I seperated the glueing in two. The first stage should always be OR because we are searching for matches in *ANY* of these fields
3022 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3024 $this->_where
[$grouping][] = $sub;
3025 if ($config->includeEmailInName
) {
3026 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3027 $this->_qill
[$grouping][] = ts('Name or Email ') . "$op - '$name'";
3030 $this->_qill
[$grouping][] = ts('Name like') . " - '$name'";
3035 * where / qill clause for email
3040 function email(&$values) {
3041 list($name, $op, $value, $grouping, $wildcard) = $values;
3045 $config = CRM_Core_Config
::singleton();
3047 if (substr($n, 0, 1) == '"' &&
3048 substr($n, -1, 1) == '"'
3050 $n = substr($n, 1, -1);
3051 $value = strtolower(CRM_Core_DAO
::escapeString($n));
3052 $value = "'$value'";
3056 $value = strtolower($n);
3058 if (strpos($value, '%') === FALSE) {
3059 $value = "%{$value}%";
3064 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3065 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3068 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3069 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3072 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3076 * where / qill clause for phone number
3081 function phone_numeric(&$values) {
3082 list($name, $op, $value, $grouping, $wildcard) = $values;
3083 // Strip non-numeric characters
3084 $number = preg_replace('/[^\d]/', '', $value);
3086 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3087 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "%$number%", 'String');
3088 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3093 * where / qill clause for phone type/location
3098 function phone_option_group($values) {
3099 list($name, $op, $value, $grouping, $wildcard) = $values;
3100 $option = $name == 'phone_phone_type_id' ?
'phoneType' : 'locationType';
3101 $options = CRM_Core_PseudoConstant
::$option();
3102 $optionName = $options[$value];
3103 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3104 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3105 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3109 * where / qill clause for street_address
3114 function street_address(&$values) {
3115 list($name, $op, $value, $grouping, $wildcard) = $values;
3124 $value = strtolower($n);
3125 if (strpos($value, '%') === FALSE) {
3126 // only add wild card if not there
3127 $value = "%{$value}%";
3130 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3131 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3134 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3135 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3138 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3142 * where / qill clause for street_unit
3147 function street_number(&$values) {
3148 list($name, $op, $value, $grouping, $wildcard) = $values;
3156 if (strtolower($n) == 'odd') {
3157 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3158 $this->_qill
[$grouping][] = ts('Street Number is odd');
3160 elseif (strtolower($n) == 'even') {
3161 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3162 $this->_qill
[$grouping][] = ts('Street Number is even');
3165 $value = strtolower($n);
3167 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3168 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3171 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3175 * where / qill clause for sorting by character
3180 function sortByCharacter(&$values) {
3181 list($name, $op, $value, $grouping, $wildcard) = $values;
3183 $name = trim($value);
3184 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3185 $this->_where
[$grouping][] = $cond;
3186 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3190 * where / qill clause for including contact ids
3195 function includeContactIDs() {
3196 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3200 $contactIds = array();
3201 foreach ($this->_params
as $id => $values) {
3202 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3203 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3206 if (!empty($contactIds)) {
3207 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3212 * where / qill clause for postal code
3217 function postalCode(&$values) {
3218 // skip if the fields dont have anything to do with postal_code
3219 if (!CRM_Utils_Array
::value('postal_code', $this->_fields
)) {
3223 list($name, $op, $value, $grouping, $wildcard) = $values;
3225 // Handle numeric postal code range searches properly by casting the column as numeric
3226 if (is_numeric($value)) {
3227 $field = 'ROUND(civicrm_address.postal_code)';
3228 $val = CRM_Utils_Type
::escape($value, 'Integer');
3231 $field = 'civicrm_address.postal_code';
3232 $val = CRM_Utils_Type
::escape($value, 'String');
3235 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3237 if ($name == 'postal_code') {
3238 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3239 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3241 elseif ($name == 'postal_code_low') {
3242 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3243 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3245 elseif ($name == 'postal_code_high') {
3246 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3247 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3252 * where / qill clause for location type
3257 function locationType(&$values, $status = NULL) {
3258 list($name, $op, $value, $grouping, $wildcard) = $values;
3260 if (is_array($value)) {
3261 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', array_keys($value)) . ')';
3262 $this->_tables
['civicrm_address'] = 1;
3263 $this->_whereTables
['civicrm_address'] = 1;
3265 $locationType = CRM_Core_PseudoConstant
::locationType();
3267 foreach (array_keys($value) as $id) {
3268 $names[] = $locationType[$id];
3271 $this->_primaryLocation
= FALSE;
3274 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3277 return implode(' ' . ts('or') . ' ', $names);
3282 function country(&$values, $fromStateProvince = TRUE) {
3283 list($name, $op, $value, $grouping, $wildcard) = $values;
3285 if (!$fromStateProvince) {
3286 $stateValues = $this->getWhereValues('state_province', $grouping);
3287 if (!empty($stateValues)) {
3288 // return back to caller if there are state province values
3289 // since that handles this case
3294 $countryClause = $countryQill = NULL;
3299 $this->_tables
['civicrm_country'] = 1;
3300 $this->_whereTables
['civicrm_country'] = 1;
3302 $countries = CRM_Core_PseudoConstant
::country();
3303 if (is_numeric($value)) {
3304 $countryClause = self
::buildClause(
3305 'civicrm_country.id',
3310 $countryName = $countries[(int ) $value];
3314 $intValues = self
::parseSearchBuilderString($value);
3315 if ($intValues && ($op == 'IN' ||
$op == 'NOT IN')) {
3316 $countryClause = self
::buildClause(
3317 'civicrm_country.id',
3322 $countryNames = array();
3323 foreach ($intValues as $v) {
3324 $countryNames[] = $countries[$v];
3326 $countryName = implode(',', $countryNames);
3329 $wc = ($op != 'LIKE') ?
"LOWER('civicrm_country.name')" : 'civicrm_country.name';
3330 $countryClause = self
::buildClause(
3331 'civicrm_country.name',
3336 $countryName = $value;
3339 $countryQill = ts('Country') . " {$op} '$countryName'";
3341 if (!$fromStateProvince) {
3342 $this->_where
[$grouping][] = $countryClause;
3343 $this->_qill
[$grouping][] = $countryQill;
3347 if ($fromStateProvince) {
3348 if (!empty($countryClause)) {
3351 " ...AND... " . $countryQill,
3355 return array(NULL, NULL);
3361 * where / qill clause for county (if present)
3366 function county(&$values, $status = null) {
3367 list($name, $op, $value, $grouping, $wildcard) = $values;
3369 if (! is_array($value)) {
3370 // force the county to be an array
3371 $value = array($value);
3374 // check if the values are ids OR names of the counties
3375 $inputFormat = 'id';
3376 foreach ($value as $v) {
3377 if (!is_numeric($v)) {
3378 $inputFormat = 'name';
3383 if ($inputFormat == 'id') {
3384 $clause = 'civicrm_county.id IN (' . implode(',', $value) . ')';
3386 $county = CRM_Core_PseudoConstant
::county();
3387 foreach ($value as $id) {
3388 $names[] = CRM_Utils_Array
::value($id, $county);
3392 $inputClause = array();
3393 foreach ($value as $name) {
3394 $name = trim($name);
3395 $inputClause[] = "'$name'";
3397 $clause = 'civicrm_county.name IN (' . implode(',', $inputClause) . ')';
3400 $this->_tables
['civicrm_county'] = 1;
3401 $this->_whereTables
['civicrm_county'] = 1;
3403 $this->_where
[$grouping][] = $clause;
3405 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3407 return implode(' ' . ts('or') . ' ', $names);
3412 * where / qill clause for state/province AND country (if present)
3417 function stateProvince(&$values, $status = NULL) {
3418 list($name, $op, $value, $grouping, $wildcard) = $values;
3420 // quick escape for IS NULL
3421 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3424 else if (!is_array($value)) {
3425 // force the state to be an array
3426 // check if its in the mapper format!
3427 $values = self
::parseSearchBuilderString($value);
3428 if (is_array($values)) {
3432 $value = array($value);
3436 // check if the values are ids OR names of the states
3437 $inputFormat = 'id';
3439 foreach ($value as $v) {
3440 if (!is_numeric($v)) {
3441 $inputFormat = 'name';
3451 else if ($op == '!=') {
3455 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3456 $op = str_replace('EMPTY', 'NULL', $op);
3458 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3459 $stateClause = "civicrm_state_province.id $op";
3461 else if ($inputFormat == 'id') {
3462 if ($op != 'NOT IN') {
3465 $stateClause = "civicrm_state_province.id $op (" . implode(',', $value) . ')';
3467 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3468 foreach ($value as $id) {
3469 $names[] = CRM_Utils_Array
::value($id, $stateProvince);
3473 $inputClause = array();
3474 foreach ($value as $name) {
3475 $name = trim($name);
3476 $inputClause[] = "'$name'";
3478 $stateClause = "civicrm_state_province.name $op (" . implode(',', $inputClause) . ')';
3482 $this->_tables
['civicrm_state_province'] = 1;
3483 $this->_whereTables
['civicrm_state_province'] = 1;
3485 $countryValues = $this->getWhereValues('country', $grouping);
3486 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3488 if ($countryClause) {
3489 $clause = "( $stateClause AND $countryClause )";
3492 $clause = $stateClause;
3495 $this->_where
[$grouping][] = $clause;
3497 $this->_qill
[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3500 return implode(' ' . ts('or') . ' ', $names) . $countryQill;;
3505 * where / qill clause for change log
3510 function changeLog(&$values) {
3511 list($name, $op, $value, $grouping, $wildcard) = $values;
3513 $targetName = $this->getWhereValues('changed_by', $grouping);
3518 $name = trim($targetName[2]);
3519 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3520 $name = $targetName[4] ?
"%$name%" : $name;
3521 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3522 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3523 $this->_qill
[$grouping][] = ts('Changed by') . ": $name";
3526 function modifiedDates($values) {
3527 $this->_useDistinct
= TRUE;
3529 // CRM-11281, default to added date if not set
3530 $fieldTitle = ts('Added Date');
3532 foreach (array_keys($this->_params
) as $id) {
3533 if ($this->_params
[$id][0] == 'log_date') {
3534 if ($this->_params
[$id][2] == 2) {
3535 $fieldTitle = ts('Modified Date');
3540 $this->dateQueryBuilder($values,
3541 'civicrm_log', 'log_date', 'modified_date', $fieldTitle
3545 function demographics(&$values) {
3546 list($name, $op, $value, $grouping, $wildcard) = $values;
3548 if (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3550 $this->dateQueryBuilder($values,
3551 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3554 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3556 $this->dateQueryBuilder($values,
3557 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3561 self
::$_openedPanes[ts('Demographics')] = TRUE;
3564 function privacy(&$values) {
3565 list($name, $op, $value, $grouping, $wildcard) = $values;
3566 //fixed for profile search listing CRM-4633
3567 if (strpbrk($value, "[")) {
3568 $value = "'{$value}'";
3570 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3573 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3575 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3576 $title = $field ?
$field['title'] : $name;
3577 $this->_qill
[$grouping][] = "$title $op $value";
3580 function privacyOptions($values) {
3581 list($name, $op, $value, $grouping, $wildcard) = $values;
3583 if (empty($value) ||
3589 // get the operator and toggle values
3590 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3593 strtolower($opValues[2] == 'AND')
3598 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3600 if ($toggleValues &&
3601 $toggleValues[2] == 2
3608 foreach ($value as $dontCare => $pOption) {
3609 $clauses[] = " ( contact_a.{$pOption} $compareOP 1 ) ";
3610 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3611 $title = $field ?
$field['title'] : $pOption;
3612 $qill[] = " $title $compareOP 1 ";
3615 $this->_where
[$grouping][] = '( ' . implode($operator, $clauses) . ' )';
3616 $this->_qill
[$grouping][] = implode($operator, $qill);
3619 function preferredCommunication(&$values) {
3620 list($name, $op, $value, $grouping, $wildcard) = $values;
3623 if (!is_array($value)) {
3625 $value = trim($value, ' ()');
3626 if (strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
3627 $v = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
3630 $v = explode(",", $value);
3633 foreach ($v as $item) {
3640 foreach ($value as $key => $checked) {
3647 $commPref = CRM_Core_PseudoConstant
::pcm();
3649 $sqlValue = array();
3650 $sql = "contact_a.preferred_communication_method";
3651 foreach ($pref as $val) {
3652 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $val . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' ) ";
3653 $showValue[] = $commPref[$val];
3655 $this->_where
[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
3656 $this->_qill
[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
3660 * where / qill clause for task / task status
3665 function task(&$values) {
3666 list($name, $op, $value, $grouping, $wildcard) = $values;
3668 $targetName = $this->getWhereValues('task_id', $grouping);
3673 $taskID = CRM_Utils_Type
::escape($targetName[2], 'Integer');
3674 $clause = "civicrm_task_status.task_id = $taskID ";
3678 $statusID = CRM_Utils_Type
::escape($value, 'Integer');
3679 $clause .= " AND civicrm_task_status.status_id = $statusID";
3682 $this->_where
[$grouping][] = "civicrm_task_status.task_id = $taskID AND civicrm_task_status.status_id = $statusID";
3683 $this->_tables
['civicrm_task_status'] = $this->_whereTables
['civicrm_task_status'] = 1;
3685 $taskSelect = CRM_Core_PseudoConstant
::tasks();
3686 $this->_qill
[$grouping][] = ts('Task') . ": $taskSelect[$taskID]";
3688 $statusSelect = CRM_Core_OptionGroup
::values('task_status');
3689 $this->_qill
[$grouping][] = ts('Task Status') . ": $statusSelect[$statusID]";
3694 * where / qill clause for relationship
3699 function relationship(&$values) {
3700 list($name, $op, $value, $grouping, $wildcard) = $values;
3702 // also get values array for relation_target_name
3703 // for relatinship search we always do wildcard
3704 $targetName = $this->getWhereValues('relation_target_name', $grouping);
3705 $relStatus = $this->getWhereValues('relation_status', $grouping);
3706 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
3707 $start = $this->getWhereValues('relation_date_low', $grouping);
3708 $end = $this->getWhereValues('relation_date_high', $grouping);
3710 $nameClause = $name = NULL;
3712 $name = trim($targetName[2]);
3713 if (substr($name, 0, 1) == '"' &&
3714 substr($name, -1, 1) == '"'
3716 $name = substr($name, 1, -1);
3717 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3718 $nameClause = "= '$name'";
3721 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3722 $nameClause = "LIKE '%{$name}%'";
3726 $rel = explode('_', $value);
3728 self
::$_relType = $rel[1];
3730 $params = array('id' => $rel[0]);
3731 $rTypeValues = array();
3732 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
3737 if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
3738 self
::$_relType = 'reciprocal';
3742 $this->_where
[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
3745 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
3746 $relTypeOrg = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
3747 $relTypeHou = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Household');
3748 $allRelationshipType = array();
3749 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
3750 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
3752 if ($nameClause ||
!$targetGroup) {
3753 $this->_qill
[$grouping][] = "$allRelationshipType[$value] $name";
3757 //check to see if the target contact is in specified group
3759 //add contacts from static groups
3760 $this->_tables
['civicrm_relationship_group_contact'] =
3761 $this->_whereTables
['civicrm_relationship_group_contact'] =
3762 " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = contact_b.id";
3763 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" . implode(",", $targetGroup[2]) . ") )";
3765 //add contacts from saved searches
3766 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
3768 //set the group where clause
3770 $groupWhere[] = "( " . $ssWhere . " )";
3772 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
3774 //Get the names of the target groups for the qill
3775 $groupNames = &CRM_Core_PseudoConstant
::group();
3776 $qillNames = array();
3777 foreach ($targetGroup[2] as $groupId) {
3778 if (array_key_exists($groupId, $groupNames)) {
3779 $qillNames[] = $groupNames[$groupId];
3782 $this->_qill
[$grouping][] = "$allRelationshipType[$value] ( " . implode(", ", $qillNames) . " )";
3786 //check for active, inactive and all relation status
3787 if ($relStatus[2] == 0) {
3788 $this->_where
[$grouping][] = "(
3789 civicrm_relationship.is_active = 1 AND
3790 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= CURDATE() ) AND
3791 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= CURDATE() )
3793 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
3795 elseif ($relStatus[2] == 1) {
3796 $this->_where
[$grouping][] = "(
3797 civicrm_relationship.is_active = 0 OR
3798 civicrm_relationship.end_date < CURDATE() OR
3799 civicrm_relationship.start_date > CURDATE()
3801 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
3805 if ($start ||
$end) {
3806 foreach (array('start' => '>=', 'end' => '<=') as $d => $op) {
3807 if (!empty($
{$d}[2])) {
3808 $date = date('Ymd', strtotime($
{$d}[2]));
3809 $this->_where
[$grouping][] = "civicrm_relationship.{$d}_date $op $date";
3810 $this->_qill
[$grouping][] = ($d == 'end' ?
ts('Relationship Ended by') : ts('Relationship Started On or After')) . " " . CRM_Utils_Date
::customFormat($date);
3815 $this->_where
[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rel[0];
3816 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
3817 $this->_useDistinct
= TRUE;
3821 * default set of return properties
3826 static function &defaultReturnProperties($mode = 1) {
3827 if (!isset(self
::$_defaultReturnProperties)) {
3828 self
::$_defaultReturnProperties = array();
3831 if (!isset(self
::$_defaultReturnProperties[$mode])) {
3832 // add activity return properties
3833 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
3834 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
3837 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
3840 if (empty(self
::$_defaultReturnProperties[$mode])) {
3841 self
::$_defaultReturnProperties[$mode] = array(
3844 'legal_identifier' => 1,
3845 'external_identifier' => 1,
3846 'contact_type' => 1,
3847 'contact_sub_type' => 1,
3849 'display_name' => 1,
3850 'preferred_mail_format' => 1,
3855 'individual_prefix' => 1,
3856 'individual_suffix' => 1,
3859 'street_address' => 1,
3860 'supplemental_address_1' => 1,
3861 'supplemental_address_2' => 1,
3864 'postal_code_suffix' => 1,
3865 'state_province' => 1,
3867 'world_region' => 1,
3874 'household_name' => 1,
3875 'organization_name' => 1,
3876 'deceased_date' => 1,
3881 'current_employer' => 1,
3882 // FIXME: should we use defaultHierReturnProperties() for the below?
3883 'do_not_email' => 1,
3886 'do_not_phone' => 1,
3887 'do_not_trade' => 1,
3889 'contact_is_deleted' => 1,
3893 return self
::$_defaultReturnProperties[$mode];
3897 * get primary condition for a sql clause
3904 static function getPrimaryCondition($value) {
3905 if (is_numeric($value)) {
3906 $value = (int ) $value;
3907 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
3913 * wrapper for a simple search query
3915 * @param array $params
3916 * @param array $returnProperties
3917 * @param bolean $count
3922 static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
3923 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
3924 list($select, $from, $where, $having) = $query->query();
3926 return "$select $from $where $having";
3930 * These are stub comments as this function needs more explanation - particularly in terms of how it
3931 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
3933 * This function was originally written as a wrapper for the api query but is called from multiple places
3934 * in the core code directly so the name is misleading. This function does not use the searchQuery function
3935 * but it is unclear as to whehter that is historical or there is a reason
3936 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
3938 * @param array $params
3939 * @param array $returnProperties
3940 * @param string $sort
3941 * @param int $offset
3942 * @param int $row_count
3943 * @params bool $smartGroupCache ?? update smart group cache?
3944 * @param bool $count return count obnly
3945 * @param bool $skipPermissions Should permissions be ignored or should the logged in user's permissions be applied
3950 static function apiQuery(
3952 $returnProperties = NULL,
3957 $smartGroupCache = TRUE,
3959 $skipPermissions = True
3962 $query = new CRM_Contact_BAO_Query(
3963 $params, $returnProperties,
3964 NULL, TRUE, FALSE, 1,
3966 TRUE, $smartGroupCache
3969 //this should add a check for view deleted if permissions are enabled
3970 if ($skipPermissions){
3971 $query->_skipDeleteClause
= TRUE;
3973 $query->generatePermissionClause(FALSE, $count);
3974 list($select, $from, $where, $having) = $query->query($count);
3976 $options = $query->_options
;
3977 if(!empty($query->_permissionWhereClause
)){
3978 if (empty($where)) {
3979 $where = "WHERE $query->_permissionWhereClause";
3982 $where = "$where AND $query->_permissionWhereClause";
3986 $sql = "$select $from $where $having";
3989 if ($query->_useGroupBy
) {
3990 $sql .= ' GROUP BY contact_a.id';
3992 if (!empty($sort)) {
3993 $sql .= " ORDER BY $sort ";
3995 if ($row_count > 0 && $offset >= 0) {
3996 $sql .= " LIMIT $offset, $row_count ";
3999 $dao = CRM_Core_DAO
::executeQuery($sql);
4002 while ($dao->fetch()) {
4004 $noRows = $dao->rowCount
;
4006 return array($noRows,NULL);
4008 $values[$dao->contact_id
] = $query->store($dao);
4011 return array($values, $options);
4015 * create and query the db for an contact search
4017 * @param int $offset the offset for the query
4018 * @param int $rowCount the number of rows to return
4019 * @param string $sort the order by string
4020 * @param boolean $count is this a count only query ?
4021 * @param boolean $includeContactIds should we include contact ids?
4022 * @param boolean $sortByChar if true returns the distinct array of first characters for search results
4023 * @param boolean $groupContacts if true, return only the contact ids
4024 * @param boolean $returnQuery should we return the query as a string
4025 * @param string $additionalWhereClause if the caller wants to further restrict the search (used for components)
4026 * @param string $additionalFromClause should be clause with proper joins, effective to reduce where clause load.
4028 * @return CRM_Contact_DAO_Contact
4031 function searchQuery(
4032 $offset = 0, $rowCount = 0, $sort = NULL,
4033 $count = FALSE, $includeContactIds = FALSE,
4034 $sortByChar = FALSE, $groupContacts = FALSE,
4035 $returnQuery = FALSE,
4036 $additionalWhereClause = NULL, $sortOrder = NULL,
4037 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4040 if ($includeContactIds) {
4041 $this->_includeContactIds
= TRUE;
4042 $this->_whereClause
= $this->whereClause();
4045 // hack for now, add permission only if we are in search
4046 // FIXME: we should actually filter out deleted contacts (unless requested to do the opposite)
4047 $permission = ' ( 1 ) ';
4048 $onlyDeleted = FALSE;
4049 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4051 // if we’re explicitely looking for a certain contact’s contribs, events, etc.
4052 // and that contact happens to be deleted, set $onlyDeleted to true
4053 foreach ($this->_params
as $values) {
4054 $name = CRM_Utils_Array
::value(0, $values);
4055 $op = CRM_Utils_Array
::value(1, $values);
4056 $value = CRM_Utils_Array
::value(2, $values);
4057 if ($name == 'contact_id' and $op == '=') {
4058 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4059 $onlyDeleted = TRUE;
4064 $this->generatePermissionClause($onlyDeleted, $count);
4066 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts);
4068 //additional from clause should be w/ proper joins.
4069 if ($additionalFromClause) {
4070 $from .= "\n" . $additionalFromClause;
4073 if (empty($where)) {
4074 $where = "WHERE $this->_permissionWhereClause";
4077 $where = "$where AND $this->_permissionWhereClause";
4080 if ($additionalWhereClause) {
4081 $where = $where . ' AND ' . $additionalWhereClause;
4084 // building the query string
4087 if (isset($this->_groupByComponentClause
)) {
4088 $groupBy = $this->_groupByComponentClause
;
4090 elseif ($this->_useGroupBy
) {
4091 $groupBy = ' GROUP BY contact_a.id';
4094 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4095 $groupBy = 'GROUP BY civicrm_activity.id ';
4098 $order = $orderBy = $limit = '';
4100 $config = CRM_Core_Config
::singleton();
4101 if ($config->includeOrderByClause ||
4102 isset($this->_distinctComponentClause
)
4105 if (is_string($sort)) {
4109 $orderBy = trim($sort->orderBy());
4111 if (!empty($orderBy)) {
4112 // this is special case while searching for
4113 // changelog CRM-1718
4114 if (preg_match('/sort_name/i', $orderBy)) {
4115 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4118 $order = " ORDER BY $orderBy";
4121 $order .= " $sortOrder";
4124 // always add contact_a.id to the ORDER clause
4125 // so the order is deterministic
4126 if (strpos('contact_a.id', $order) === FALSE) {
4127 $order .= ", contact_a.id";
4131 elseif ($sortByChar) {
4132 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4135 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4140 // hack for order clause
4142 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4143 $fieldOrder = explode(' ', $fieldStr);
4144 $field = $fieldOrder[0];
4150 case 'contact_a.sort_name':
4151 case 'contact_a.id':
4156 $this->_whereTables
["civicrm_address"] = 1;
4157 $order = str_replace($field, "civicrm_address.{$field}", $order);
4161 case 'state_province':
4162 $this->_whereTables
["civicrm_{$field}"] = 1;
4163 $order = str_replace($field, "civicrm_{$field}.name", $order);
4167 $this->_whereTables
["civicrm_email"] = 1;
4168 $order = str_replace($field, "civicrm_email.{$field}", $order);
4178 if ($rowCount > 0 && $offset >= 0) {
4179 $limit = " LIMIT $offset, $rowCount ";
4181 // ok here is a first hack at an optimization, lets get all the contact ids
4182 // that are restricted and we'll then do the final clause with it
4184 if (isset($this->_distinctComponentClause
)) {
4185 if (strpos($this->_distinctComponentClause
, 'DISTINCT') == FALSE) {
4186 $limitSelect = "SELECT DISTINCT {$this->_distinctComponentClause}";
4189 $limitSelect = "SELECT {$this->_distinctComponentClause}";
4193 $limitSelect = 'SELECT DISTINCT contact_a.id as id';
4197 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL,
4198 $this->_primaryLocation
, $this->_mode
4201 if ($additionalFromClause) {
4202 $this->_simpleFromClause
.= "\n" . $additionalFromClause;
4204 // if we are doing a transform, do it here
4207 if ($this->_displayRelationshipType
) {
4208 $this->filterRelatedContacts($this->_simpleFromClause
, $where, $having);
4211 $limitQuery = "$limitSelect {$this->_simpleFromClause} $where $groupBy $order $limit";
4212 $limitDAO = CRM_Core_DAO
::executeQuery($limitQuery);
4213 $limitIDs = array();
4214 while ($limitDAO->fetch()) {
4215 if ($limitDAO->id
) {
4216 $limitIDs[] = $limitDAO->id
;
4219 if (empty($limitIDs)) {
4220 $limitClause = ' AND ( 0 ) ';
4223 if (isset($this->_distinctComponentClause
)) {
4224 $limitClause = " AND {$this->_distinctComponentClause} IN ( ";
4227 $limitClause = ' AND contact_a.id IN ( ';
4229 $limitClause .= implode(',', $limitIDs) . ' ) ';
4231 $where .= $limitClause;
4232 // reset limit clause since we already restrict what records we want
4238 // if we are doing a transform, do it here
4239 // use the $from, $where and $having to get the contact ID
4240 if ($this->_displayRelationshipType
) {
4241 $this->filterRelatedContacts($from, $where, $having);
4244 if ($skipOrderAndLimit) {
4245 $query = "$select $from $where $having $groupBy";
4248 $query = "$select $from $where $having $groupBy $order $limit";
4256 return CRM_Core_DAO
::singleValueQuery($query);
4259 //crm_core_error::debug('$query', $query); //exit;
4261 $dao = CRM_Core_DAO
::executeQuery($query);
4262 if ($groupContacts) {
4264 while ($dao->fetch()) {
4267 return implode(',', $ids);
4274 * Populate $this->_permissionWhereClause with permission related clause and update other
4275 * query related properties.
4277 * Function calls ACL permission class and hooks to filter the query appropriately
4279 * Note that these 2 params were in the code when extracted from another function
4280 * and a second round extraction would be to make them properties of the class
4282 * @param bool $onlyDeleted Only get deleted contacts
4283 * @param bool $count Return Count only
4287 function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4288 if (!$this->_skipPermission
) {
4289 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4290 CRM_Core_Permission
::VIEW
,
4292 $this->_whereTables
,
4295 $this->_skipDeleteClause
4298 // regenerate fromClause since permission might have added tables
4299 if ($this->_permissionWhereClause
) {
4300 //fix for row count in qill (in contribute/membership find)
4302 $this->_useDistinct
= TRUE;
4304 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4305 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4309 // add delete clause if needed even if we are skipping permission
4311 if (!$this->_skipDeleteClause
) {
4312 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4313 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4317 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4323 function setSkipPermission($val) {
4324 $this->_skipPermission
= $val;
4327 function &summaryContribution($context = NULL) {
4328 list($select, $from, $where, $having) = $this->query(TRUE);
4332 SELECT COUNT( civicrm_contribution.total_amount ) as total_count,
4333 SUM( civicrm_contribution.total_amount ) as total_amount,
4334 AVG( civicrm_contribution.total_amount ) as total_avg,
4335 civicrm_contribution.currency as currency";
4337 // make sure contribution is completed - CRM-4989
4338 $where .= " AND civicrm_contribution.contribution_status_id = 1 ";
4339 if ($context == 'search') {
4340 $where .= " AND contact_a.is_deleted = 0 ";
4344 $summary['total'] = array();
4345 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4347 $query = "$select $from $where GROUP BY currency";
4350 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4352 $summary['total']['count'] = 0;
4353 $summary['total']['amount'] = $summary['total']['avg'] = array();
4354 while ($dao->fetch()) {
4355 $summary['total']['count'] +
= $dao->total_count
;
4356 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4357 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4359 if (!empty($summary['total']['amount'])) {
4360 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4361 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4364 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4369 SELECT COUNT( civicrm_contribution.total_amount ) as cancel_count,
4370 SUM( civicrm_contribution.total_amount ) as cancel_amount,
4371 AVG( civicrm_contribution.total_amount ) as cancel_avg,
4372 civicrm_contribution.currency as currency";
4374 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4375 if ($context == 'search') {
4376 $where .= " AND contact_a.is_deleted = 0 ";
4379 $query = "$select $from $where GROUP BY currency";
4380 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4383 if ($dao->fetch()) {
4384 $summary['cancel']['count'] = $dao->cancel_count
;
4385 $summary['cancel']['amount'] = $dao->cancel_amount
;
4386 $summary['cancel']['avg'] = $dao->cancel_avg
;
4390 $summary['cancel']['count'] = 0;
4391 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4392 while ($dao->fetch()) {
4393 $summary['cancel']['count'] +
= $dao->cancel_count
;
4394 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4395 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4397 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4398 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
4405 * getter for the qill object
4411 return $this->_qill
;
4415 * default set of return default hier return properties
4420 static function &defaultHierReturnProperties() {
4421 if (!isset(self
::$_defaultHierReturnProperties)) {
4422 self
::$_defaultHierReturnProperties = array(
4425 'legal_identifier' => 1,
4426 'external_identifier' => 1,
4427 'contact_type' => 1,
4428 'contact_sub_type' => 1,
4430 'display_name' => 1,
4435 'individual_prefix' => 1,
4436 'individual_suffix' => 1,
4437 'email_greeting' => 1,
4438 'postal_greeting' => 1,
4442 'preferred_communication_method' => 1,
4443 'do_not_phone' => 1,
4444 'do_not_email' => 1,
4447 'do_not_trade' => 1,
4450 '1' => array('location_type' => 1,
4451 'street_address' => 1,
4453 'state_province' => 1,
4455 'postal_code_suffix' => 1,
4458 'phone-Mobile' => 1,
4471 'location_type' => 1,
4472 'street_address' => 1,
4474 'state_province' => 1,
4476 'postal_code_suffix' => 1,
4479 'phone-Mobile' => 1,
4493 return self
::$_defaultHierReturnProperties;
4496 function dateQueryBuilder(
4497 &$values, $tableName, $fieldName,
4498 $dbFieldName, $fieldTitle,
4499 $appendTimeStamp = TRUE
4501 list($name, $op, $value, $grouping, $wildcard) = $values;
4507 if ($name == "{$fieldName}_low" ||
4508 $name == "{$fieldName}_high"
4510 if (isset($this->_rangeCache
[$fieldName])) {
4513 $this->_rangeCache
[$fieldName] = 1;
4515 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4517 if ($name == $fieldName . '_low') {
4519 $firstPhrase = ts('greater than or equal to');
4520 $firstDate = CRM_Utils_Date
::processDate($value);
4522 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4523 if (!empty($secondValues) && $secondValues[2]) {
4525 $secondPhrase = ts('less than or equal to');
4526 $secondValue = $secondValues[2];
4528 if ($appendTimeStamp && strlen($secondValue) == 10) {
4529 $secondValue .= ' 23:59:59';
4531 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4534 elseif ($name == $fieldName . '_high') {
4536 $firstPhrase = ts('less than or equal to');
4538 if ($appendTimeStamp && strlen($value) == 10) {
4539 $value .= ' 23:59:59';
4541 $firstDate = CRM_Utils_Date
::processDate($value);
4543 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4544 if (!empty($secondValues) && $secondValues[2]) {
4546 $secondPhrase = ts('greater than or equal to');
4547 $secondValue = $secondValues[2];
4548 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4552 if (!$appendTimeStamp) {
4553 $firstDate = substr($firstDate, 0, 8);
4555 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
4558 if (!$appendTimeStamp) {
4559 $secondDate = substr($secondDate, 0, 8);
4561 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
4564 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4566 $this->_where
[$grouping][] = "
4567 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
4568 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
4570 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
4573 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
4574 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
4578 if ($name == $fieldName) {
4582 $date = CRM_Utils_Date
::processDate($value);
4584 if (!$appendTimeStamp) {
4585 $date = substr($date, 0, 8);
4588 $format = CRM_Utils_Date
::customFormat($date);
4591 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'";
4594 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op";
4596 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4597 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$format\"";
4601 $tableName == 'civicrm_log' &&
4602 $fieldTitle == ts('Added Date')
4604 //CRM-6903 --hack to check modified date of first record.
4605 //as added date means first modified date of object.
4606 $addedDateQuery = 'select id from civicrm_log group by entity_id order by id';
4607 $this->_where
[$grouping][] = "civicrm_log.id IN ( {$addedDateQuery} )";
4611 function numberRangeBuilder(&$values,
4612 $tableName, $fieldName,
4613 $dbFieldName, $fieldTitle,
4616 list($name, $op, $value, $grouping, $wildcard) = $values;
4618 if ($name == "{$fieldName}_low" ||
4619 $name == "{$fieldName}_high"
4621 if (isset($this->_rangeCache
[$fieldName])) {
4624 $this->_rangeCache
[$fieldName] = 1;
4626 $secondOP = $secondPhrase = $secondValue = NULL;
4628 if ($name == "{$fieldName}_low") {
4630 $firstPhrase = ts('greater than');
4632 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4633 if (!empty($secondValues)) {
4635 $secondPhrase = ts('less than');
4636 $secondValue = $secondValues[2];
4641 $firstPhrase = ts('less than');
4643 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4644 if (!empty($secondValues)) {
4646 $secondPhrase = ts('greater than');
4647 $secondValue = $secondValues[2];
4652 $this->_where
[$grouping][] = "
4653 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
4654 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
4656 $displayValue = $options ?
$options[$value] : $value;
4657 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
4659 $this->_qill
[$grouping][] =
4660 "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
4663 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
4664 $displayValue = $options ?
$options[$value] : $value;
4665 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
4667 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4672 if ($name == $fieldName) {
4676 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
4678 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4679 $displayValue = $options ?
$options[$value] : $value;
4680 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
4687 * Given the field name, operator, value & its data type
4688 * builds the where Clause for the query
4689 * used for handling 'IS NULL'/'IS NOT NULL' operators
4691 * @param string $field fieldname
4692 * @param string $op operator
4693 * @param string $value value
4694 * @param string $dataType data type of the field
4696 * @return where clause for the query
4699 static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
4701 $clause = "$field $op";
4709 $clause = " ( $field IS NULL OR $field = '' ) ";
4712 case 'IS NOT EMPTY':
4713 $clause = " ( $field IS NOT NULL AND $field <> '' ) ";
4718 if (isset($dataType)) {
4719 if (is_array($value)) {
4723 $value = CRM_Utils_Type
::escape($value, "String");
4724 $values = explode(',', CRM_Utils_Array
::value(0, explode(')', CRM_Utils_Array
::value(1, explode('(', $value)))));
4726 // supporting multiple values in IN clause
4728 foreach ($values as $v) {
4730 $val[] = "'" . CRM_Utils_Type
::escape($v, $dataType) . "'";
4732 $value = "(" . implode($val, ",") . ")";
4734 return "$clause $value";
4737 if (empty($dataType)) {
4738 $dataType = 'String';
4741 $value = CRM_Utils_Type
::escape($value, $dataType);
4743 // if we dont have a dataType we should assume
4744 if ($dataType == 'String') {
4745 $value = "'" . strtolower($value) . "'";
4747 return "$clause $value";
4751 function openedSearchPanes($reset = FALSE) {
4752 if (!$reset ||
empty($this->_whereTables
)) {
4753 return self
::$_openedPanes;
4756 // pane name to table mapper
4757 $panesMapper = array(
4758 ts('Contributions') => 'civicrm_contribution',
4759 ts('Memberships') => 'civicrm_membership',
4760 ts('Events') => 'civicrm_participant',
4761 ts('Relationships') => 'civicrm_relationship',
4762 ts('Activities') => 'civicrm_activity',
4763 ts('Pledges') => 'civicrm_pledge',
4764 ts('Cases') => 'civicrm_case',
4765 ts('Grants') => 'civicrm_grant',
4766 ts('Address Fields') => 'civicrm_address',
4767 ts('Notes') => 'civicrm_note',
4768 ts('Change Log') => 'civicrm_log',
4769 ts('Mailings') => 'civicrm_mailing_event_queue',
4772 foreach (array_keys($this->_whereTables
) as $table) {
4773 if ($panName = array_search($table, $panesMapper)) {
4774 self
::$_openedPanes[$panName] = TRUE;
4778 return self
::$_openedPanes;
4781 function setOperator($operator) {
4782 $validOperators = array('AND', 'OR');
4783 if (!in_array($operator, $validOperators)) {
4786 $this->_operator
= $operator;
4789 function getOperator() {
4790 return $this->_operator
;
4793 function filterRelatedContacts(&$from, &$where, &$having) {
4794 static $_rTypeProcessed = NULL;
4795 static $_rTypeFrom = NULL;
4796 static $_rTypeWhere = NULL;
4798 if (!$_rTypeProcessed) {
4799 $_rTypeProcessed = TRUE;
4801 // create temp table with contact ids
4802 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
4803 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
4804 CRM_Core_DAO
::executeQuery($sql);
4807 REPLACE INTO $tableName ( contact_id )
4813 CRM_Core_DAO
::executeQuery($sql);
4815 $qillMessage = ts('Contacts with a Relationship Type of: ');
4816 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
4818 if (is_numeric($this->_displayRelationshipType
)) {
4819 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
4821 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
4822 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
4825 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
4826 AND displayRelType.is_active = 1
4830 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
4831 if ($dirOne == 'a') {
4832 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
4834 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
4835 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
4839 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
4841 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
4842 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
4846 WHERE displayRelType.relationship_type_id = $relType
4847 AND displayRelType.is_active = 1
4851 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
4854 if (strpos($from, $_rTypeFrom) === FALSE) {
4855 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
4856 // this happens when we have an event_type in the quert (CRM-7969)
4857 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
4858 $from .= $_rTypeFrom;
4859 $where = $_rTypeWhere;
4865 static function caseImportant( $op ) {
4867 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
4870 static function componentPresent( &$returnProperties, $prefix ) {
4871 foreach ($returnProperties as $name => $dontCare ) {
4872 if (substr($name, 0, strlen($prefix)) == $prefix) {
4880 * Builds the necessary structures for all fields that are similar to option value lookups
4882 * @param $name string the name of the field
4883 * @param $op string the sql operator, this function should handle ALL SQL operators
4884 * @param $value any string / integer / array depends on the operator and whos calling the query builder
4885 * @param $grouping int the index where to place the where clause
4886 * @param $selectValue array the key value pairs for this element. This allows us to use this function for things besides option-value pairs
4887 * @param $field array an array that contains various properties of the field identified by $name
4888 * @param $label string The label for this field element
4889 * @param $dataType string The data type for this element
4891 * @return void adds the where clause and qill to the query object
4893 function optionValueQuery(
4901 $dataType = 'String'
4904 if (is_numeric($value)) {
4905 $qill = $value = $selectValues[(int ) $value];
4907 elseif ($op == 'IN' ||
$op == 'NOT IN') {
4908 $values = self
::parseSearchBuilderString($value);
4909 if (is_array($values)) {
4910 $newValues = array();
4911 foreach ($values as $v) {
4912 $newValues[] = $selectValues[(int ) $v];
4914 $value = $newValues;
4915 $qill = implode(', ', $value);
4918 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
4919 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
4920 $this->_qill
[$grouping][] = $label . " $op '$qill'";
4923 /** function to check and explode a user defined numeric string into an array
4924 * this was the protocol used by search builder in the old old days before we had
4925 * super nice js widgets to do the hard work
4927 * @param string the string to check
4928 * @param string the dataType we should check for the values, default integer
4930 * @return FALSE if string does not match the patter
4931 * array of numeric values if string does match the pattern
4934 static function parseSearchBuilderString($string, $dataType = 'Integer') {
4935 $string = trim($string);
4936 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
4940 $string = substr($string, 1, -1);
4941 $values = explode(',', $string);
4942 if (empty($values)) {
4946 $returnValues = array();
4947 foreach ($values as $v) {
4948 if ($dataType == 'Integer' && ! is_numeric($v)) {
4951 else if ($dataType == 'String' && ! is_string($v)) {
4954 $returnValues[] = trim($v);
4957 if (empty($returnValues)) {
4961 return $returnValues;