3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
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;
155 * additional permission from clause
160 public $_permissionFromClause;
163 * the from clause for the simple select and alphabetical
168 public $_simpleFromClause;
179 * The english language version of the query
186 * All the fields that could potentially be involved in
194 * The cache to translate the option values into labels
201 * are we in search mode
205 public $_search = TRUE;
208 * should we skip permission checking
212 public $_skipPermission = FALSE;
215 * should we skip adding of delete clause
219 public $_skipDeleteClause = FALSE;
222 * are we in strict mode (use equality over LIKE)
226 public $_strict = FALSE;
229 * What operator to use to group the clauses
233 public $_operator = 'AND';
238 * Should we only search on primary location
242 public $_primaryLocation = TRUE;
245 * are contact ids part of the query
249 public $_includeContactIds = FALSE;
252 * Should we use the smart group cache
256 public $_smartGroupCache = TRUE;
259 * Should we display contacts with a specific relationship type
263 public $_displayRelationshipType = NULL;
266 * reference to the query object for custom values
270 public $_customQuery;
273 * should we enable the distinct clause, used if we are including
274 * more than one group
278 public $_useDistinct = FALSE;
281 * Should we just display one contact record
283 public $_useGroupBy = FALSE;
286 * the relationship type direction
299 static $_activityRole;
302 * Consider the component activity type
303 * during activity search.
308 static $_considerCompActivities;
311 * Consider with contact activities only,
312 * during activity search.
317 static $_withContactActivitiesOnly;
320 * use distinct component clause for component searches
324 public $_distinctComponentClause;
327 * use groupBy component clause for component searches
331 public $_groupByComponentClause;
334 * Track open panes, useful in advance search
339 public static $_openedPanes = array();
342 * The tables which have a dependency on location and/or address
347 static $_dependencies = array(
348 'civicrm_state_province' => 1,
349 'civicrm_country' => 1,
350 'civicrm_county' => 1,
351 'civicrm_address' => 1,
352 'civicrm_location_type' => 1,
356 * List of location specific fields
358 static $_locationSpecificFields = array(
363 'supplemental_address_1',
364 'supplemental_address_2',
367 'postal_code_suffix',
380 * Rememeber if we handle either end of a number or date range
381 * so we can skip the other
383 protected $_rangeCache = array();
385 * Set to true when $this->relationship is run to avoid adding twice
388 protected $_relationshipValuesAdded = FALSE;
391 * Set to the name of the temp table if one has been created
394 static $_relationshipTempTable = NULL;
396 public $_pseudoConstantsSelect = array();
399 * class constructor which also does all the work
401 * @param array $params
402 * @param array $returnProperties
403 * @param array $fields
404 * @param boolean $includeContactIds
405 * @param boolean $strict
406 * @param boolean $mode - mode the search is operating on
411 function __construct(
412 $params = NULL, $returnProperties = NULL, $fields = NULL,
413 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
414 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
415 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
418 $this->_params
= &$params;
419 if ($this->_params
== NULL) {
420 $this->_params
= array();
423 if (empty($returnProperties)) {
424 $this->_returnProperties
= self
::defaultReturnProperties($mode);
427 $this->_returnProperties
= &$returnProperties;
430 $this->_includeContactIds
= $includeContactIds;
431 $this->_strict
= $strict;
432 $this->_mode
= $mode;
433 $this->_skipPermission
= $skipPermission;
434 $this->_smartGroupCache
= $smartGroupCache;
435 $this->_displayRelationshipType
= $displayRelationshipType;
436 $this->setOperator($operator);
439 $this->_fields
= &$fields;
440 $this->_search
= FALSE;
441 $this->_skipPermission
= TRUE;
444 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE);
446 $fields = CRM_Core_Component
::getQueryFields();
447 unset($fields['note']);
448 $this->_fields
= array_merge($this->_fields
, $fields);
450 // add activity fields
451 $fields = CRM_Activity_BAO_Activity
::exportableFields();
452 $this->_fields
= array_merge($this->_fields
, $fields);
454 // add any fields provided by hook implementers
455 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
456 $this->_fields
= array_merge($this->_fields
, $extFields);
459 // basically do all the work once, and then reuse it
464 * function which actually does all the work for the constructor
469 function initialize() {
470 $this->_select
= array();
471 $this->_element
= array();
472 $this->_tables
= array();
473 $this->_whereTables
= array();
474 $this->_where
= array();
475 $this->_qill
= array();
476 $this->_options
= array();
477 $this->_cfIDs
= array();
478 $this->_paramLookup
= array();
479 $this->_having
= array();
481 $this->_customQuery
= NULL;
483 // reset cached static variables - CRM-5803
484 self
::$_activityRole = NULL;
485 self
::$_considerCompActivities = NULL;
486 self
::$_withContactActivitiesOnly = NULL;
488 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
489 $this->_element
['contact_id'] = 1;
490 $this->_tables
['civicrm_contact'] = 1;
492 if (!empty($this->_params
)) {
493 $this->buildParamsLookup();
496 $this->_whereTables
= $this->_tables
;
498 $this->selectClause();
499 $this->_whereClause
= $this->whereClause();
501 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
502 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
504 $this->openedSearchPanes(TRUE);
507 function buildParamsLookup() {
508 // first fix and handle contact deletion nicely
509 // this code is primarily for search builder use case
510 // where different clauses can specify if they want deleted
513 $trashParamExists = FALSE;
514 $paramByGroup = array();
515 foreach ( $this->_params
as $k => $param ) {
516 if (!empty($param[0]) && $param[0] == 'contact_is_deleted' ) {
517 $trashParamExists = TRUE;
519 if (!empty($param[3])) {
520 $paramByGroup[$param[3]][$k] = $param;
524 if ( $trashParamExists ) {
525 $this->_skipDeleteClause
= TRUE;
527 //cycle through group sets and explicitly add trash param if not set
528 foreach ( $paramByGroup as $setID => $set ) {
530 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params
) &&
531 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params
) ) {
532 $this->_params
[] = array(
533 'contact_is_deleted',
543 foreach ($this->_params
as $value) {
544 if (!CRM_Utils_Array
::value(0, $value)) {
547 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
549 if (!array_key_exists($cfID, $this->_cfIDs
)) {
550 $this->_cfIDs
[$cfID] = array();
552 $this->_cfIDs
[$cfID][] = $value;
555 if (!array_key_exists($value[0], $this->_paramLookup
)) {
556 $this->_paramLookup
[$value[0]] = array();
558 $this->_paramLookup
[$value[0]][] = $value;
563 * Some composite fields do not appear in the fields array
564 * hack to make them part of the query
569 function addSpecialFields() {
570 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
571 foreach ($special as $name) {
572 if (CRM_Utils_Array
::value($name, $this->_returnProperties
)) {
573 $this->_select
[$name] = "contact_a.{$name} as $name";
574 $this->_element
[$name] = 1;
580 * Given a list of conditions in params and a list of desired
581 * return Properties generate the required select and from
582 * clauses. Note that since the where clause introduces new
583 * tables, the initial attempt also retrieves all variables used
589 function selectClause() {
591 $this->addSpecialFields();
593 foreach ($this->_fields
as $name => $field) {
594 // skip component fields
595 // there are done by the alter query below
596 // and need not be done on every field
598 (substr($name, 0, 12) == 'participant_') ||
599 (substr($name, 0, 7) == 'pledge_') ||
600 (substr($name, 0, 5) == 'case_')
605 // redirect to activity select clause
606 if (substr($name, 0, 9) == 'activity_') {
607 CRM_Activity_BAO_Query
::select($this);
611 // if this is a hierarchical name, we ignore it
612 $names = explode('-', $name);
613 if (count($names > 1) && isset($names[1]) && is_numeric($names[1])) {
617 // make an exception for special cases, to add the field in select clause
618 $makeException = FALSE;
620 //special handling for groups/tags
621 if (in_array($name, array('groups', 'tags', 'notes'))
622 && isset($this->_returnProperties
[substr($name, 0, -1)])
624 $makeException = TRUE;
627 // since note has 3 different options we need special handling
628 // note / note_subject / note_body
629 if ($name == 'notes') {
630 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
631 if (isset($this->_returnProperties
[$noteField])) {
632 $makeException = TRUE;
638 if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id'))) {
639 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
640 $makeException = TRUE;
644 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
646 CRM_Utils_Array
::value($name, $this->_paramLookup
) ||
647 CRM_Utils_Array
::value($name, $this->_returnProperties
) ||
651 // add to cfIDs array if not present
652 if (!array_key_exists($cfID, $this->_cfIDs
)) {
653 $this->_cfIDs
[$cfID] = array();
656 elseif (isset($field['where'])) {
657 list($tableName, $fieldName) = explode('.', $field['where'], 2);
658 if (isset($tableName)) {
659 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
660 $this->_tables
['civicrm_address'] = 1;
661 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
662 $this->_element
['address_id'] = 1;
665 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
666 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
668 if ($tableName == 'im_provider') {
669 CRM_Core_OptionValue
::select($this);
672 if (in_array($tableName,
673 array('email_greeting', 'postal_greeting', 'addressee'))) {
674 $this->_element
["{$name}_id"] = 1;
675 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
676 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
677 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
678 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
680 if ($tableName == 'email_greeting') {
681 $this->_pseudoConstantsSelect
[$name]['join'] =
682 " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
683 $this->_pseudoConstantsSelect
[$name]['join'] .=
684 " LEFT JOIN civicrm_option_value email_greeting ON (contact_a.email_greeting_id = email_greeting.value AND option_group_email_greeting.id = email_greeting.option_group_id ) ";
686 elseif ($tableName == 'postal_greeting') {
687 $this->_pseudoConstantsSelect
[$name]['join'] =
688 " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
689 $this->_pseudoConstantsSelect
[$name]['join'] .=
690 " LEFT JOIN civicrm_option_value postal_greeting ON (contact_a.postal_greeting_id = postal_greeting.value AND option_group_postal_greeting.id = postal_greeting.option_group_id ) ";
692 elseif ($tableName == 'addressee') {
693 $this->_pseudoConstantsSelect
[$name]['join'] =
694 " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
695 $this->_pseudoConstantsSelect
[$name]['join'] .=
696 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
698 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
701 $greetField = "{$name}_display";
702 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
703 $this->_element
[$greetField] = 1;
705 $greetField = "{$name}_custom";
706 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
707 $this->_element
[$greetField] = 1;
711 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
712 $this->_tables
[$tableName] = 1;
715 // also get the id of the tableName
716 $tName = substr($tableName, 8);
717 if (in_array($tName, array('country', 'state_province', 'county'))) {
718 $pf = ($tName == 'state_province') ?
'state_province_name' : $name;
719 $this->_pseudoConstantsSelect
[$pf] =
720 array('pseudoField' => "{$tName}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address',
721 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
723 if ($tName == 'state_province') {
724 $this->_pseudoConstantsSelect
[$tName] =
725 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id",
726 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
729 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
730 $this->_element
["{$tName}_id"] = 1;
732 elseif ($tName != 'contact') {
733 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
734 $this->_element
["{$tName}_id"] = 1;
737 //special case for phone
738 if ($name == 'phone') {
739 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
740 $this->_element
['phone_type_id'] = 1;
743 // if IM then select provider_id also
744 // to get "IM Service Provider" in a file to be exported, CRM-3140
746 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
747 $this->_element
['provider_id'] = 1;
750 if ($tName == 'contact') {
751 // special case, when current employer is set for Individual contact
752 if ($fieldName == 'organization_name') {
753 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
755 elseif ($fieldName != 'id') {
756 if ($fieldName == 'prefix_id') {
757 $this->_pseudoConstantsSelect
['individual_prefix'] = array('pseudoField' => 'prefix_id', 'idCol' => "prefix_id", 'bao' => 'CRM_Contact_BAO_Contact');
759 if ($fieldName == 'suffix_id') {
760 $this->_pseudoConstantsSelect
['individual_suffix'] = array('pseudoField' => 'suffix_id', 'idCol' => "suffix_id", 'bao' => 'CRM_Contact_BAO_Contact');
762 if ($fieldName == 'gender_id') {
763 $this->_pseudoConstantsSelect
['gender'] = array('pseudoField' => 'gender_id', 'idCol' => "gender_id", 'bao' => 'CRM_Contact_BAO_Contact');
765 $this->_select
[$name] = "contact_a.{$fieldName} as `$name`";
768 elseif (in_array($tName, array('state_province', 'country', 'county'))) {
769 $this->_pseudoConstantsSelect
[$pf]['select'] = "{$field['where']} as `$name`";
770 $this->_pseudoConstantsSelect
[$pf]['element'] = $name;
771 if ($tName == 'state_province') {
772 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
773 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
777 $this->_select
[$name] = "{$field['where']} as `$name`";
779 if (!in_array($tName, array('state_province', 'country', 'county'))) {
780 $this->_element
[$name] = 1;
785 elseif ($name === 'tags') {
786 $this->_useGroupBy
= TRUE;
787 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
788 $this->_element
[$name] = 1;
789 $this->_tables
['civicrm_tag'] = 1;
790 $this->_tables
['civicrm_entity_tag'] = 1;
792 elseif ($name === 'groups') {
793 $this->_useGroupBy
= TRUE;
794 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
795 $this->_element
[$name] = 1;
796 $this->_tables
['civicrm_group'] = 1;
798 elseif ($name === 'notes') {
799 // if note field is subject then return subject else body of the note
800 $noteColumn = 'note';
801 if (isset($noteField) && $noteField == 'note_subject') {
802 $noteColumn = 'subject';
805 $this->_useGroupBy
= TRUE;
806 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
807 $this->_element
[$name] = 1;
808 $this->_tables
['civicrm_note'] = 1;
810 elseif ($name === 'current_employer') {
811 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
812 $this->_element
[$name] = 1;
817 CRM_Utils_Array
::value('is_search_range', $field)
819 // this is a custom field with range search enabled, so we better check for two/from values
820 if (CRM_Utils_Array
::value($name . '_from', $this->_paramLookup
)) {
821 if (!array_key_exists($cfID, $this->_cfIDs
)) {
822 $this->_cfIDs
[$cfID] = array();
824 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
825 // search in the cdID array for the same grouping
827 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
828 if ($c[3] == $p[3]) {
829 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
834 $p[2] = array('from' => $p[2]);
835 $this->_cfIDs
[$cfID][] = $p;
839 if (CRM_Utils_Array
::value($name . '_to', $this->_paramLookup
)) {
840 if (!array_key_exists($cfID, $this->_cfIDs
)) {
841 $this->_cfIDs
[$cfID] = array();
843 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
844 // search in the cdID array for the same grouping
846 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
847 if ($c[4] == $p[4]) {
848 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
853 $p[2] = array('to' => $p[2]);
854 $this->_cfIDs
[$cfID][] = $p;
861 // add location as hierarchical elements
862 $this->addHierarchicalElements();
864 // add multiple field like website
865 $this->addMultipleElements();
868 CRM_Core_Component
::alterQuery($this, 'select');
870 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
872 if (!empty($this->_cfIDs
)) {
873 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE);
874 $this->_customQuery
->query();
875 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
876 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
877 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
878 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
879 $this->_options
= $this->_customQuery
->_options
;
884 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
890 function addHierarchicalElements() {
891 if (!CRM_Utils_Array
::value('location', $this->_returnProperties
)) {
894 if (!is_array($this->_returnProperties
['location'])) {
898 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
899 $processed = array();
902 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
903 $addressCustomFieldIds = array();
905 foreach ($this->_returnProperties
['location'] as $name => $elements) {
906 $lCond = self
::getPrimaryCondition($name);
909 $locationTypeId = array_search($name, $locationTypes);
910 if ($locationTypeId === FALSE) {
913 $lCond = "location_type_id = $locationTypeId";
914 $this->_useDistinct
= TRUE;
916 //commented for CRM-3256
917 $this->_useGroupBy
= TRUE;
920 $name = str_replace(' ', '_', $name);
922 $tName = "$name-location_type";
923 $ltName = "`$name-location_type`";
924 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
925 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
926 $this->_element
["{$tName}_id"] = 1;
927 $this->_element
["{$tName}"] = 1;
929 $locationTypeName = $tName;
930 $locationTypeJoin = array();
934 foreach ($elements as $elementFullName => $dontCare) {
936 $elementName = $elementCmpName = $elementFullName;
938 if (substr($elementCmpName, 0, 5) == 'phone') {
939 $elementCmpName = 'phone';
942 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
943 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
944 $addressCustomFieldIds[$cfID][$name] = 1;
947 //add address table only once
948 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
950 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
952 $tName = "$name-address";
953 $aName = "`$name-address`";
954 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
955 $this->_element
["{$tName}_id"] = 1;
956 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
957 $this->_tables
[$tName] = $addressJoin;
958 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
959 $processed[$aName] = 1;
963 $cond = $elementType = '';
964 if (strpos($elementName, '-') !== FALSE) {
965 // this is either phone, email or IM
966 list($elementName, $elementType) = explode('-', $elementName);
969 if (($elementName != 'phone') && ($elementName != 'im')) {
970 $cond = self
::getPrimaryCondition($elementType);
972 // CRM-13011 : If location type is primary, do not restrict search to the phone
973 // type id - we want the primary phone, regardless of what type it is.
974 // Otherwise, restrict to the specified phone type for the given field.
975 if ((!$cond) && ($elementName == 'phone') && $elements['location_type'] != 'Primary') {
976 $cond = "phone_type_id = '$elementType'";
978 elseif ((!$cond) && ($elementName == 'im')) {
979 // IM service provider id, CRM-3140
980 $cond = "provider_id = '$elementType'";
982 $elementType = '-' . $elementType;
985 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
987 // hack for profile, add location id
990 // fix for CRM-882( to handle phone types )
991 !is_numeric($elementType)
993 if (is_numeric($name)) {
994 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
997 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1000 elseif (is_numeric($name)) {
1001 //this for phone type to work
1002 if (in_array($elementName, array('phone', 'phone_ext'))) {
1003 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1006 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1010 //this is for phone type to work for profile edit
1011 if (in_array($elementName, array('phone', 'phone_ext'))) {
1012 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1015 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1020 // Check if there is a value, if so also add to where Clause
1022 if ($this->_params
) {
1024 if (isset($locationTypeId)) {
1025 $nm .= "-$locationTypeId";
1027 if (!is_numeric($elementType)) {
1028 $nm .= "$elementType";
1031 foreach ($this->_params
as $id => $values) {
1032 if ($values[0] == $nm ||
1033 (in_array($elementName, array('phone', 'im'))
1034 && (strpos($values[0], $nm) !== FALSE)
1044 if ($field && isset($field['where'])) {
1045 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1046 $pf = substr($tableName, 8);
1047 $tName = $name . '-' . $pf . $elementType;
1048 if (isset($tableName)) {
1049 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1050 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1053 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1056 $this->_element
["{$tName}_id"] = 1;
1057 if (substr($tName, -15) == '-state_province') {
1058 // FIXME: hack to fix CRM-1900
1059 $a = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1063 if (substr_count($a, 'state_province_name') > 0) {
1064 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1065 array('pseudoField' => '{$pf}_id', 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1066 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1069 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1070 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id");
1071 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1075 if (substr($elementFullName, 0, 2) == 'im') {
1076 $provider = "{$name}-{$elementFullName}-provider_id";
1077 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1078 $this->_element
[$provider] = 1;
1080 if ($pf == 'country' ||
$pf == 'county') {
1081 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array('pseudoField' => "{$pf}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1082 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1085 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1089 if (in_array($pf, array('state_province', 'country', 'county'))) {
1090 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1093 $this->_element
["{$name}-{$elementFullName}"] = 1;
1096 if (!CRM_Utils_Array
::value("`$tName`", $processed)) {
1097 $processed["`$tName`"] = 1;
1098 $newName = $tableName . '_' . $index;
1099 switch ($tableName) {
1100 case 'civicrm_phone':
1101 case 'civicrm_email':
1103 case 'civicrm_openid':
1105 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id AND `$tName`.$lCond";
1106 // this special case to add phone type
1108 $phoneTypeCondition = " AND `$tName`.$cond ";
1109 //gross hack to pickup corrupted data also, CRM-7603
1110 if (strpos($cond, 'phone_type_id') !== FALSE) {
1111 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1113 $this->_tables
[$tName] .= $phoneTypeCondition;
1116 //build locationType join
1117 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1120 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1124 case 'civicrm_state_province':
1125 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1126 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1127 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1129 $this->_whereTables
["{$name}-address"] = $addressJoin;
1133 case 'civicrm_country':
1134 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1135 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1136 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1138 $this->_whereTables
["{$name}-address"] = $addressJoin;
1142 case 'civicrm_county':
1143 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1144 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1145 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1147 $this->_whereTables
["{$name}-address"] = $addressJoin;
1153 $this->_whereTables
["{$name}-address"] = $addressJoin;
1162 // add location type join
1163 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1164 $this->_tables
[$locationTypeName] = $ltypeJoin;
1166 // table should be present in $this->_whereTables,
1167 // to add its condition in location type join, CRM-3939.
1168 if ($addWhereCount) {
1169 $locClause = array();
1170 foreach ($this->_whereTables
as $tableName => $clause) {
1171 if (CRM_Utils_Array
::value($tableName, $locationTypeJoin)) {
1172 $locClause[] = $locationTypeJoin[$tableName];
1176 if (!empty($locClause)) {
1177 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1182 if (!empty($addressCustomFieldIds)) {
1183 $cfIDs = $addressCustomFieldIds;
1184 $customQuery = new CRM_Core_BAO_CustomQuery($cfIDs);
1185 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1186 foreach ($locTypeName as $name => $dnc) {
1187 $fieldName = "$name-custom_{$cfID}";
1188 $tName = "$name-address-custom-{$cfID}";
1189 $aName = "`$name-address-custom-{$cfID}`";
1190 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1191 $this->_element
["{$tName}_id"] = 1;
1192 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1193 $this->_element
[$fieldName] = 1;
1194 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1201 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
1207 function addMultipleElements() {
1208 if (!CRM_Utils_Array
::value('website', $this->_returnProperties
)) {
1211 if (!is_array($this->_returnProperties
['website'])) {
1215 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1216 foreach ($elements as $elementFullName => $dontCare) {
1217 $tName = "website-{$key}-{$elementFullName}";
1218 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1219 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1220 $this->_element
["{$tName}_id"] = 1;
1221 $this->_element
["{$tName}"] = 1;
1223 $type = "website-{$key}-website_type_id";
1224 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1225 $this->_element
[$type] = 1;
1226 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id )";
1232 * generate the query based on what type of query we need
1234 * @param boolean $count
1235 * @param boolean $sortByChar
1236 * @param boolean $groupContacts
1238 * @return the sql string for that query (this will most likely
1242 function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE) {
1244 if (isset($this->_distinctComponentClause
)) {
1245 // we add distinct to get the right count for components
1246 // for the more complex result set, we use GROUP BY the same id
1248 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1251 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1253 $from = $this->_simpleFromClause
;
1254 if ($this->_useDistinct
) {
1255 $this->_useGroupBy
= TRUE;
1258 elseif ($sortByChar) {
1259 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1260 $from = $this->_simpleFromClause
;
1262 elseif ($groupContacts) {
1263 $select = 'SELECT contact_a.id as id';
1264 if ($this->_useDistinct
) {
1265 $this->_useGroupBy
= TRUE;
1267 $from = $this->_simpleFromClause
;
1270 if (CRM_Utils_Array
::value('group', $this->_paramLookup
)) {
1271 // make sure there is only one element
1272 // this is used when we are running under smog and need to know
1273 // how the contact was added (CRM-1203)
1274 if ((count($this->_paramLookup
['group']) == 1) &&
1275 (count($this->_paramLookup
['group'][0][2]) == 1)
1277 $groups = array_keys($this->_paramLookup
['group'][0][2]);
1278 $groupId = $groups[0];
1280 //check if group is saved search
1281 $group = new CRM_Contact_BAO_Group();
1282 $group->id
= $groupId;
1285 if (!isset($group->saved_search_id
)) {
1286 $tbName = "`civicrm_group_contact-{$groupId}`";
1287 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1288 $this->_element
['group_contact_id'] = 1;
1289 $this->_select
['status'] = "$tbName.status as status";
1290 $this->_element
['status'] = 1;
1293 $this->_useGroupBy
= TRUE;
1295 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1296 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1298 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1299 $this->_useDistinct
= FALSE;
1300 $this->_useGroupBy
= TRUE;
1304 $select = "SELECT ";
1305 if (isset($this->_distinctComponentClause
)) {
1306 $select .= "{$this->_distinctComponentClause}, ";
1308 $select .= implode(', ', $this->_select
);
1309 $from = $this->_fromClause
;
1313 if (!empty($this->_whereClause
)) {
1314 $where = "WHERE {$this->_whereClause}";
1318 if (!empty($this->_having
)) {
1319 foreach ($this->_having
as $havingsets) {
1320 foreach ($havingsets as $havingset) {
1321 $havingvalue[] = $havingset;
1324 $having = ' HAVING ' . implode(' AND ', $havingvalue);
1327 // if we are doing a transform, do it here
1328 // use the $from, $where and $having to get the contact ID
1329 if ($this->_displayRelationshipType
) {
1330 $this->filterRelatedContacts($from, $where, $having);
1333 return array($select, $from, $where, $having);
1336 function &getWhereValues($name, $grouping) {
1338 foreach ($this->_params
as $values) {
1339 if ($values[0] == $name && $values[3] == $grouping) {
1347 static function fixDateValues($relative, &$from, &$to) {
1349 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1353 static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE) {
1355 if (empty($formValues)) {
1359 foreach ($formValues as $id => $values) {
1360 if ($id == 'privacy') {
1361 if (is_array($formValues['privacy'])) {
1362 $op = CRM_Utils_Array
::value('do_not_toggle', $formValues['privacy']) ?
'=' : '!=';
1363 foreach ($formValues['privacy'] as $key => $value) {
1365 $params[] = array($key, $op, $value, 0, 0);
1370 elseif ($id == 'email_on_hold') {
1371 if ($formValues['email_on_hold']['on_hold']) {
1372 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1375 elseif (preg_match('/_date_relative$/', $id) ||
1376 $id == 'event_relative' ||
1377 $id == 'case_from_relative' ||
1378 $id == 'case_to_relative'
1380 if ($id == 'event_relative') {
1381 $fromRange = 'event_start_date_low';
1382 $toRange = 'event_end_date_high';
1384 else if ($id == 'case_from_relative') {
1385 $fromRange = 'case_from_start_date_low';
1386 $toRange = 'case_from_start_date_high';
1388 else if ($id == 'case_to_relative') {
1389 $fromRange = 'case_to_end_date_low';
1390 $toRange = 'case_to_end_date_high';
1393 $dateComponent = explode('_date_relative', $id);
1394 $fromRange = "{$dateComponent[0]}_date_low";
1395 $toRange = "{$dateComponent[0]}_date_high";
1398 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1399 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1404 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals);
1409 $params[] = $values;
1415 static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE) {
1416 // skip a few search variables
1417 static $skipWhere = NULL;
1418 static $arrayValues = NULL;
1419 static $likeNames = NULL;
1422 if (CRM_Utils_System
::isNull($values)) {
1428 'task', 'radio_ts', 'uf_group_id',
1429 'component_mode', 'qfKey', 'operator',
1430 'display_relationship_type',
1434 if (in_array($id, $skipWhere) ||
1435 substr($id, 0, 4) == '_qf_' ||
1436 substr($id, 0, 7) == 'hidden_'
1442 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1445 // email comes in via advanced search
1446 // so use wildcard always
1447 if ($id == 'email') {
1451 if (!$useEquals && in_array($id, $likeNames)) {
1452 $result = array($id, 'LIKE', $values, 0, 1);
1454 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1455 $result = array($id, 'LIKE', $values, 0, 0);
1457 elseif ($id == 'group') {
1458 if (is_array($values)) {
1459 foreach ($values as $groupIds => $val) {
1461 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1462 if (strlen($matches[1]) > 0) {
1463 $values[$matches[1]] = 1;
1464 unset($values[$groupIds]);
1470 $groupIds = explode(',', $values);
1472 foreach ($groupIds as $groupId) {
1473 $values[$groupId] = 1;
1477 $result = array($id, 'IN', $values, 0, 0);
1479 elseif ($id == 'contact_tags' ||
$id == 'tag') {
1480 if (!is_array($values)) {
1481 $tagIds = explode(',', $values);
1483 foreach ($tagIds as $tagId) {
1484 $values[$tagId] = 1;
1487 $result = array($id, 'IN', $values, 0, 0);
1490 $result = array($id, '=', $values, 0, $wildcard);
1496 function whereClauseSingle(&$values) {
1497 // do not process custom fields or prefixed contact ids or component params
1498 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1499 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1500 (substr($values[0], 0, 13) == 'contribution_') ||
1501 (substr($values[0], 0, 6) == 'event_') ||
1502 (substr($values[0], 0, 12) == 'participant_') ||
1503 (substr($values[0], 0, 7) == 'member_') ||
1504 (substr($values[0], 0, 6) == 'grant_') ||
1505 (substr($values[0], 0, 7) == 'pledge_') ||
1506 (substr($values[0], 0, 5) == 'case_') ||
1507 (substr($values[0], 0, 10) == 'financial_') ||
1508 (substr($values[0], 0, 11) == 'membership_')
1513 // skip for hook injected fields / params
1514 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1515 if (array_key_exists($values[0], $extFields)) {
1519 switch ($values[0]) {
1520 case 'deleted_contacts':
1521 $this->deletedContacts($values);
1524 case 'contact_type':
1525 $this->contactType($values);
1528 case 'contact_sub_type':
1529 $this->contactSubType($values);
1533 $this->group($values);
1537 // so we resolve this into a list of groups & proceed as if they had been
1539 list($name, $op, $value, $grouping, $wildcard) = $values;
1540 $values[0] = 'group';
1542 $this->_paramLookup
['group'][0][0] ='group';
1543 $this->_paramLookup
['group'][0][1] = 'IN';
1544 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1545 $this->group($values);
1548 // case tag comes from find contacts
1550 $this->tagSearch($values);
1554 case 'contact_tags':
1555 $this->tag($values);
1560 case 'note_subject':
1561 $this->notes($values);
1565 $this->ufUser($values);
1569 case 'display_name':
1570 $this->sortName($values);
1574 $this->email($values);
1577 case 'phone_numeric':
1578 $this->phone_numeric($values);
1581 case 'phone_phone_type_id':
1582 case 'phone_location_type_id':
1583 $this->phone_option_group($values);
1586 case 'street_address':
1587 $this->street_address($values);
1590 case 'street_number':
1591 $this->street_number($values);
1594 case 'sortByCharacter':
1595 $this->sortByCharacter($values);
1598 case 'location_type':
1599 $this->locationType($values);
1603 $this->county($values);
1606 case 'state_province':
1607 $this->stateProvince($values);
1611 $this->country($values, FALSE);
1615 case 'postal_code_low':
1616 case 'postal_code_high':
1617 $this->postalCode($values);
1620 case 'activity_date':
1621 case 'activity_date_low':
1622 case 'activity_date_high':
1623 case 'activity_role':
1624 case 'activity_status':
1625 case 'activity_subject':
1626 case 'test_activities':
1627 case 'activity_type_id':
1628 case 'activity_survey_id':
1629 case 'activity_tags':
1630 case 'activity_taglist':
1631 case 'activity_test':
1632 case 'activity_campaign_id':
1633 case 'activity_engagement_level':
1635 case 'activity_result':
1636 case 'source_contact':
1637 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1640 case 'birth_date_low':
1641 case 'birth_date_high':
1642 case 'deceased_date_low':
1643 case 'deceased_date_high':
1644 $this->demographics($values);
1647 case 'log_date_low':
1648 case 'log_date_high':
1649 $this->modifiedDates($values);
1653 $this->changeLog($values);
1656 case 'do_not_phone':
1657 case 'do_not_email':
1660 case 'do_not_trade':
1662 $this->privacy($values);
1665 case 'privacy_options':
1666 $this->privacyOptions($values);
1669 case 'privacy_operator':
1670 case 'privacy_toggle':
1671 // these are handled by privacy options
1674 case 'preferred_communication_method':
1675 $this->preferredCommunication($values);
1678 case 'relation_type_id':
1679 case 'relation_start_date_high':
1680 case 'relation_start_date_low':
1681 case 'relation_end_date_high':
1682 case 'relation_end_date_low':
1683 case 'relation_target_name':
1684 case 'relation_status':
1685 case 'relation_date_low':
1686 case 'relation_date_high':
1687 $this->relationship($values);
1688 $this->_relationshipValuesAdded
= TRUE;
1691 case 'task_status_id':
1692 $this->task($values);
1696 // since this case is handled with the above
1699 case 'prox_distance':
1700 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1703 case 'prox_street_address':
1705 case 'prox_postal_code':
1706 case 'prox_state_province_id':
1707 case 'prox_country_id':
1708 // handled by the proximity_distance clause
1712 $this->restWhere($values);
1718 * Given a list of conditions in params generate the required
1724 function whereClause() {
1725 $this->_where
[0] = array();
1726 $this->_qill
[0] = array();
1728 $this->includeContactIds();
1729 if (!empty($this->_params
)) {
1730 foreach (array_keys($this->_params
) as $id) {
1731 if (!CRM_Utils_Array
::value(0, $this->_params
[$id])) {
1734 // check for both id and contact_id
1735 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
1737 $this->_params
[$id][1] == 'IS NULL' ||
1738 $this->_params
[$id][1] == 'IS NOT NULL'
1740 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]}";
1742 elseif (is_array($this->_params
[$id][2])) {
1743 $idList = implode("','", $this->_params
[$id][2]);
1744 //why on earth do they put ' in the middle & not on the outside? We have to assume it's
1745 //to support 'something' so lets add them conditionally to support the api (which is a tested flow
1746 // so if you are looking to alter this check api test results
1747 if(strpos(trim($idList), "'") > 0) {
1748 $idList = "'" . $idList . "'";
1751 $this->_where
[0][] = "contact_a.id IN ({$idList})";
1754 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]} {$this->_params[$id][2]}";
1758 $this->whereClauseSingle($this->_params
[$id]);
1762 CRM_Core_Component
::alterQuery($this, 'where');
1764 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
1767 if ($this->_customQuery
) {
1768 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1769 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1770 if (!empty($this->_customQuery
->_where
)) {
1771 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
1774 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
1778 $andClauses = array();
1781 if (!empty($this->_where
)) {
1782 foreach ($this->_where
as $grouping => $values) {
1783 if ($grouping > 0 && !empty($values)) {
1784 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1789 if (!empty($this->_where
[0])) {
1790 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
1792 if (!empty($clauses)) {
1793 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1796 if ($validClauses > 1) {
1797 $this->_useDistinct
= TRUE;
1801 return implode(' AND ', $andClauses);
1804 function restWhere(&$values) {
1805 $name = CRM_Utils_Array
::value(0, $values);
1806 $op = CRM_Utils_Array
::value(1, $values);
1807 $value = CRM_Utils_Array
::value(2, $values);
1808 $grouping = CRM_Utils_Array
::value(3, $values);
1809 $wildcard = CRM_Utils_Array
::value(4, $values);
1811 if (isset($grouping) && !CRM_Utils_Array
::value($grouping, $this->_where
)) {
1812 $this->_where
[$grouping] = array();
1815 $multipleFields = array('url');
1817 //check if the location type exits for fields
1819 $locType = explode('-', $name);
1821 if (!in_array($locType[0], $multipleFields)) {
1822 //add phone type if exists
1823 if (isset($locType[2]) && $locType[2]) {
1824 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
1828 $field = CRM_Utils_Array
::value($name, $this->_fields
);
1831 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
1840 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
1841 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1843 if (substr($name, 0, 14) === 'state_province') {
1844 if (isset($locType[1]) && is_numeric($locType[1])) {
1846 $aName = "{$locationType[$locType[1]]}-address";
1847 $where = "`$aName`.state_province_id";
1850 $where = "civicrm_address.state_province_id";
1853 $states = CRM_Core_PseudoConstant
::stateProvince();
1854 if (is_numeric($value)) {
1855 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1856 $value = $states[(int ) $value];
1859 $intVal = CRM_Utils_Array
::key($value, $states);
1860 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1863 $this->_qill
[$grouping][] = ts('State') . " $op '$value'";
1866 $this->_qill
[$grouping][] = ts('State') . " ($lType) $op '$value'";
1869 elseif (!empty($field['pseudoconstant'])) {
1870 $this->optionValueQuery(
1871 $name, $op, $value, $grouping,
1872 CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', $field['name']),
1878 if ($name == 'gender_id') {
1879 self
::$_openedPanes[ts('Demographics')] = TRUE;
1882 elseif (substr($name, 0, 7) === 'country') {
1883 if (isset($locType[1]) && is_numeric($locType[1])) {
1885 $aName = "{$locationType[$locType[1]]}-address";
1886 $where = "`$aName`.country_id";
1889 $where = "civicrm_address.country_id";
1892 $countries = CRM_Core_PseudoConstant
::country();
1893 if (is_numeric($value)) {
1894 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1895 $value = $countries[(int ) $value];
1898 $intVal = CRM_Utils_Array
::key($value, $countries);
1899 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1903 $this->_qill
[$grouping][] = ts('Country') . " $op '$value'";
1906 $this->_qill
[$grouping][] = ts('Country') . " ($lType) $op '$value'";
1909 elseif (substr($name, 0, 6) === 'county') {
1910 if (isset($locType[1]) && is_numeric($locType[1])) {
1912 $aName = "{$locationType[$locType[1]]}-address";
1913 $where = "`$aName`.county_id";
1916 $where = "civicrm_address.county_id";
1919 $counties = CRM_Core_PseudoConstant
::county();
1920 if (is_numeric($value)) {
1921 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1922 $value = $counties[(int ) $value];
1925 $intVal = CRM_Utils_Array
::key($value, $counties);
1926 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1930 $this->_qill
[$grouping][] = ts('County') . " $op '$value'";
1933 $this->_qill
[$grouping][] = ts('County') . " ($lType) $op '$value'";
1936 elseif ($name === 'world_region') {
1937 $this->optionValueQuery(
1938 $name, $op, $value, $grouping,
1939 CRM_Core_PseudoConstant
::worldRegion(),
1944 elseif ($name === 'birth_date') {
1945 $date = CRM_Utils_Date
::processDate($value);
1946 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
1949 $date = CRM_Utils_Date
::customFormat($date);
1950 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
1953 $this->_qill
[$grouping][] = "$field[title] $op";
1955 self
::$_openedPanes[ts('Demographics')] = TRUE;
1957 elseif ($name === 'deceased_date') {
1958 $date = CRM_Utils_Date
::processDate($value);
1959 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
1961 $date = CRM_Utils_Date
::customFormat($date);
1962 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
1965 $this->_qill
[$grouping][] = "$field[title] $op";
1967 self
::$_openedPanes[ts('Demographics')] = TRUE;
1969 elseif ($name === 'is_deceased') {
1970 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
1971 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
1972 self
::$_openedPanes[ts('Demographics')] = TRUE;
1974 elseif ($name === 'contact_id') {
1975 if (is_int($value)) {
1976 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
1977 $this->_qill
[$grouping][] = "$field[title] $op $value";
1980 elseif ($name === 'name') {
1981 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
1983 $value = "%$value%";
1986 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
1987 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
1988 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
1990 elseif ($name === 'current_employer') {
1991 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
1993 $value = "%$value%";
1996 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
1997 $ceWhereClause = self
::buildClause($wc, $op,
2000 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2001 $this->_where
[$grouping][] = $ceWhereClause;
2002 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2004 elseif ($name === 'email_greeting') {
2005 $filterCondition = array('greeting_type' => 'email_greeting');
2006 $this->optionValueQuery(
2007 $name, $op, $value, $grouping,
2008 CRM_Core_PseudoConstant
::greeting($filterCondition),
2010 ts('Email Greeting')
2013 elseif ($name === 'postal_greeting') {
2014 $filterCondition = array('greeting_type' => 'postal_greeting');
2015 $this->optionValueQuery(
2016 $name, $op, $value, $grouping,
2017 CRM_Core_PseudoConstant
::greeting($filterCondition),
2019 ts('Postal Greeting')
2022 elseif ($name === 'addressee') {
2023 $filterCondition = array('greeting_type' => 'addressee');
2024 $this->optionValueQuery(
2025 $name, $op, $value, $grouping,
2026 CRM_Core_PseudoConstant
::greeting($filterCondition),
2031 elseif (substr($name, 0, 4) === 'url-') {
2032 $tName = 'civicrm_website';
2033 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2034 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2036 $value = "%$value%";
2040 $wc = 'civicrm_website.url';
2041 $this->_where
[$grouping][] = $d = self
::buildClause($wc, $op, $value);
2042 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2044 elseif ($name === 'contact_is_deleted') {
2045 $this->_where
[$grouping][] = self
::buildClause("contact_a.is_deleted", $op, $value);
2046 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2049 // sometime the value is an array, need to investigate and fix
2050 if (is_array($value)) {
2051 CRM_Core_Error
::fatal();
2054 if (!empty($field['where'])) {
2056 $value = $strtolower($value);
2059 $value = "%$value%";
2063 if (isset($locType[1]) &&
2064 is_numeric($locType[1])
2068 //get the location name
2069 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2071 $where = "`$tName`.$fldName";
2073 $this->_where
[$grouping][] = self
::buildClause("LOWER($where)", $op, $value);
2074 $this->_whereTables
[$tName] = $this->_tables
[$tName];
2075 $this->_qill
[$grouping][] = "$field[title] $op '$value'";
2078 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2079 if ($tableName == 'civicrm_contact') {
2080 $fieldName = "LOWER(contact_a.{$fieldName})";
2083 if ($op != 'IN' && !is_numeric($value)) {
2084 $fieldName = "LOWER({$field['where']})";
2087 $fieldName = "{$field['where']}";
2092 if (CRM_Utils_Array
::value('type', $field)) {
2093 $type = CRM_Utils_Type
::typeToString($field['type']);
2096 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2097 $this->_qill
[$grouping][] = "$field[title] $op $value";
2102 if ($setTables && isset($field['where'])) {
2103 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2104 if (isset($tableName)) {
2105 $this->_tables
[$tableName] = 1;
2106 $this->_whereTables
[$tableName] = 1;
2112 static function getLocationTableName(&$where, &$locType) {
2113 if (isset($locType[1]) && is_numeric($locType[1])) {
2114 list($tbName, $fldName) = explode(".", $where);
2116 //get the location name
2117 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2118 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2119 if (in_array($locType[0], $specialFields)) {
2120 //hack to fix / special handing for phone_ext
2121 if ($locType[0] == 'phone_ext') {
2122 $locType[0] = 'phone';
2124 if (isset($locType[2]) && $locType[2]) {
2125 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2128 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2131 elseif (in_array($locType[0],
2133 'address_name', 'street_address', 'supplemental_address_1', 'supplemental_address_2',
2134 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
2137 //fix for search by profile with address fields.
2138 $tName = "{$locationType[$locType[1]]}-address";
2140 elseif ($locType[0] == 'on_hold') {
2141 $tName = "{$locationType[$locType[1]]}-email";
2144 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2146 $tName = str_replace(' ', '_', $tName);
2147 return array($tName, $fldName);
2149 CRM_Core_Error
::fatal();
2153 * Given a result dao, extract the values and return that array
2155 * @param Object $dao
2157 * @return array values for this query
2159 function store($dao) {
2162 foreach ($this->_element
as $key => $dontCare) {
2163 if (property_exists($dao, $key)) {
2164 if (strpos($key, '-') !== FALSE) {
2165 $values = explode('-', $key);
2166 $lastElement = array_pop($values);
2168 $cnt = count($values);
2170 foreach ($values as $v) {
2171 if (!array_key_exists($v, $current)) {
2172 $current[$v] = array();
2174 //bad hack for im_provider
2175 if ($lastElement == 'provider_id') {
2176 if ($count < $cnt) {
2177 $current = &$current[$v];
2180 $lastElement = "{$v}_{$lastElement}";
2184 $current = &$current[$v];
2189 $current[$lastElement] = $dao->$key;
2192 $value[$key] = $dao->$key;
2200 * getter for tables array
2206 return $this->_tables
;
2209 function whereTables() {
2210 return $this->_whereTables
;
2214 * generate the where clause (used in match contacts and permissions)
2216 * @param array $params
2217 * @param array $fields
2218 * @param array $tables
2219 * @param boolean $strict
2225 static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2226 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2230 $tables = array_merge($query->tables(), $tables);
2231 $whereTables = array_merge($query->whereTables(), $whereTables);
2233 return $query->_whereClause
;
2237 * create the from clause
2239 * @param array $tables tables that need to be included in this from clause
2240 * if null, return mimimal from clause (i.e. civicrm_contact)
2241 * @param array $inner tables that should be inner-joined
2242 * @param array $right tables that should be right-joined
2244 * @return string the from clause
2248 static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2250 $from = ' FROM civicrm_contact contact_a';
2251 if (empty($tables)) {
2255 if (CRM_Utils_Array
::value('civicrm_worldregion', $tables)) {
2256 $tables = array_merge(array('civicrm_country' => 1), $tables);
2259 if ((CRM_Utils_Array
::value('civicrm_state_province', $tables) ||
2260 CRM_Utils_Array
::value('civicrm_country', $tables) ||
2261 CRM_Utils_Array
::value('civicrm_county', $tables)
2263 !CRM_Utils_Array
::value('civicrm_address', $tables)
2265 $tables = array_merge(array('civicrm_address' => 1),
2270 // add group_contact table if group table is present
2271 if (CRM_Utils_Array
::value('civicrm_group', $tables) &&
2272 !CRM_Utils_Array
::value('civicrm_group_contact', $tables)
2274 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
2277 // add group_contact and group table is subscription history is present
2278 if (CRM_Utils_Array
::value('civicrm_subscription_history', $tables)
2279 && !CRM_Utils_Array
::value('civicrm_group', $tables)
2281 $tables = array_merge(array(
2282 'civicrm_group' => 1,
2283 'civicrm_group_contact' => 1,
2289 // to handle table dependencies of components
2290 CRM_Core_Component
::tableNames($tables);
2291 // to handle table dependencies of hook injected tables
2292 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2294 //format the table list according to the weight
2295 $info = CRM_Core_TableHierarchy
::info();
2297 foreach ($tables as $key => $value) {
2299 if (strpos($key, '-') !== FALSE) {
2300 $keyArray = explode('-', $key);
2301 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2303 elseif (strpos($key, '_') !== FALSE) {
2304 $keyArray = explode('_', $key);
2305 if (is_numeric(array_pop($keyArray))) {
2306 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2309 $k = CRM_Utils_Array
::value($key, $info, 99);
2313 $k = CRM_Utils_Array
::value($key, $info, 99);
2315 $tempTable[$k . ".$key"] = $key;
2318 $newTables = array();
2319 foreach ($tempTable as $key) {
2320 $newTables[$key] = $tables[$key];
2323 $tables = $newTables;
2325 foreach ($tables as $name => $value) {
2330 if (CRM_Utils_Array
::value($name, $inner)) {
2333 elseif (CRM_Utils_Array
::value($name, $right)) {
2341 // if there is already a join statement in value, use value itself
2342 if (strpos($value, 'JOIN')) {
2343 $from .= " $value ";
2346 $from .= " $side JOIN $name ON ( $value ) ";
2351 case 'civicrm_address':
2352 if ($primaryLocation) {
2353 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2356 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2360 case 'civicrm_phone':
2361 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2364 case 'civicrm_email':
2365 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2369 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2373 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2374 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2375 $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)";
2378 case 'civicrm_openid':
2379 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2382 case 'civicrm_worldregion':
2383 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2384 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2387 case 'civicrm_location_type':
2388 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2391 case 'civicrm_group':
2392 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2395 case 'civicrm_group_contact':
2396 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2399 case 'civicrm_activity':
2400 case 'civicrm_activity_tag':
2401 case 'activity_type':
2402 case 'activity_status':
2403 case 'civicrm_activity_contact':
2404 case 'source_contact':
2405 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2408 case 'civicrm_entity_tag':
2409 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2410 civicrm_entity_tag.entity_id = contact_a.id ) ";
2413 case 'civicrm_note':
2414 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2415 contact_a.id = civicrm_note.entity_id ) ";
2418 case 'civicrm_subscription_history':
2419 $from .= " $side JOIN civicrm_subscription_history
2420 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2421 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2424 case 'civicrm_relationship':
2425 if (self
::$_relType == 'reciprocal') {
2426 if(self
::$_relationshipTempTable) {
2427 // we have a temptable to join on
2428 $tbl = self
::$_relationshipTempTable;
2429 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2432 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2433 $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)";
2436 elseif (self
::$_relType == 'b') {
2437 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2438 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2441 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2442 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2447 $from .= " $side JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2448 $from .= " $side JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2452 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2455 case 'civicrm_grant':
2456 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2459 case 'civicrm_website':
2460 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2464 $from .= CRM_Core_Component
::from($name, $mode, $side);
2465 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2475 * WHERE / QILL clause for deleted_contacts
2479 function deletedContacts($values) {
2480 list($_, $_, $value, $grouping, $_) = $values;
2482 // *prepend* to the relevant grouping as this is quite an important factor
2483 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2488 * where / qill clause for contact_type
2493 function contactType(&$values) {
2494 list($name, $op, $value, $grouping, $wildcard) = $values;
2496 $subTypes = array();
2499 // account for search builder mapping multiple values
2500 if (!is_array($value)) {
2501 $values = self
::parseSearchBuilderString($value, 'String');
2502 if (is_array($values)) {
2503 $value = array_flip($values);
2507 if (is_array($value)) {
2508 foreach ($value as $k => $v) {
2513 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2514 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2517 if (!empty($subType)) {
2518 $subTypes[$subType] = 1;
2520 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2525 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2526 $contactType = $contactTypeANDSubType[0];
2527 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2528 if (!empty($subType)) {
2529 $subTypes[$subType] = 1;
2531 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2535 if (!empty($clause)) {
2536 if ($op == 'IN' ||
$op == 'NOT IN') {
2537 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2541 $type = array_pop($clause);
2542 $this->_where
[$grouping][] = "contact_a.contact_type $op $type";
2545 $this->_qill
[$grouping][] = ts('Contact Type') . ' - ' . implode(' ' . ts('or') . ' ', $quill);
2547 if (!empty($subTypes)) {
2548 $this->includeContactSubTypes($subTypes, $grouping);
2554 * where / qill clause for contact_sub_type
2559 function contactSubType(&$values) {
2560 list($name, $op, $value, $grouping, $wildcard) = $values;
2561 $this->includeContactSubTypes($value, $grouping);
2564 function includeContactSubTypes($value, $grouping) {
2567 $alias = "contact_a.contact_sub_type";
2569 if (is_array($value)) {
2570 foreach ($value as $k => $v) {
2572 $clause[$k] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($k, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2577 $clause[$value] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2580 if (!empty($clause)) {
2581 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2582 $this->_qill
[$grouping][] = ts('Contact Subtype') . ' - ' . implode(' ' . ts('or') . ' ', array_keys($clause));
2587 * where / qill clause for groups
2592 function group(&$values) {
2593 list($name, $op, $value, $grouping, $wildcard) = $values;
2595 if (count($value) > 1) {
2596 $this->_useDistinct
= TRUE;
2599 $groupNames = CRM_Core_PseudoConstant
::group();
2600 $groupIds = implode(',', array_keys($value));
2603 foreach ($value as $id => $dontCare) {
2604 if (array_key_exists($id, $groupNames) && $dontCare) {
2605 $names[] = $groupNames[$id];
2611 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2613 is_array($gcsValues[2])
2615 foreach ($gcsValues[2] as $k => $v) {
2617 if ($k == 'Added') {
2620 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2625 $statii[] = '"Added"';
2630 if (count($value) == 1 &&
2631 count($statii) == 1 &&
2632 $statii[0] == '"Added"'
2634 // check if smart group, if so we can get rid of that one additional
2636 $groupIDs = array_keys($value);
2638 if (CRM_Utils_Array
::value(0, $groupIDs) &&
2639 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
2649 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2650 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON ( contact_a.id = {$gcTable}.contact_id AND {$gcTable}.group_id $op ( $groupIds ) )";
2653 $qill = ts('Contacts %1', array(1 => $op));
2654 $qill .= ' ' . implode(' ' . ts('or') . ' ', $names);
2656 $groupClause = NULL;
2659 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2660 if (!empty($statii)) {
2661 $groupClause .= " AND {$gcTable}.status IN (" . implode(', ', $statii) . ")";
2662 $qill .= " " . ts('AND') . " " . ts('Group Status') . ' - ' . implode(' ' . ts('or') . ' ', $statii);
2667 $ssClause = $this->savedSearch($values);
2670 $groupClause = "( ( $groupClause ) OR ( $ssClause ) )";
2673 $groupClause = $ssClause;
2678 $this->_where
[$grouping][] = $groupClause;
2679 $this->_qill
[$grouping][] = $qill;
2682 * Function translates selection of group type into a list of groups
2684 function getGroupsFromTypeCriteria($value){
2685 $groupIds = array();
2686 foreach ($value as $groupTypeValue) {
2687 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2688 $groupIds = ($groupIds +
$groupList);
2694 * where / qill clause for smart groups
2699 function savedSearch(&$values) {
2700 list($name, $op, $value, $grouping, $wildcard) = $values;
2701 return $this->addGroupContactCache(array_keys($value));
2704 function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
2705 $config = CRM_Core_Config
::singleton();
2707 // find all the groups that are part of a saved search
2708 $groupIDs = implode(',', $groups);
2709 if (empty($groupIDs)) {
2714 SELECT id, cache_date, saved_search_id, children
2716 WHERE id IN ( $groupIDs )
2717 AND ( saved_search_id != 0
2718 OR saved_search_id IS NOT NULL
2719 OR children IS NOT NULL )
2721 $group = CRM_Core_DAO
::executeQuery($sql);
2723 while ($group->fetch()) {
2724 if ($tableAlias == NULL) {
2725 $alias = "`civicrm_group_contact_cache_{$group->id}`";
2728 $alias = $tableAlias;
2731 $this->_useDistinct
= TRUE;
2733 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
2734 CRM_Contact_BAO_GroupContactCache
::load($group);
2737 $this->_tables
[$alias] = $this->_whereTables
[$alias] = " LEFT JOIN civicrm_group_contact_cache {$alias} ON {$joinTable}.id = {$alias}.contact_id ";
2738 $ssWhere[] = "{$alias}.group_id = {$group->id}";
2741 if (!empty($ssWhere)) {
2742 return implode(' OR ', $ssWhere);
2748 * where / qill clause for cms users
2753 function ufUser(&$values) {
2754 list($name, $op, $value, $grouping, $wildcard) = $values;
2757 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2759 $this->_qill
[$grouping][] = ts('CMS User');
2761 elseif ($value == 0) {
2762 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2764 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2765 $this->_qill
[$grouping][] = ts('Not a CMS User');
2770 * all tag search specific
2775 function tagSearch(&$values) {
2776 list($name, $op, $value, $grouping, $wildcard) = $values;
2779 $value = "%{$value}%";
2782 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2783 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2785 $etTable = "`civicrm_entity_tag-" . $value . "`";
2786 $tTable = "`civicrm_tag-" . $value . "`";
2788 if ($useAllTagTypes[2]) {
2789 $this->_tables
[$etTable] =
2790 $this->_whereTables
[$etTable] =
2791 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
2792 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
2794 // search tag in cases
2795 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2796 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
2797 $this->_tables
[$etCaseTable] =
2798 $this->_whereTables
[$etCaseTable] =
2799 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2800 LEFT JOIN civicrm_case
2801 ON (civicrm_case_contact.case_id = civicrm_case.id
2802 AND civicrm_case.is_deleted = 0 )
2803 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
2804 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
2805 // search tag in activities
2806 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2807 $tActTable = "`civicrm_act_tag-" . $value . "`";
2808 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2809 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2811 $this->_tables
[$etActTable] =
2812 $this->_whereTables
[$etActTable] =
2813 " LEFT JOIN civicrm_activity_contact
2814 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
2815 LEFT JOIN civicrm_activity
2816 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
2817 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2818 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
2819 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
2821 $this->_where
[$grouping][] = "({$tTable}.name $op '". $value . "' OR {$tCaseTable}.name $op '". $value . "' OR {$tActTable}.name $op '". $value . "')";
2822 $this->_qill
[$grouping][] = ts('Tag %1 %2 ', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
2824 $etTable = "`civicrm_entity_tag-" . $value . "`";
2825 $tTable = "`civicrm_tag-" . $value . "`";
2826 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
2827 {$etTable}.entity_table = 'civicrm_contact' )
2828 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
2830 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
2831 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
2836 * where / qill clause for tag
2841 function tag(&$values) {
2842 list($name, $op, $value, $grouping, $wildcard) = $values;
2844 $tagNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
2845 if (is_array($value)) {
2846 if (count($value) > 1) {
2847 $this->_useDistinct
= TRUE;
2849 foreach ($value as $id => $dontCare) {
2850 $names[] = CRM_Utils_Array
::value($id, $tagNames);
2852 $names = implode(' ' . ts('or') . ' ', $names);
2853 $value = implode(',', array_keys($value));
2856 $names = CRM_Utils_Array
::value($value, $tagNames);
2860 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2861 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2863 $etTable = "`civicrm_entity_tag-" . $value . "`";
2865 if ($useAllTagTypes[2]) {
2866 $this->_tables
[$etTable] =
2867 $this->_whereTables
[$etTable] =
2868 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2870 // search tag in cases
2871 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2872 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2873 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2875 $this->_tables
[$etCaseTable] =
2876 $this->_whereTables
[$etCaseTable] =
2877 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2878 LEFT JOIN civicrm_case
2879 ON (civicrm_case_contact.case_id = civicrm_case.id
2880 AND civicrm_case.is_deleted = 0 )
2881 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
2882 // search tag in activities
2883 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2884 $this->_tables
[$etActTable] =
2885 $this->_whereTables
[$etActTable] =
2886 " LEFT JOIN civicrm_activity_contact
2887 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
2888 LEFT JOIN civicrm_activity
2889 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
2890 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2891 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
2894 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
2895 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
2898 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (". $value . ") OR {$etCaseTable}.tag_id $op (". $value . ") OR {$etActTable}.tag_id $op (". $value . "))";
2900 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
2902 $this->_tables
[$etTable] =
2903 $this->_whereTables
[$etTable] =
2904 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2907 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
2908 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
2909 $op = str_replace('EMPTY', 'NULL', $op);
2910 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
2913 $this->_where
[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
2915 $this->_qill
[$grouping][] = ts('Tagged %1', array( 1 => $op)) . ' ' . $names;
2921 * where/qill clause for notes
2926 function notes(&$values) {
2927 list($name, $op, $value, $grouping, $wildcard) = $values;
2929 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
2930 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
2931 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
2933 $this->_useDistinct
= TRUE;
2935 $this->_tables
['civicrm_note'] =
2936 $this->_whereTables
['civicrm_note'] =
2937 " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
2939 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2941 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
2942 if ($wildcard ||
$op == 'LIKE') {
2943 if (strpos($value, '%') === FALSE) {
2944 $value = "%$value%";
2948 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
2954 if ( $noteOption %
2 == 0 ) {
2955 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
2956 $label = ts('Note: Body Only');
2958 if ( $noteOption %
3 == 0 ) {
2959 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
2960 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
2962 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
2963 $this->_qill
[$grouping][] = $label . " $op - '$n'";
2966 function nameNullOrEmptyOp($name, $op, $grouping) {
2970 $this->_where
[$grouping][] = "contact_a.$name $op";
2971 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
2975 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
2976 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
2979 case 'IS NOT EMPTY':
2980 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
2981 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
2990 * where / qill clause for sort_name
2995 function sortName(&$values) {
2996 list($name, $op, $value, $grouping, $wildcard) = $values;
2998 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
2999 if ( $this->nameNullOrEmptyOp( $name, $op, $grouping ) ) {
3004 $name = trim($value);
3010 $config = CRM_Core_Config
::singleton();
3014 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3017 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3018 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3020 if (substr($name, 0, 1) == '"' &&
3021 substr($name, -1, 1) == '"'
3023 //If name is encased in double quotes, the value should be taken to be the string in entirety and the
3024 $value = substr($name, 1, -1);
3025 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
3026 $wc = ($newName == 'sort_name') ?
'LOWER(contact_a.sort_name)' : 'LOWER(contact_a.display_name)';
3027 $sub[] = " ( $wc = '$value' ) ";
3028 if ($config->includeEmailInName
) {
3029 $sub[] = " ( civicrm_email.email = '$value' ) ";
3032 elseif (strpos($name, ',') !== FALSE) {
3033 // if we have a comma in the string, search for the entire string
3034 $value = $strtolower(CRM_Core_DAO
::escapeString($name));
3036 if ($config->includeWildCardInName
) {
3037 $value = "'%$value%'";
3040 $value = "'$value%'";
3045 $value = "'$value'";
3047 if ($newName == 'sort_name') {
3048 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3051 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3053 $sub[] = " ( $wc $op $value )";
3054 if ($config->includeNickNameInName
) {
3055 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3056 $sub[] = " ( $wc $op $value )";
3058 if ($config->includeEmailInName
) {
3059 $sub[] = " ( civicrm_email.email $op $value ) ";
3063 // the string should be treated as a series of keywords to be matched with match ANY OR
3064 // match ALL depending on Civi config settings (see CiviAdmin)
3066 // The Civi configuration setting can be overridden if the string *starts* with the case
3067 // insenstive strings 'AND:' or 'OR:'TO THINK ABOUT: what happens when someone searches
3068 // for the following "AND: 'a string in quotes'"? - probably nothing - it would make the
3069 // AND OR variable reduntant because there is only one search string?
3071 // Check to see if the $subGlue is overridden in the search text
3072 if (strtolower(substr($name, 0, 4)) == 'and:') {
3073 $name = substr($name, 4);
3076 if (strtolower(substr($name, 0, 3)) == 'or:') {
3077 $name = substr($name, 3);
3081 $firstChar = substr($name, 0, 1);
3082 $lastChar = substr($name, -1, 1);
3083 $quotes = array("'", '"');
3084 if ((strlen($name) > 2) && in_array($firstChar, $quotes) &&
3085 in_array($lastChar, $quotes)
3087 $name = substr($name, 1);
3088 $name = substr($name, 0, -1);
3089 $pieces = array($name);
3092 $pieces = explode(' ', $name);
3094 foreach ($pieces as $piece) {
3095 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($piece)));
3096 if (strlen($value)) {
3097 // Added If as a sanitization - without it, when you do an OR search, any string with
3098 // double spaces (i.e. " ") or that has a space after the keyword (e.g. "OR: ") will
3099 // return all contacts because it will include a condition similar to "OR contact
3100 // name LIKE '%'". It might be better to replace this with array_filter.
3101 $fieldsub = array();
3103 if ($config->includeWildCardInName
) {
3104 $value = "'%$value%'";
3107 $value = "'$value%'";
3112 $value = "'$value'";
3114 if ($newName == 'sort_name') {
3115 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3118 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3120 $fieldsub[] = " ( $wc $op $value )";
3121 if ($config->includeNickNameInName
) {
3122 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3123 $fieldsub[] = " ( $wc $op $value )";
3125 if ($config->includeEmailInName
) {
3126 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3128 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3129 // I seperated the glueing in two. The first stage should always be OR because we are searching for matches in *ANY* of these fields
3134 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3136 $this->_where
[$grouping][] = $sub;
3137 if ($config->includeEmailInName
) {
3138 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3139 $this->_qill
[$grouping][] = ts('Name or Email ') . "$op - '$name'";
3142 $this->_qill
[$grouping][] = ts('Name like') . " - '$name'";
3147 * where / qill clause for email
3152 function email(&$values) {
3153 list($name, $op, $value, $grouping, $wildcard) = $values;
3157 $config = CRM_Core_Config
::singleton();
3159 if (substr($n, 0, 1) == '"' &&
3160 substr($n, -1, 1) == '"'
3162 $n = substr($n, 1, -1);
3163 $value = strtolower(CRM_Core_DAO
::escapeString($n));
3164 $value = "'$value'";
3168 $value = strtolower($n);
3170 if (strpos($value, '%') === FALSE) {
3171 $value = "%{$value}%";
3176 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3177 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3180 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3181 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3184 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3188 * where / qill clause for phone number
3193 function phone_numeric(&$values) {
3194 list($name, $op, $value, $grouping, $wildcard) = $values;
3195 // Strip non-numeric characters; allow wildcards
3196 $number = preg_replace('/[^\d%]/', '', $value);
3198 if ( strpos($number, '%') === FALSE ) {
3199 $number = "%$number%";
3202 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3203 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3204 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3209 * where / qill clause for phone type/location
3214 function phone_option_group($values) {
3215 list($name, $op, $value, $grouping, $wildcard) = $values;
3216 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3217 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3218 $optionName = $options[$value];
3219 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3220 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3221 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3225 * where / qill clause for street_address
3230 function street_address(&$values) {
3231 list($name, $op, $value, $grouping, $wildcard) = $values;
3240 $value = strtolower($n);
3241 if (strpos($value, '%') === FALSE) {
3242 // only add wild card if not there
3243 $value = "%{$value}%";
3246 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3247 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3250 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3251 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3254 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3258 * where / qill clause for street_unit
3263 function street_number(&$values) {
3264 list($name, $op, $value, $grouping, $wildcard) = $values;
3272 if (strtolower($n) == 'odd') {
3273 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3274 $this->_qill
[$grouping][] = ts('Street Number is odd');
3276 elseif (strtolower($n) == 'even') {
3277 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3278 $this->_qill
[$grouping][] = ts('Street Number is even');
3281 $value = strtolower($n);
3283 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3284 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3287 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3291 * where / qill clause for sorting by character
3296 function sortByCharacter(&$values) {
3297 list($name, $op, $value, $grouping, $wildcard) = $values;
3299 $name = trim($value);
3300 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3301 $this->_where
[$grouping][] = $cond;
3302 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3306 * where / qill clause for including contact ids
3311 function includeContactIDs() {
3312 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3316 $contactIds = array();
3317 foreach ($this->_params
as $id => $values) {
3318 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3319 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3322 if (!empty($contactIds)) {
3323 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3328 * where / qill clause for postal code
3333 function postalCode(&$values) {
3334 // skip if the fields dont have anything to do with postal_code
3335 if (!CRM_Utils_Array
::value('postal_code', $this->_fields
)) {
3339 list($name, $op, $value, $grouping, $wildcard) = $values;
3341 // Handle numeric postal code range searches properly by casting the column as numeric
3342 if (is_numeric($value)) {
3343 $field = 'ROUND(civicrm_address.postal_code)';
3344 $val = CRM_Utils_Type
::escape($value, 'Integer');
3347 $field = 'civicrm_address.postal_code';
3348 $val = CRM_Utils_Type
::escape($value, 'String');
3351 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3353 if ($name == 'postal_code') {
3354 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3355 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3357 elseif ($name == 'postal_code_low') {
3358 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3359 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3361 elseif ($name == 'postal_code_high') {
3362 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3363 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3368 * where / qill clause for location type
3373 function locationType(&$values, $status = NULL) {
3374 list($name, $op, $value, $grouping, $wildcard) = $values;
3376 if (is_array($value)) {
3377 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', array_keys($value)) . ')';
3378 $this->_tables
['civicrm_address'] = 1;
3379 $this->_whereTables
['civicrm_address'] = 1;
3381 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3383 foreach (array_keys($value) as $id) {
3384 $names[] = $locationType[$id];
3387 $this->_primaryLocation
= FALSE;
3390 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3393 return implode(' ' . ts('or') . ' ', $names);
3398 function country(&$values, $fromStateProvince = TRUE) {
3399 list($name, $op, $value, $grouping, $wildcard) = $values;
3401 if (!$fromStateProvince) {
3402 $stateValues = $this->getWhereValues('state_province', $grouping);
3403 if (!empty($stateValues)) {
3404 // return back to caller if there are state province values
3405 // since that handles this case
3410 $countryClause = $countryQill = NULL;
3416 $this->_tables
['civicrm_address'] = 1;
3417 $this->_whereTables
['civicrm_address'] = 1;
3419 $countries = CRM_Core_PseudoConstant
::country();
3420 if (is_numeric($value)) {
3421 $countryClause = self
::buildClause(
3422 'civicrm_address.country_id',
3427 $countryName = $countries[(int ) $value];
3431 $intValues = self
::parseSearchBuilderString($value);
3432 if ($intValues && ($op == 'IN' ||
$op == 'NOT IN')) {
3433 $countryClause = self
::buildClause(
3434 'civicrm_address.country_id',
3439 $countryNames = array();
3440 foreach ($intValues as $v) {
3441 $countryNames[] = $countries[$v];
3443 $countryName = implode(',', $countryNames);
3446 $countries = CRM_Core_PseudoConstant
::country();
3447 $intVal = CRM_Utils_Array
::key($value, $countries);
3448 $countryClause = self
::buildClause(
3449 'civicrm_address.country_id',
3454 $countryName = $value;
3457 $countryQill = ts('Country') . " {$op} '$countryName'";
3459 if (!$fromStateProvince) {
3460 $this->_where
[$grouping][] = $countryClause;
3461 $this->_qill
[$grouping][] = $countryQill;
3465 if ($fromStateProvince) {
3466 if (!empty($countryClause)) {
3469 " ...AND... " . $countryQill,
3473 return array(NULL, NULL);
3479 * where / qill clause for county (if present)
3484 function county(&$values, $status = null) {
3485 list($name, $op, $value, $grouping, $wildcard) = $values;
3487 if (! is_array($value)) {
3488 // force the county to be an array
3489 $value = array($value);
3492 // check if the values are ids OR names of the counties
3493 $inputFormat = 'id';
3494 foreach ($value as $v) {
3495 if (!is_numeric($v)) {
3496 $inputFormat = 'name';
3504 else if ($op == '!=') {
3508 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3509 $op = str_replace('EMPTY', 'NULL', $op);
3512 if (in_array( $op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3513 $clause = "civicrm_address.county_id $op";
3515 elseif ($inputFormat == 'id') {
3516 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3518 $county = CRM_Core_PseudoConstant
::county();
3519 foreach ($value as $id) {
3520 $names[] = CRM_Utils_Array
::value($id, $county);
3524 $inputClause = array();
3525 $county = CRM_Core_PseudoConstant
::county();
3526 foreach ($value as $name) {
3527 $name = trim($name);
3528 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3530 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3533 $this->_tables
['civicrm_address'] = 1;
3534 $this->_whereTables
['civicrm_address'] = 1;
3536 $this->_where
[$grouping][] = $clause;
3538 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3540 return implode(' ' . ts('or') . ' ', $names);
3545 * where / qill clause for state/province AND country (if present)
3550 function stateProvince(&$values, $status = NULL) {
3551 list($name, $op, $value, $grouping, $wildcard) = $values;
3553 // quick escape for IS NULL
3554 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3557 else if (!is_array($value)) {
3558 // force the state to be an array
3559 // check if its in the mapper format!
3560 $values = self
::parseSearchBuilderString($value);
3561 if (is_array($values)) {
3565 $value = array($value);
3569 // check if the values are ids OR names of the states
3570 $inputFormat = 'id';
3572 foreach ($value as $v) {
3573 if (!is_numeric($v)) {
3574 $inputFormat = 'name';
3584 else if ($op == '!=') {
3588 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3589 $op = str_replace('EMPTY', 'NULL', $op);
3591 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3592 $stateClause = "civicrm_address.state_province_id $op";
3594 else if ($inputFormat == 'id') {
3595 if ($op != 'NOT IN') {
3598 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
3600 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3601 foreach ($value as $id) {
3602 $names[] = CRM_Utils_Array
::value($id, $stateProvince);
3606 $inputClause = array();
3607 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3608 foreach ($value as $name) {
3609 $name = trim($name);
3610 $inputClause[] = CRM_Utils_Array
::key($name, $stateProvince);
3612 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
3615 $this->_tables
['civicrm_address'] = 1;
3616 $this->_whereTables
['civicrm_address'] = 1;
3618 $countryValues = $this->getWhereValues('country', $grouping);
3619 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3621 if ($countryClause) {
3622 $clause = "( $stateClause AND $countryClause )";
3625 $clause = $stateClause;
3628 $this->_where
[$grouping][] = $clause;
3630 $this->_qill
[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3633 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
3638 * where / qill clause for change log
3643 function changeLog(&$values) {
3644 list($name, $op, $value, $grouping, $wildcard) = $values;
3646 $targetName = $this->getWhereValues('changed_by', $grouping);
3651 $name = trim($targetName[2]);
3652 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3653 $name = $targetName[4] ?
"%$name%" : $name;
3654 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3655 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3656 $this->_qill
[$grouping][] = ts('Changed by') . ": $name";
3659 function modifiedDates($values) {
3660 $this->_useDistinct
= TRUE;
3662 // CRM-11281, default to added date if not set
3663 $fieldTitle = ts('Added Date');
3665 foreach (array_keys($this->_params
) as $id) {
3666 if ($this->_params
[$id][0] == 'log_date') {
3667 if ($this->_params
[$id][2] == 2) {
3668 $fieldTitle = ts('Modified Date');
3673 $this->dateQueryBuilder($values,
3674 'civicrm_log', 'log_date', 'modified_date', $fieldTitle
3678 function demographics(&$values) {
3679 list($name, $op, $value, $grouping, $wildcard) = $values;
3681 if (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3683 $this->dateQueryBuilder($values,
3684 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3687 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3689 $this->dateQueryBuilder($values,
3690 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3694 self
::$_openedPanes[ts('Demographics')] = TRUE;
3697 function privacy(&$values) {
3698 list($name, $op, $value, $grouping, $wildcard) = $values;
3699 //fixed for profile search listing CRM-4633
3700 if (strpbrk($value, "[")) {
3701 $value = "'{$value}'";
3703 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3706 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3708 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3709 $title = $field ?
$field['title'] : $name;
3710 $this->_qill
[$grouping][] = "$title $op $value";
3713 function privacyOptions($values) {
3714 list($name, $op, $value, $grouping, $wildcard) = $values;
3716 if (empty($value) ||
!is_array($value)) {
3720 // get the operator and toggle values
3721 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3724 strtolower($opValues[2] == 'AND')
3729 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3731 if ($toggleValues &&
3732 $toggleValues[2] == 2
3739 foreach ($value as $dontCare => $pOption) {
3740 $clauses[] = " ( contact_a.{$pOption} $compareOP 1 ) ";
3741 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3742 $title = $field ?
$field['title'] : $pOption;
3743 $qill[] = " $title $compareOP 1 ";
3746 $this->_where
[$grouping][] = '( ' . implode($operator, $clauses) . ' )';
3747 $this->_qill
[$grouping][] = implode($operator, $qill);
3750 function preferredCommunication(&$values) {
3751 list($name, $op, $value, $grouping, $wildcard) = $values;
3754 if (in_array($op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3757 elseif (!is_array($value)) {
3759 $value = trim($value, ' ()');
3760 if (strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
3761 $v = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
3764 $v = explode(",", $value);
3767 foreach ($v as $item) {
3774 foreach ($value as $key => $checked) {
3781 $commPref = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
3783 $sqlValue = array();
3784 $showValue = array();
3785 $sql = "contact_a.preferred_communication_method";
3786 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3787 $sqlValue[] = "{$sql} {$op}";
3790 foreach ($pref as $val) {
3791 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $val . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' ) ";
3792 $showValue[] = $commPref[$val];
3795 $this->_where
[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
3796 $this->_qill
[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
3800 * where / qill clause for relationship
3805 function relationship(&$values) {
3806 list($name, $op, $value, $grouping, $wildcard) = $values;
3807 if($this->_relationshipValuesAdded
){
3810 // also get values array for relation_target_name
3811 // for relatinship search we always do wildcard
3812 $targetName = $this->getWhereValues('relation_target_name', $grouping);
3813 $relStatus = $this->getWhereValues('relation_status', $grouping);
3814 $relPermission = $this->getWhereValues('relation_permission', $grouping);
3815 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
3817 $nameClause = $name = NULL;
3819 $name = trim($targetName[2]);
3820 if (substr($name, 0, 1) == '"' &&
3821 substr($name, -1, 1) == '"'
3823 $name = substr($name, 1, -1);
3824 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3825 $nameClause = "= '$name'";
3828 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3829 $nameClause = "LIKE '%{$name}%'";
3833 $rel = explode('_', $value);
3835 self
::$_relType = $rel[1];
3836 $params = array('id' => $rel[0]);
3837 $rTypeValues = array();
3838 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
3839 if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
3840 // if we don't know which end of the relationship we are dealing with we'll create a temp table
3841 //@todo unless we are dealing with a target group
3842 self
::$_relType = 'reciprocal';
3844 // if we are creating a temp table we build our own where for the relationship table
3845 $relationshipTempTable = NULL;
3846 if(self
::$_relType == 'reciprocal' && empty($targetGroup)) {
3848 self
::$_relationshipTempTable =
3849 $relationshipTempTable =
3850 CRM_Core_DAO
::createTempTableName( 'civicrm_rel');
3852 $where[$grouping][] = " sort_name $nameClause ";
3856 $where = &$this->_where
;
3858 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
3863 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
3864 $relTypeOrg = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
3865 $relTypeHou = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Household');
3866 $allRelationshipType = array();
3867 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
3868 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
3870 if ($nameClause ||
!$targetGroup) {
3871 $this->_qill
[$grouping][] = "$allRelationshipType[$value] $name";
3875 //check to see if the target contact is in specified group
3877 //add contacts from static groups
3878 $this->_tables
['civicrm_relationship_group_contact'] =
3879 $this->_whereTables
['civicrm_relationship_group_contact'] =
3880 " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = contact_b.id AND civicrm_relationship_group_contact.status = 'Added'";
3882 "( civicrm_relationship_group_contact.group_id IN (" .
3883 implode(",", $targetGroup[2]) . ") ) ";
3885 //add contacts from saved searches
3886 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
3888 //set the group where clause
3890 $groupWhere[] = "( " . $ssWhere . " )";
3892 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
3894 //Get the names of the target groups for the qill
3895 $groupNames = CRM_Core_PseudoConstant
::group();
3896 $qillNames = array();
3897 foreach ($targetGroup[2] as $groupId) {
3898 if (array_key_exists($groupId, $groupNames)) {
3899 $qillNames[] = $groupNames[$groupId];
3902 $this->_qill
[$grouping][] = "$allRelationshipType[$value] ( " . implode(", ", $qillNames) . " )";
3905 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
3906 $today = date('Ymd');
3907 //check for active, inactive and all relation status
3908 if ($relStatus[2] == 0) {
3909 $where[$grouping][] = "(
3910 civicrm_relationship.is_active = 1 AND
3911 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
3912 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
3914 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
3916 elseif ($relStatus[2] == 1) {
3917 $where[$grouping][] = "(
3918 civicrm_relationship.is_active = 0 OR
3919 civicrm_relationship.end_date < {$today} OR
3920 civicrm_relationship.start_date > {$today}
3922 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
3925 //check for permissioned, non-permissioned and all permissioned relations
3926 if ($relPermission[2] == 1) {
3927 $this->_where
[$grouping][] = "(
3928 civicrm_relationship.is_permission_a_b = 1
3930 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
3931 } elseif ($relPermission[2] == 2) {
3932 //non-allowed permission relationship.
3933 $this->_where
[$grouping][] = "(
3934 civicrm_relationship.is_permission_a_b = 0
3936 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
3939 $this->addRelationshipDateClauses($grouping, $where);
3940 if(!empty($rType) && isset($rType->id
)){
3941 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
3943 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
3944 $this->_useDistinct
= TRUE;
3945 $this->_relationshipValuesAdded
= TRUE;
3946 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
3948 // @todo creating a temp table could be expanded to group filter
3949 // as even creating a temp table of all relationships is much much more efficient than
3950 // an OR in the join
3951 if($relationshipTempTable) {
3952 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
3954 CREATE TEMPORARY TABLE {$relationshipTempTable}
3955 (SELECT contact_id_b as contact_id, civicrm_relationship.id
3956 FROM civicrm_relationship
3957 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
3960 (SELECT contact_id_a as contact_id, civicrm_relationship.id
3961 FROM civicrm_relationship
3962 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
3965 CRM_Core_DAO
::executeQuery($sql);
3970 * Add start & end date criteria in
3971 * @param string $grouping
3972 * @param array $where = array to add where clauses to, in case you are generating a temp table
3973 * not the main query.
3975 function addRelationshipDateClauses($grouping, &$where){
3976 $dateValues = array();
3982 foreach ($dateTypes as $dateField){
3983 $dateValueLow = $this->getWhereValues('relation_'. $dateField .'_low', $grouping);
3984 $dateValueHigh= $this->getWhereValues('relation_'. $dateField .'_high', $grouping);
3985 if(!empty($dateValueLow)){
3986 $date = date('Ymd', strtotime($dateValueLow[2]));
3987 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
3988 $this->_qill
[$grouping][] = ($dateField == 'end_date' ?
ts('Relationship Ended on or After') : ts('Relationship Recorded Start Date On or Before')) . " " . CRM_Utils_Date
::customFormat($date);
3990 if(!empty($dateValueHigh)){
3991 $date = date('Ymd', strtotime($dateValueHigh[2]));
3992 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
3993 $this->_qill
[$grouping][] = ( $dateField == 'end_date' ?
ts('Relationship Ended on or Before') : ts('Relationship Recorded Start Date On or After')) . " " . CRM_Utils_Date
::customFormat($date);
3998 * default set of return properties
4003 static function &defaultReturnProperties($mode = 1) {
4004 if (!isset(self
::$_defaultReturnProperties)) {
4005 self
::$_defaultReturnProperties = array();
4008 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4009 // add activity return properties
4010 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4011 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4014 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4017 if (empty(self
::$_defaultReturnProperties[$mode])) {
4018 self
::$_defaultReturnProperties[$mode] = array(
4021 'legal_identifier' => 1,
4022 'external_identifier' => 1,
4023 'contact_type' => 1,
4024 'contact_sub_type' => 1,
4026 'display_name' => 1,
4027 'preferred_mail_format' => 1,
4036 'street_address' => 1,
4037 'supplemental_address_1' => 1,
4038 'supplemental_address_2' => 1,
4041 'postal_code_suffix' => 1,
4042 'state_province' => 1,
4044 'world_region' => 1,
4051 'household_name' => 1,
4052 'organization_name' => 1,
4053 'deceased_date' => 1,
4058 'current_employer' => 1,
4059 // FIXME: should we use defaultHierReturnProperties() for the below?
4060 'do_not_email' => 1,
4063 'do_not_phone' => 1,
4064 'do_not_trade' => 1,
4066 'contact_is_deleted' => 1,
4067 'preferred_communication_method' => 1,
4068 'preferred_language' => 1,
4072 return self
::$_defaultReturnProperties[$mode];
4076 * get primary condition for a sql clause
4083 static function getPrimaryCondition($value) {
4084 if (is_numeric($value)) {
4085 $value = (int ) $value;
4086 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4092 * wrapper for a simple search query
4094 * @param array $params
4095 * @param array $returnProperties
4096 * @param \bolean|bool $count
4101 static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4102 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4103 list($select, $from, $where, $having) = $query->query();
4105 return "$select $from $where $having";
4109 * These are stub comments as this function needs more explanation - particularly in terms of how it
4110 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4112 * This function was originally written as a wrapper for the api query but is called from multiple places
4113 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4114 * but it is unclear as to whehter that is historical or there is a reason
4115 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4117 * @param array $params
4118 * @param array $returnProperties
4119 * @param null $fields
4120 * @param string $sort
4121 * @param int $offset
4122 * @param int $row_count
4123 * @param bool $smartGroupCache
4124 * @param bool $count return count obnly
4125 * @param bool $skipPermissions Should permissions be ignored or should the logged in user's permissions be applied
4127 * @params bool $smartGroupCache ?? update smart group cache?
4132 static function apiQuery(
4134 $returnProperties = NULL,
4139 $smartGroupCache = TRUE,
4141 $skipPermissions = TRUE
4144 $query = new CRM_Contact_BAO_Query(
4145 $params, $returnProperties,
4146 NULL, TRUE, FALSE, 1,
4148 TRUE, $smartGroupCache
4151 //this should add a check for view deleted if permissions are enabled
4152 if ($skipPermissions){
4153 $query->_skipDeleteClause
= TRUE;
4155 $query->generatePermissionClause(FALSE, $count);
4157 // note : this modifies _fromClause and _simpleFromClause
4158 $query->includePseudoFieldsJoin($sort);
4160 list($select, $from, $where, $having) = $query->query($count);
4162 $options = $query->_options
;
4163 if(!empty($query->_permissionWhereClause
)){
4164 if (empty($where)) {
4165 $where = "WHERE $query->_permissionWhereClause";
4168 $where = "$where AND $query->_permissionWhereClause";
4172 $sql = "$select $from $where $having";
4175 if ($query->_useGroupBy
) {
4176 $sql .= ' GROUP BY contact_a.id';
4178 if (!empty($sort)) {
4179 $sort = CRM_Utils_Type
::escape($sort, 'String');
4180 $sql .= " ORDER BY $sort ";
4182 if ($row_count > 0 && $offset >= 0) {
4183 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4184 $rowCount = CRM_Utils_Type
::escape($row_count, 'Int');
4185 $sql .= " LIMIT $offset, $row_count ";
4188 $dao = CRM_Core_DAO
::executeQuery($sql);
4191 while ($dao->fetch()) {
4193 $noRows = $dao->rowCount
;
4195 return array($noRows,NULL);
4197 $val = $query->store($dao);
4198 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4200 if (!empty($convertedVals)) {
4201 $val = array_replace_recursive($val, $convertedVals);
4203 $values[$dao->contact_id
] = $val;
4206 return array($values, $options);
4210 * create and query the db for an contact search
4212 * @param int $offset the offset for the query
4213 * @param int $rowCount the number of rows to return
4214 * @param string $sort the order by string
4215 * @param boolean $count is this a count only query ?
4216 * @param boolean $includeContactIds should we include contact ids?
4217 * @param boolean $sortByChar if true returns the distinct array of first characters for search results
4218 * @param boolean $groupContacts if true, return only the contact ids
4219 * @param boolean $returnQuery should we return the query as a string
4220 * @param string $additionalWhereClause if the caller wants to further restrict the search (used for components)
4221 * @param string $additionalFromClause should be clause with proper joins, effective to reduce where clause load.
4223 * @return CRM_Contact_DAO_Contact
4226 function searchQuery(
4227 $offset = 0, $rowCount = 0, $sort = NULL,
4228 $count = FALSE, $includeContactIds = FALSE,
4229 $sortByChar = FALSE, $groupContacts = FALSE,
4230 $returnQuery = FALSE,
4231 $additionalWhereClause = NULL, $sortOrder = NULL,
4232 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4235 if ($includeContactIds) {
4236 $this->_includeContactIds
= TRUE;
4237 $this->_whereClause
= $this->whereClause();
4240 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4242 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4243 // and that contact happens to be deleted, set $onlyDeleted to true
4244 foreach ($this->_params
as $values) {
4245 $name = CRM_Utils_Array
::value(0, $values);
4246 $op = CRM_Utils_Array
::value(1, $values);
4247 $value = CRM_Utils_Array
::value(2, $values);
4248 if ($name == 'contact_id' and $op == '=') {
4249 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4250 $onlyDeleted = TRUE;
4255 $this->generatePermissionClause($onlyDeleted, $count);
4257 // building the query string
4260 if (isset($this->_groupByComponentClause
)) {
4261 $groupBy = $this->_groupByComponentClause
;
4263 elseif ($this->_useGroupBy
) {
4264 $groupBy = ' GROUP BY contact_a.id';
4267 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4268 $groupBy = 'GROUP BY civicrm_activity.id ';
4271 $order = $orderBy = $limit = '';
4273 $config = CRM_Core_Config
::singleton();
4274 if ($config->includeOrderByClause ||
4275 isset($this->_distinctComponentClause
)
4278 if (is_string($sort)) {
4282 $orderBy = trim($sort->orderBy());
4284 if (!empty($orderBy)) {
4285 // this is special case while searching for
4286 // changelog CRM-1718
4287 if (preg_match('/sort_name/i', $orderBy)) {
4288 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4291 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
4292 $order = " ORDER BY $orderBy";
4295 $sortOrder = CRM_Utils_Type
::escape($sortOrder, 'String');
4296 $order .= " $sortOrder";
4299 // always add contact_a.id to the ORDER clause
4300 // so the order is deterministic
4301 if (strpos('contact_a.id', $order) === FALSE) {
4302 $order .= ", contact_a.id";
4306 elseif ($sortByChar) {
4307 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4310 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4314 // hack for order clause
4316 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4317 $fieldOrder = explode(' ', $fieldStr);
4318 $field = $fieldOrder[0];
4324 $this->_whereTables
["civicrm_address"] = 1;
4325 $order = str_replace($field, "civicrm_address.{$field}", $order);
4329 case 'state_province':
4330 $this->_whereTables
["civicrm_{$field}"] = 1;
4331 $order = str_replace($field, "civicrm_{$field}.name", $order);
4335 $this->_whereTables
["civicrm_email"] = 1;
4336 $order = str_replace($field, "civicrm_email.{$field}", $order);
4339 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4340 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4344 if ($rowCount > 0 && $offset >= 0) {
4345 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4346 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4347 $limit = " LIMIT $offset, $rowCount ";
4351 // note : this modifies _fromClause and _simpleFromClause
4352 $this->includePseudoFieldsJoin($sort);
4354 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts);
4356 if(!empty($this->_permissionWhereClause
)){
4357 if (empty($where)) {
4358 $where = "WHERE $this->_permissionWhereClause";
4361 $where = "$where AND $this->_permissionWhereClause";
4365 if ($additionalWhereClause) {
4366 $where = $where . ' AND ' . $additionalWhereClause;
4369 //additional from clause should be w/ proper joins.
4370 if ($additionalFromClause) {
4371 $from .= "\n" . $additionalFromClause;
4374 // if we are doing a transform, do it here
4375 // use the $from, $where and $having to get the contact ID
4376 if ($this->_displayRelationshipType
) {
4377 $this->filterRelatedContacts($from, $where, $having);
4380 if ($skipOrderAndLimit) {
4381 $query = "$select $from $where $having $groupBy";
4384 $query = "$select $from $where $having $groupBy $order $limit";
4392 return CRM_Core_DAO
::singleValueQuery($query);
4395 $dao = CRM_Core_DAO
::executeQuery($query);
4396 if ($groupContacts) {
4398 while ($dao->fetch()) {
4401 return implode(',', $ids);
4408 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4410 * @param string $cacheKey
4411 * @param int $offset
4412 * @param int $rowCount
4413 * @param bool $includeContactIds
4414 * @return CRM_Core_DAO
4416 function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4417 $this->_includeContactIds
= $includeContactIds;
4418 list($select, $from, $where) = $this->query();
4419 $from = " FROM civicrm_prevnext_cache pnc INNER JOIN civicrm_contact contact_a ON contact_a.id = pnc.entity_id1 AND pnc.cacheKey = '$cacheKey' " . substr($from, 31);
4420 $order = " ORDER BY pnc.id";
4421 $groupBy = " GROUP BY contact_a.id";
4422 $limit = " LIMIT $offset, $rowCount";
4423 $query = "$select $from $where $groupBy $order $limit";
4425 return CRM_Core_DAO
::executeQuery($query);
4429 * Populate $this->_permissionWhereClause with permission related clause and update other
4430 * query related properties.
4432 * Function calls ACL permission class and hooks to filter the query appropriately
4434 * Note that these 2 params were in the code when extracted from another function
4435 * and a second round extraction would be to make them properties of the class
4437 * @param bool $onlyDeleted Only get deleted contacts
4438 * @param bool $count Return Count only
4442 function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4443 if (!$this->_skipPermission
) {
4444 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4445 CRM_Core_Permission
::VIEW
,
4447 $this->_whereTables
,
4450 $this->_skipDeleteClause
4453 // regenerate fromClause since permission might have added tables
4454 if ($this->_permissionWhereClause
) {
4455 //fix for row count in qill (in contribute/membership find)
4457 $this->_useDistinct
= TRUE;
4459 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4460 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4464 // add delete clause if needed even if we are skipping permission
4466 if (!$this->_skipDeleteClause
) {
4467 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4468 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4472 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4478 function setSkipPermission($val) {
4479 $this->_skipPermission
= $val;
4482 function &summaryContribution($context = NULL) {
4483 list($select, $from, $where, $having) = $this->query(TRUE);
4487 SELECT COUNT( civicrm_contribution.total_amount ) as total_count,
4488 SUM( civicrm_contribution.total_amount ) as total_amount,
4489 AVG( civicrm_contribution.total_amount ) as total_avg,
4490 civicrm_contribution.currency as currency";
4492 // make sure contribution is completed - CRM-4989
4493 $where .= " AND civicrm_contribution.contribution_status_id = 1 ";
4494 if ($context == 'search') {
4495 $where .= " AND contact_a.is_deleted = 0 ";
4499 $summary['total'] = array();
4500 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4502 $query = "$select $from $where GROUP BY currency";
4505 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4507 $summary['total']['count'] = 0;
4508 $summary['total']['amount'] = $summary['total']['avg'] = array();
4509 while ($dao->fetch()) {
4510 $summary['total']['count'] +
= $dao->total_count
;
4511 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4512 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4514 if (!empty($summary['total']['amount'])) {
4515 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4516 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4519 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4524 SELECT COUNT( civicrm_contribution.total_amount ) as cancel_count,
4525 SUM( civicrm_contribution.total_amount ) as cancel_amount,
4526 AVG( civicrm_contribution.total_amount ) as cancel_avg,
4527 civicrm_contribution.currency as currency";
4529 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4530 if ($context == 'search') {
4531 $where .= " AND contact_a.is_deleted = 0 ";
4534 $query = "$select $from $where GROUP BY currency";
4535 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4538 if ($dao->fetch()) {
4539 $summary['cancel']['count'] = $dao->cancel_count
;
4540 $summary['cancel']['amount'] = $dao->cancel_amount
;
4541 $summary['cancel']['avg'] = $dao->cancel_avg
;
4545 $summary['cancel']['count'] = 0;
4546 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4547 while ($dao->fetch()) {
4548 $summary['cancel']['count'] +
= $dao->cancel_count
;
4549 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4550 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4552 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4553 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
4560 * getter for the qill object
4566 return $this->_qill
;
4570 * default set of return default hier return properties
4575 static function &defaultHierReturnProperties() {
4576 if (!isset(self
::$_defaultHierReturnProperties)) {
4577 self
::$_defaultHierReturnProperties = array(
4580 'legal_identifier' => 1,
4581 'external_identifier' => 1,
4582 'contact_type' => 1,
4583 'contact_sub_type' => 1,
4585 'display_name' => 1,
4592 'email_greeting' => 1,
4593 'postal_greeting' => 1,
4597 'preferred_communication_method' => 1,
4598 'do_not_phone' => 1,
4599 'do_not_email' => 1,
4602 'do_not_trade' => 1,
4605 '1' => array('location_type' => 1,
4606 'street_address' => 1,
4608 'state_province' => 1,
4610 'postal_code_suffix' => 1,
4613 'phone-Mobile' => 1,
4626 'location_type' => 1,
4627 'street_address' => 1,
4629 'state_province' => 1,
4631 'postal_code_suffix' => 1,
4634 'phone-Mobile' => 1,
4648 return self
::$_defaultHierReturnProperties;
4651 function dateQueryBuilder(
4652 &$values, $tableName, $fieldName,
4653 $dbFieldName, $fieldTitle,
4654 $appendTimeStamp = TRUE
4656 list($name, $op, $value, $grouping, $wildcard) = $values;
4662 if ($name == "{$fieldName}_low" ||
4663 $name == "{$fieldName}_high"
4665 if (isset($this->_rangeCache
[$fieldName])) {
4668 $this->_rangeCache
[$fieldName] = 1;
4670 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4672 if ($name == $fieldName . '_low') {
4674 $firstPhrase = ts('greater than or equal to');
4675 $firstDate = CRM_Utils_Date
::processDate($value);
4677 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4678 if (!empty($secondValues) && $secondValues[2]) {
4680 $secondPhrase = ts('less than or equal to');
4681 $secondValue = $secondValues[2];
4683 if ($appendTimeStamp && strlen($secondValue) == 10) {
4684 $secondValue .= ' 23:59:59';
4686 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4689 elseif ($name == $fieldName . '_high') {
4691 $firstPhrase = ts('less than or equal to');
4693 if ($appendTimeStamp && strlen($value) == 10) {
4694 $value .= ' 23:59:59';
4696 $firstDate = CRM_Utils_Date
::processDate($value);
4698 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4699 if (!empty($secondValues) && $secondValues[2]) {
4701 $secondPhrase = ts('greater than or equal to');
4702 $secondValue = $secondValues[2];
4703 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4707 if (!$appendTimeStamp) {
4708 $firstDate = substr($firstDate, 0, 8);
4710 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
4713 if (!$appendTimeStamp) {
4714 $secondDate = substr($secondDate, 0, 8);
4716 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
4719 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4721 $this->_where
[$grouping][] = "
4722 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
4723 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
4725 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
4728 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
4729 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
4733 if ($name == $fieldName) {
4737 $date = CRM_Utils_Date
::processDate($value);
4739 if (!$appendTimeStamp) {
4740 $date = substr($date, 0, 8);
4743 $format = CRM_Utils_Date
::customFormat($date);
4746 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'";
4749 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op";
4751 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4752 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$format\"";
4756 $tableName == 'civicrm_log' &&
4757 $fieldTitle == ts('Added Date')
4759 //CRM-6903 --hack to check modified date of first record.
4760 //as added date means first modified date of object.
4761 $addedDateQuery = 'select id from civicrm_log group by entity_id order by id';
4762 $this->_where
[$grouping][] = "civicrm_log.id IN ( {$addedDateQuery} )";
4766 function numberRangeBuilder(&$values,
4767 $tableName, $fieldName,
4768 $dbFieldName, $fieldTitle,
4771 list($name, $op, $value, $grouping, $wildcard) = $values;
4773 if ($name == "{$fieldName}_low" ||
4774 $name == "{$fieldName}_high"
4776 if (isset($this->_rangeCache
[$fieldName])) {
4779 $this->_rangeCache
[$fieldName] = 1;
4781 $secondOP = $secondPhrase = $secondValue = NULL;
4783 if ($name == "{$fieldName}_low") {
4785 $firstPhrase = ts('greater than');
4787 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4788 if (!empty($secondValues)) {
4790 $secondPhrase = ts('less than');
4791 $secondValue = $secondValues[2];
4796 $firstPhrase = ts('less than');
4798 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4799 if (!empty($secondValues)) {
4801 $secondPhrase = ts('greater than');
4802 $secondValue = $secondValues[2];
4807 $this->_where
[$grouping][] = "
4808 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
4809 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
4811 $displayValue = $options ?
$options[$value] : $value;
4812 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
4814 $this->_qill
[$grouping][] =
4815 "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
4818 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
4819 $displayValue = $options ?
$options[$value] : $value;
4820 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
4822 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4827 if ($name == $fieldName) {
4831 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
4833 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4834 $displayValue = $options ?
$options[$value] : $value;
4835 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
4842 * Given the field name, operator, value & its data type
4843 * builds the where Clause for the query
4844 * used for handling 'IS NULL'/'IS NOT NULL' operators
4846 * @param string $field fieldname
4847 * @param string $op operator
4848 * @param string $value value
4849 * @param string $dataType data type of the field
4851 * @return where clause for the query
4854 static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
4856 $clause = "$field $op";
4864 $clause = " ( $field IS NULL OR $field = '' ) ";
4867 case 'IS NOT EMPTY':
4868 $clause = " ( $field IS NOT NULL AND $field <> '' ) ";
4873 if (isset($dataType)) {
4874 if (is_array($value)) {
4878 $value = CRM_Utils_Type
::escape($value, "String");
4879 $values = explode(',', CRM_Utils_Array
::value(0, explode(')', CRM_Utils_Array
::value(1, explode('(', $value)))));
4881 // supporting multiple values in IN clause
4883 foreach ($values as $v) {
4885 $val[] = "'" . CRM_Utils_Type
::escape($v, $dataType) . "'";
4887 $value = "(" . implode($val, ",") . ")";
4889 return "$clause $value";
4892 if (empty($dataType)) {
4893 $dataType = 'String';
4896 $value = CRM_Utils_Type
::escape($value, $dataType);
4897 // if we dont have a dataType we should assume
4898 if ($dataType == 'String' ||
$dataType == 'Text') {
4899 $value = "'" . strtolower($value) . "'";
4901 return "$clause $value";
4905 function openedSearchPanes($reset = FALSE) {
4906 if (!$reset ||
empty($this->_whereTables
)) {
4907 return self
::$_openedPanes;
4910 // pane name to table mapper
4911 $panesMapper = array(
4912 ts('Contributions') => 'civicrm_contribution',
4913 ts('Memberships') => 'civicrm_membership',
4914 ts('Events') => 'civicrm_participant',
4915 ts('Relationships') => 'civicrm_relationship',
4916 ts('Activities') => 'civicrm_activity',
4917 ts('Pledges') => 'civicrm_pledge',
4918 ts('Cases') => 'civicrm_case',
4919 ts('Grants') => 'civicrm_grant',
4920 ts('Address Fields') => 'civicrm_address',
4921 ts('Notes') => 'civicrm_note',
4922 ts('Change Log') => 'civicrm_log',
4923 ts('Mailings') => 'civicrm_mailing_event_queue',
4925 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
4927 foreach (array_keys($this->_whereTables
) as $table) {
4928 if ($panName = array_search($table, $panesMapper)) {
4929 self
::$_openedPanes[$panName] = TRUE;
4933 return self
::$_openedPanes;
4936 function setOperator($operator) {
4937 $validOperators = array('AND', 'OR');
4938 if (!in_array($operator, $validOperators)) {
4941 $this->_operator
= $operator;
4944 function getOperator() {
4945 return $this->_operator
;
4948 function filterRelatedContacts(&$from, &$where, &$having) {
4949 static $_rTypeProcessed = NULL;
4950 static $_rTypeFrom = NULL;
4951 static $_rTypeWhere = NULL;
4953 if (!$_rTypeProcessed) {
4954 $_rTypeProcessed = TRUE;
4956 // create temp table with contact ids
4957 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
4958 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
4959 CRM_Core_DAO
::executeQuery($sql);
4962 REPLACE INTO $tableName ( contact_id )
4968 CRM_Core_DAO
::executeQuery($sql);
4970 $qillMessage = ts('Contacts with a Relationship Type of: ');
4971 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
4973 if (is_numeric($this->_displayRelationshipType
)) {
4974 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
4976 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
4977 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
4980 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
4981 AND displayRelType.is_active = 1
4985 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
4986 if ($dirOne == 'a') {
4987 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
4989 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
4990 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
4994 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
4996 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
4997 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5001 WHERE displayRelType.relationship_type_id = $relType
5002 AND displayRelType.is_active = 1
5005 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5008 if (strpos($from, $_rTypeFrom) === FALSE) {
5009 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5010 // this happens when we have an event_type in the quert (CRM-7969)
5011 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5012 $from .= $_rTypeFrom;
5013 $where = $_rTypeWhere;
5019 static function caseImportant( $op ) {
5021 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5024 static function componentPresent( &$returnProperties, $prefix ) {
5025 foreach ($returnProperties as $name => $dontCare ) {
5026 if (substr($name, 0, strlen($prefix)) == $prefix) {
5034 * Builds the necessary structures for all fields that are similar to option value lookups
5036 * @param $name string the name of the field
5037 * @param $op string the sql operator, this function should handle ALL SQL operators
5038 * @param $value any string / integer / array depends on the operator and whos calling the query builder
5039 * @param $grouping int the index where to place the where clause
5040 * @param $selectValues
5041 * @param $field array an array that contains various properties of the field identified by $name
5042 * @param $label string The label for this field element
5043 * @param $dataType string The data type for this element
5045 * @param bool $useIDsOnly
5047 * @internal param array $selectValue the key value pairs for this element. This allows us to use this function for things besides option-value pairs
5048 * @return void adds the where clause and qill to the query object
5050 function optionValueQuery(
5058 $dataType = 'String',
5062 if (!empty($selectValues)) {
5063 $qill = $selectValues[$value];
5069 $pseudoFields = array('email_greeting', 'postal_greeting', 'addressee', 'gender_id', 'prefix_id', 'suffix_id');
5071 if (is_numeric($value)) {
5072 $qill = $selectValues[(int ) $value];
5074 elseif ($op == 'IN' ||
$op == 'NOT IN') {
5075 $values = self
::parseSearchBuilderString($value);
5076 if (is_array($values)) {
5078 $newValues = array();
5079 foreach ($values as $v) {
5080 $intVals[] = (int) $v;
5081 $newValues[] = $selectValues[(int ) $v];
5084 $value = (in_array($name, $pseudoFields)) ?
$intVals : $newValues;
5085 $qill = implode(', ', $newValues);
5088 elseif (!array_key_exists($value, $selectValues)) {
5089 // its a string, lets get the int value
5090 $value = array_search($value, $selectValues);
5093 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5094 if ($tableName == 'civicrm_contact') {
5095 $wc = "contact_a.$fieldName";
5099 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5102 if (in_array($name, $pseudoFields)) {
5103 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id'))) {
5104 $wc = "contact_a.{$name}_id";
5106 $dataType = 'Positive';
5107 $value = (!$value) ?
0 : $value;
5110 $this->_qill
[$grouping][] = $label . " $op '$qill'";
5111 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' ||
$op == 'RLIKE')) ?
'=' : $op;
5112 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5116 * function to check and explode a user defined numeric string into an array
5117 * this was the protocol used by search builder in the old old days before we had
5118 * super nice js widgets to do the hard work
5120 * @param the $string
5121 * @param string $dataType the dataType we should check for the values, default integer
5123 * @return FALSE if string does not match the patter
5124 * array of numeric values if string does match the pattern
5127 static function parseSearchBuilderString($string, $dataType = 'Integer') {
5128 $string = trim($string);
5129 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5133 $string = substr($string, 1, -1);
5134 $values = explode(',', $string);
5135 if (empty($values)) {
5139 $returnValues = array();
5140 foreach ($values as $v) {
5141 if ($dataType == 'Integer' && ! is_numeric($v)) {
5144 else if ($dataType == 'String' && ! is_string($v)) {
5147 $returnValues[] = trim($v);
5150 if (empty($returnValues)) {
5154 return $returnValues;
5158 * convert the pseudo constants id's to their names
5160 * @param reference parameter $dao
5161 * @param bool $return
5165 function convertToPseudoNames(&$dao, $return = FALSE) {
5166 if (empty($this->_pseudoConstantsSelect
)) {
5170 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5171 if (CRM_Utils_Array
::value('sorting', $this->_pseudoConstantsSelect
[$key])) {
5175 if (property_exists($dao, $value['idCol'])) {
5176 $val = $dao->$value['idCol'];
5178 if (CRM_Utils_System
::isNull($val)) {
5181 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5183 $idColumn = "{$key}_id";
5184 $dao->$idColumn = $val;
5185 $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5187 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5188 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5191 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5192 $dao->$key = $labels[$val];
5195 // return converted values in array format
5197 if (strpos($key, '-') !== FALSE) {
5198 $keyVal = explode('-', $key);
5199 $current = &$values;
5200 $lastElement = array_pop($keyVal);
5201 foreach ($keyVal as $v) {
5202 if (!array_key_exists($v, $current)) {
5203 $current[$v] = array();
5205 $current = &$current[$v];
5207 $current[$lastElement] = $dao->$key;
5210 $values[$key] = $dao->$key;
5219 * include pseudo fields LEFT JOIN
5220 * @param $sort can be a object or string
5224 function includePseudoFieldsJoin($sort) {
5225 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5228 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5231 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5232 if (CRM_Utils_Array
::value('table', $value)) {
5233 $regex = "/({$value['table']}\.|{$name})/";
5234 if (preg_match($regex, $sort)) {
5235 $this->_elemnt
[$value['element']] = 1;
5236 $this->_select
[$value['element']] = $value['select'];
5237 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5238 $present[$value['table']] = $value['join'];
5242 $presentSimpleFrom = $present;
5244 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5245 array_key_exists('civicrm_country', $presentSimpleFrom)) {
5246 unset($presentSimpleFrom['civicrm_country']);
5248 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5249 array_key_exists('civicrm_country', $present)) {
5250 unset($present['civicrm_country']);
5253 $presentClause = $presentSimpleFromClause = NULL;
5254 if (!empty($present)) {
5255 $presentClause = implode(' ', $present);
5257 if (!empty($presentSimpleFrom)) {
5258 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5261 $this->_fromClause
= $this->_fromClause
. $presentClause;
5262 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5264 return array($presentClause, $presentSimpleFromClause);