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 if ($name == 'communication_style_id') {
766 $this->_pseudoConstantsSelect
['communication_style'] = array('pseudoField' => 'communication_style_id', 'idCol' => "communication_style_id", 'bao' => 'CRM_Contact_BAO_Contact');
768 $this->_select
[$name] = "contact_a.{$fieldName} as `$name`";
771 elseif (in_array($tName, array('state_province', 'country', 'county'))) {
772 $this->_pseudoConstantsSelect
[$pf]['select'] = "{$field['where']} as `$name`";
773 $this->_pseudoConstantsSelect
[$pf]['element'] = $name;
774 if ($tName == 'state_province') {
775 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
776 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
780 $this->_select
[$name] = "{$field['where']} as `$name`";
782 if (!in_array($tName, array('state_province', 'country', 'county'))) {
783 $this->_element
[$name] = 1;
788 elseif ($name === 'tags') {
789 $this->_useGroupBy
= TRUE;
790 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
791 $this->_element
[$name] = 1;
792 $this->_tables
['civicrm_tag'] = 1;
793 $this->_tables
['civicrm_entity_tag'] = 1;
795 elseif ($name === 'groups') {
796 $this->_useGroupBy
= TRUE;
797 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
798 $this->_element
[$name] = 1;
799 $this->_tables
['civicrm_group'] = 1;
801 elseif ($name === 'notes') {
802 // if note field is subject then return subject else body of the note
803 $noteColumn = 'note';
804 if (isset($noteField) && $noteField == 'note_subject') {
805 $noteColumn = 'subject';
808 $this->_useGroupBy
= TRUE;
809 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
810 $this->_element
[$name] = 1;
811 $this->_tables
['civicrm_note'] = 1;
813 elseif ($name === 'current_employer') {
814 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
815 $this->_element
[$name] = 1;
820 CRM_Utils_Array
::value('is_search_range', $field)
822 // this is a custom field with range search enabled, so we better check for two/from values
823 if (CRM_Utils_Array
::value($name . '_from', $this->_paramLookup
)) {
824 if (!array_key_exists($cfID, $this->_cfIDs
)) {
825 $this->_cfIDs
[$cfID] = array();
827 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
828 // search in the cdID array for the same grouping
830 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
831 if ($c[3] == $p[3]) {
832 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
837 $p[2] = array('from' => $p[2]);
838 $this->_cfIDs
[$cfID][] = $p;
842 if (CRM_Utils_Array
::value($name . '_to', $this->_paramLookup
)) {
843 if (!array_key_exists($cfID, $this->_cfIDs
)) {
844 $this->_cfIDs
[$cfID] = array();
846 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
847 // search in the cdID array for the same grouping
849 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
850 if ($c[4] == $p[4]) {
851 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
856 $p[2] = array('to' => $p[2]);
857 $this->_cfIDs
[$cfID][] = $p;
864 // add location as hierarchical elements
865 $this->addHierarchicalElements();
867 // add multiple field like website
868 $this->addMultipleElements();
871 CRM_Core_Component
::alterQuery($this, 'select');
873 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
875 if (!empty($this->_cfIDs
)) {
876 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE);
877 $this->_customQuery
->query();
878 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
879 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
880 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
881 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
882 $this->_options
= $this->_customQuery
->_options
;
887 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
893 function addHierarchicalElements() {
894 if (!CRM_Utils_Array
::value('location', $this->_returnProperties
)) {
897 if (!is_array($this->_returnProperties
['location'])) {
901 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
902 $processed = array();
905 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
906 $addressCustomFieldIds = array();
908 foreach ($this->_returnProperties
['location'] as $name => $elements) {
909 $lCond = self
::getPrimaryCondition($name);
912 $locationTypeId = array_search($name, $locationTypes);
913 if ($locationTypeId === FALSE) {
916 $lCond = "location_type_id = $locationTypeId";
917 $this->_useDistinct
= TRUE;
919 //commented for CRM-3256
920 $this->_useGroupBy
= TRUE;
923 $name = str_replace(' ', '_', $name);
925 $tName = "$name-location_type";
926 $ltName = "`$name-location_type`";
927 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
928 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
929 $this->_element
["{$tName}_id"] = 1;
930 $this->_element
["{$tName}"] = 1;
932 $locationTypeName = $tName;
933 $locationTypeJoin = array();
937 foreach ($elements as $elementFullName => $dontCare) {
939 $elementName = $elementCmpName = $elementFullName;
941 if (substr($elementCmpName, 0, 5) == 'phone') {
942 $elementCmpName = 'phone';
945 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
946 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
947 $addressCustomFieldIds[$cfID][$name] = 1;
950 //add address table only once
951 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
953 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
955 $tName = "$name-address";
956 $aName = "`$name-address`";
957 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
958 $this->_element
["{$tName}_id"] = 1;
959 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
960 $this->_tables
[$tName] = $addressJoin;
961 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
962 $processed[$aName] = 1;
966 $cond = $elementType = '';
967 if (strpos($elementName, '-') !== FALSE) {
968 // this is either phone, email or IM
969 list($elementName, $elementType) = explode('-', $elementName);
972 if (($elementName != 'phone') && ($elementName != 'im')) {
973 $cond = self
::getPrimaryCondition($elementType);
975 // CRM-13011 : If location type is primary, do not restrict search to the phone
976 // type id - we want the primary phone, regardless of what type it is.
977 // Otherwise, restrict to the specified phone type for the given field.
978 if ((!$cond) && ($elementName == 'phone') && $elements['location_type'] != 'Primary') {
979 $cond = "phone_type_id = '$elementType'";
981 elseif ((!$cond) && ($elementName == 'im')) {
982 // IM service provider id, CRM-3140
983 $cond = "provider_id = '$elementType'";
985 $elementType = '-' . $elementType;
988 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
990 // hack for profile, add location id
993 // fix for CRM-882( to handle phone types )
994 !is_numeric($elementType)
996 if (is_numeric($name)) {
997 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1000 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1003 elseif (is_numeric($name)) {
1004 //this for phone type to work
1005 if (in_array($elementName, array('phone', 'phone_ext'))) {
1006 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1009 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1013 //this is for phone type to work for profile edit
1014 if (in_array($elementName, array('phone', 'phone_ext'))) {
1015 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1018 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1023 // Check if there is a value, if so also add to where Clause
1025 if ($this->_params
) {
1027 if (isset($locationTypeId)) {
1028 $nm .= "-$locationTypeId";
1030 if (!is_numeric($elementType)) {
1031 $nm .= "$elementType";
1034 foreach ($this->_params
as $id => $values) {
1035 if ($values[0] == $nm ||
1036 (in_array($elementName, array('phone', 'im'))
1037 && (strpos($values[0], $nm) !== FALSE)
1047 if ($field && isset($field['where'])) {
1048 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1049 $pf = substr($tableName, 8);
1050 $tName = $name . '-' . $pf . $elementType;
1051 if (isset($tableName)) {
1052 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1053 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1056 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1059 $this->_element
["{$tName}_id"] = 1;
1060 if (substr($tName, -15) == '-state_province') {
1061 // FIXME: hack to fix CRM-1900
1062 $a = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1066 if (substr_count($a, 'state_province_name') > 0) {
1067 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1068 array('pseudoField' => '{$pf}_id', 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1069 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1072 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1073 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id");
1074 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1078 if (substr($elementFullName, 0, 2) == 'im') {
1079 $provider = "{$name}-{$elementFullName}-provider_id";
1080 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1081 $this->_element
[$provider] = 1;
1083 if ($pf == 'country' ||
$pf == 'county') {
1084 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array('pseudoField' => "{$pf}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1085 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1088 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1092 if (in_array($pf, array('state_province', 'country', 'county'))) {
1093 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1096 $this->_element
["{$name}-{$elementFullName}"] = 1;
1099 if (!CRM_Utils_Array
::value("`$tName`", $processed)) {
1100 $processed["`$tName`"] = 1;
1101 $newName = $tableName . '_' . $index;
1102 switch ($tableName) {
1103 case 'civicrm_phone':
1104 case 'civicrm_email':
1106 case 'civicrm_openid':
1108 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id AND `$tName`.$lCond";
1109 // this special case to add phone type
1111 $phoneTypeCondition = " AND `$tName`.$cond ";
1112 //gross hack to pickup corrupted data also, CRM-7603
1113 if (strpos($cond, 'phone_type_id') !== FALSE) {
1114 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1116 $this->_tables
[$tName] .= $phoneTypeCondition;
1119 //build locationType join
1120 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1123 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1127 case 'civicrm_state_province':
1128 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1129 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1130 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1132 $this->_whereTables
["{$name}-address"] = $addressJoin;
1136 case 'civicrm_country':
1137 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1138 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1139 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1141 $this->_whereTables
["{$name}-address"] = $addressJoin;
1145 case 'civicrm_county':
1146 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1147 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1148 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1150 $this->_whereTables
["{$name}-address"] = $addressJoin;
1156 $this->_whereTables
["{$name}-address"] = $addressJoin;
1165 // add location type join
1166 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1167 $this->_tables
[$locationTypeName] = $ltypeJoin;
1169 // table should be present in $this->_whereTables,
1170 // to add its condition in location type join, CRM-3939.
1171 if ($addWhereCount) {
1172 $locClause = array();
1173 foreach ($this->_whereTables
as $tableName => $clause) {
1174 if (CRM_Utils_Array
::value($tableName, $locationTypeJoin)) {
1175 $locClause[] = $locationTypeJoin[$tableName];
1179 if (!empty($locClause)) {
1180 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1185 if (!empty($addressCustomFieldIds)) {
1186 $cfIDs = $addressCustomFieldIds;
1187 $customQuery = new CRM_Core_BAO_CustomQuery($cfIDs);
1188 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1189 foreach ($locTypeName as $name => $dnc) {
1190 $fieldName = "$name-custom_{$cfID}";
1191 $tName = "$name-address-custom-{$cfID}";
1192 $aName = "`$name-address-custom-{$cfID}`";
1193 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1194 $this->_element
["{$tName}_id"] = 1;
1195 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1196 $this->_element
[$fieldName] = 1;
1197 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1204 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
1210 function addMultipleElements() {
1211 if (!CRM_Utils_Array
::value('website', $this->_returnProperties
)) {
1214 if (!is_array($this->_returnProperties
['website'])) {
1218 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1219 foreach ($elements as $elementFullName => $dontCare) {
1220 $tName = "website-{$key}-{$elementFullName}";
1221 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1222 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1223 $this->_element
["{$tName}_id"] = 1;
1224 $this->_element
["{$tName}"] = 1;
1226 $type = "website-{$key}-website_type_id";
1227 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1228 $this->_element
[$type] = 1;
1229 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id )";
1235 * generate the query based on what type of query we need
1237 * @param boolean $count
1238 * @param boolean $sortByChar
1239 * @param boolean $groupContacts
1241 * @return the sql string for that query (this will most likely
1245 function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE) {
1247 if (isset($this->_distinctComponentClause
)) {
1248 // we add distinct to get the right count for components
1249 // for the more complex result set, we use GROUP BY the same id
1251 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1254 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1256 $from = $this->_simpleFromClause
;
1257 if ($this->_useDistinct
) {
1258 $this->_useGroupBy
= TRUE;
1261 elseif ($sortByChar) {
1262 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1263 $from = $this->_simpleFromClause
;
1265 elseif ($groupContacts) {
1266 $select = 'SELECT contact_a.id as id';
1267 if ($this->_useDistinct
) {
1268 $this->_useGroupBy
= TRUE;
1270 $from = $this->_simpleFromClause
;
1273 if (CRM_Utils_Array
::value('group', $this->_paramLookup
)) {
1274 // make sure there is only one element
1275 // this is used when we are running under smog and need to know
1276 // how the contact was added (CRM-1203)
1277 if ((count($this->_paramLookup
['group']) == 1) &&
1278 (count($this->_paramLookup
['group'][0][2]) == 1)
1280 $groups = array_keys($this->_paramLookup
['group'][0][2]);
1281 $groupId = $groups[0];
1283 //check if group is saved search
1284 $group = new CRM_Contact_BAO_Group();
1285 $group->id
= $groupId;
1288 if (!isset($group->saved_search_id
)) {
1289 $tbName = "`civicrm_group_contact-{$groupId}`";
1290 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1291 $this->_element
['group_contact_id'] = 1;
1292 $this->_select
['status'] = "$tbName.status as status";
1293 $this->_element
['status'] = 1;
1296 $this->_useGroupBy
= TRUE;
1298 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1299 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1301 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1302 $this->_useDistinct
= FALSE;
1303 $this->_useGroupBy
= TRUE;
1307 $select = "SELECT ";
1308 if (isset($this->_distinctComponentClause
)) {
1309 $select .= "{$this->_distinctComponentClause}, ";
1311 $select .= implode(', ', $this->_select
);
1312 $from = $this->_fromClause
;
1316 if (!empty($this->_whereClause
)) {
1317 $where = "WHERE {$this->_whereClause}";
1321 if (!empty($this->_having
)) {
1322 foreach ($this->_having
as $havingsets) {
1323 foreach ($havingsets as $havingset) {
1324 $havingvalue[] = $havingset;
1327 $having = ' HAVING ' . implode(' AND ', $havingvalue);
1330 // if we are doing a transform, do it here
1331 // use the $from, $where and $having to get the contact ID
1332 if ($this->_displayRelationshipType
) {
1333 $this->filterRelatedContacts($from, $where, $having);
1336 return array($select, $from, $where, $having);
1339 function &getWhereValues($name, $grouping) {
1341 foreach ($this->_params
as $values) {
1342 if ($values[0] == $name && $values[3] == $grouping) {
1350 static function fixDateValues($relative, &$from, &$to) {
1352 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1356 static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE) {
1358 if (empty($formValues)) {
1362 foreach ($formValues as $id => $values) {
1363 if ($id == 'privacy') {
1364 if (is_array($formValues['privacy'])) {
1365 $op = CRM_Utils_Array
::value('do_not_toggle', $formValues['privacy']) ?
'=' : '!=';
1366 foreach ($formValues['privacy'] as $key => $value) {
1368 $params[] = array($key, $op, $value, 0, 0);
1373 elseif ($id == 'email_on_hold') {
1374 if ($formValues['email_on_hold']['on_hold']) {
1375 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1378 elseif (preg_match('/_date_relative$/', $id) ||
1379 $id == 'event_relative' ||
1380 $id == 'case_from_relative' ||
1381 $id == 'case_to_relative'
1383 if ($id == 'event_relative') {
1384 $fromRange = 'event_start_date_low';
1385 $toRange = 'event_end_date_high';
1387 else if ($id == 'case_from_relative') {
1388 $fromRange = 'case_from_start_date_low';
1389 $toRange = 'case_from_start_date_high';
1391 else if ($id == 'case_to_relative') {
1392 $fromRange = 'case_to_end_date_low';
1393 $toRange = 'case_to_end_date_high';
1396 $dateComponent = explode('_date_relative', $id);
1397 $fromRange = "{$dateComponent[0]}_date_low";
1398 $toRange = "{$dateComponent[0]}_date_high";
1401 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1402 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1407 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals);
1412 $params[] = $values;
1418 static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE) {
1419 // skip a few search variables
1420 static $skipWhere = NULL;
1421 static $arrayValues = NULL;
1422 static $likeNames = NULL;
1425 if (CRM_Utils_System
::isNull($values)) {
1431 'task', 'radio_ts', 'uf_group_id',
1432 'component_mode', 'qfKey', 'operator',
1433 'display_relationship_type',
1437 if (in_array($id, $skipWhere) ||
1438 substr($id, 0, 4) == '_qf_' ||
1439 substr($id, 0, 7) == 'hidden_'
1445 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1448 // email comes in via advanced search
1449 // so use wildcard always
1450 if ($id == 'email') {
1454 if (!$useEquals && in_array($id, $likeNames)) {
1455 $result = array($id, 'LIKE', $values, 0, 1);
1457 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1458 $result = array($id, 'LIKE', $values, 0, 0);
1460 elseif ($id == 'group') {
1461 if (is_array($values)) {
1462 foreach ($values as $groupIds => $val) {
1464 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1465 if (strlen($matches[1]) > 0) {
1466 $values[$matches[1]] = 1;
1467 unset($values[$groupIds]);
1473 $groupIds = explode(',', $values);
1475 foreach ($groupIds as $groupId) {
1476 $values[$groupId] = 1;
1480 $result = array($id, 'IN', $values, 0, 0);
1482 elseif ($id == 'contact_tags' ||
$id == 'tag') {
1483 if (!is_array($values)) {
1484 $tagIds = explode(',', $values);
1486 foreach ($tagIds as $tagId) {
1487 $values[$tagId] = 1;
1490 $result = array($id, 'IN', $values, 0, 0);
1493 $result = array($id, '=', $values, 0, $wildcard);
1499 function whereClauseSingle(&$values) {
1500 // do not process custom fields or prefixed contact ids or component params
1501 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1502 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1503 (substr($values[0], 0, 13) == 'contribution_') ||
1504 (substr($values[0], 0, 6) == 'event_') ||
1505 (substr($values[0], 0, 12) == 'participant_') ||
1506 (substr($values[0], 0, 7) == 'member_') ||
1507 (substr($values[0], 0, 6) == 'grant_') ||
1508 (substr($values[0], 0, 7) == 'pledge_') ||
1509 (substr($values[0], 0, 5) == 'case_') ||
1510 (substr($values[0], 0, 10) == 'financial_') ||
1511 (substr($values[0], 0, 11) == 'membership_')
1516 // skip for hook injected fields / params
1517 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1518 if (array_key_exists($values[0], $extFields)) {
1522 switch ($values[0]) {
1523 case 'deleted_contacts':
1524 $this->deletedContacts($values);
1527 case 'contact_type':
1528 $this->contactType($values);
1531 case 'contact_sub_type':
1532 $this->contactSubType($values);
1536 $this->group($values);
1540 // so we resolve this into a list of groups & proceed as if they had been
1542 list($name, $op, $value, $grouping, $wildcard) = $values;
1543 $values[0] = 'group';
1545 $this->_paramLookup
['group'][0][0] ='group';
1546 $this->_paramLookup
['group'][0][1] = 'IN';
1547 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1548 $this->group($values);
1551 // case tag comes from find contacts
1553 $this->tagSearch($values);
1557 case 'contact_tags':
1558 $this->tag($values);
1563 case 'note_subject':
1564 $this->notes($values);
1568 $this->ufUser($values);
1572 case 'display_name':
1573 $this->sortName($values);
1577 $this->email($values);
1580 case 'phone_numeric':
1581 $this->phone_numeric($values);
1584 case 'phone_phone_type_id':
1585 case 'phone_location_type_id':
1586 $this->phone_option_group($values);
1589 case 'street_address':
1590 $this->street_address($values);
1593 case 'street_number':
1594 $this->street_number($values);
1597 case 'sortByCharacter':
1598 $this->sortByCharacter($values);
1601 case 'location_type':
1602 $this->locationType($values);
1606 $this->county($values);
1609 case 'state_province':
1610 $this->stateProvince($values);
1614 $this->country($values, FALSE);
1618 case 'postal_code_low':
1619 case 'postal_code_high':
1620 $this->postalCode($values);
1623 case 'activity_date':
1624 case 'activity_date_low':
1625 case 'activity_date_high':
1626 case 'activity_role':
1627 case 'activity_status':
1628 case 'activity_subject':
1629 case 'test_activities':
1630 case 'activity_type_id':
1631 case 'activity_survey_id':
1632 case 'activity_tags':
1633 case 'activity_taglist':
1634 case 'activity_test':
1635 case 'activity_campaign_id':
1636 case 'activity_engagement_level':
1638 case 'activity_result':
1639 case 'source_contact':
1640 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1643 case 'birth_date_low':
1644 case 'birth_date_high':
1645 case 'deceased_date_low':
1646 case 'deceased_date_high':
1647 $this->demographics($values);
1650 case 'log_date_low':
1651 case 'log_date_high':
1652 $this->modifiedDates($values);
1656 $this->changeLog($values);
1659 case 'do_not_phone':
1660 case 'do_not_email':
1663 case 'do_not_trade':
1665 $this->privacy($values);
1668 case 'privacy_options':
1669 $this->privacyOptions($values);
1672 case 'privacy_operator':
1673 case 'privacy_toggle':
1674 // these are handled by privacy options
1677 case 'preferred_communication_method':
1678 $this->preferredCommunication($values);
1681 case 'relation_type_id':
1682 case 'relation_start_date_high':
1683 case 'relation_start_date_low':
1684 case 'relation_end_date_high':
1685 case 'relation_end_date_low':
1686 case 'relation_target_name':
1687 case 'relation_status':
1688 case 'relation_date_low':
1689 case 'relation_date_high':
1690 $this->relationship($values);
1691 $this->_relationshipValuesAdded
= TRUE;
1694 case 'task_status_id':
1695 $this->task($values);
1699 // since this case is handled with the above
1702 case 'prox_distance':
1703 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1706 case 'prox_street_address':
1708 case 'prox_postal_code':
1709 case 'prox_state_province_id':
1710 case 'prox_country_id':
1711 // handled by the proximity_distance clause
1715 $this->restWhere($values);
1721 * Given a list of conditions in params generate the required
1727 function whereClause() {
1728 $this->_where
[0] = array();
1729 $this->_qill
[0] = array();
1731 $this->includeContactIds();
1732 if (!empty($this->_params
)) {
1733 foreach (array_keys($this->_params
) as $id) {
1734 if (!CRM_Utils_Array
::value(0, $this->_params
[$id])) {
1737 // check for both id and contact_id
1738 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
1740 $this->_params
[$id][1] == 'IS NULL' ||
1741 $this->_params
[$id][1] == 'IS NOT NULL'
1743 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]}";
1745 elseif (is_array($this->_params
[$id][2])) {
1746 $idList = implode("','", $this->_params
[$id][2]);
1747 //why on earth do they put ' in the middle & not on the outside? We have to assume it's
1748 //to support 'something' so lets add them conditionally to support the api (which is a tested flow
1749 // so if you are looking to alter this check api test results
1750 if(strpos(trim($idList), "'") > 0) {
1751 $idList = "'" . $idList . "'";
1754 $this->_where
[0][] = "contact_a.id IN ({$idList})";
1757 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]} {$this->_params[$id][2]}";
1761 $this->whereClauseSingle($this->_params
[$id]);
1765 CRM_Core_Component
::alterQuery($this, 'where');
1767 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
1770 if ($this->_customQuery
) {
1771 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1772 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1773 if (!empty($this->_customQuery
->_where
)) {
1774 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
1777 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
1781 $andClauses = array();
1784 if (!empty($this->_where
)) {
1785 foreach ($this->_where
as $grouping => $values) {
1786 if ($grouping > 0 && !empty($values)) {
1787 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1792 if (!empty($this->_where
[0])) {
1793 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
1795 if (!empty($clauses)) {
1796 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1799 if ($validClauses > 1) {
1800 $this->_useDistinct
= TRUE;
1804 return implode(' AND ', $andClauses);
1807 function restWhere(&$values) {
1808 $name = CRM_Utils_Array
::value(0, $values);
1809 $op = CRM_Utils_Array
::value(1, $values);
1810 $value = CRM_Utils_Array
::value(2, $values);
1811 $grouping = CRM_Utils_Array
::value(3, $values);
1812 $wildcard = CRM_Utils_Array
::value(4, $values);
1814 if (isset($grouping) && !CRM_Utils_Array
::value($grouping, $this->_where
)) {
1815 $this->_where
[$grouping] = array();
1818 $multipleFields = array('url');
1820 //check if the location type exits for fields
1822 $locType = explode('-', $name);
1824 if (!in_array($locType[0], $multipleFields)) {
1825 //add phone type if exists
1826 if (isset($locType[2]) && $locType[2]) {
1827 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
1831 $field = CRM_Utils_Array
::value($name, $this->_fields
);
1834 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
1843 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
1844 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1846 if (substr($name, 0, 14) === 'state_province') {
1847 if (isset($locType[1]) && is_numeric($locType[1])) {
1849 $aName = "{$locationType[$locType[1]]}-address";
1850 $where = "`$aName`.state_province_id";
1853 $where = "civicrm_address.state_province_id";
1856 $states = CRM_Core_PseudoConstant
::stateProvince();
1857 if (is_numeric($value)) {
1858 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1859 $value = $states[(int ) $value];
1862 $intVal = CRM_Utils_Array
::key($value, $states);
1863 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1866 $this->_qill
[$grouping][] = ts('State') . " $op '$value'";
1869 $this->_qill
[$grouping][] = ts('State') . " ($lType) $op '$value'";
1872 elseif (!empty($field['pseudoconstant'])) {
1873 $this->optionValueQuery(
1874 $name, $op, $value, $grouping,
1875 CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', $field['name']),
1881 if ($name == 'gender_id') {
1882 self
::$_openedPanes[ts('Demographics')] = TRUE;
1885 elseif (substr($name, 0, 7) === 'country') {
1886 if (isset($locType[1]) && is_numeric($locType[1])) {
1888 $aName = "{$locationType[$locType[1]]}-address";
1889 $where = "`$aName`.country_id";
1892 $where = "civicrm_address.country_id";
1895 $countries = CRM_Core_PseudoConstant
::country();
1896 if (is_numeric($value)) {
1897 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1898 $value = $countries[(int ) $value];
1901 $intVal = CRM_Utils_Array
::key($value, $countries);
1902 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1906 $this->_qill
[$grouping][] = ts('Country') . " $op '$value'";
1909 $this->_qill
[$grouping][] = ts('Country') . " ($lType) $op '$value'";
1912 elseif (substr($name, 0, 6) === 'county') {
1913 if (isset($locType[1]) && is_numeric($locType[1])) {
1915 $aName = "{$locationType[$locType[1]]}-address";
1916 $where = "`$aName`.county_id";
1919 $where = "civicrm_address.county_id";
1922 $counties = CRM_Core_PseudoConstant
::county();
1923 if (is_numeric($value)) {
1924 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1925 $value = $counties[(int ) $value];
1928 $intVal = CRM_Utils_Array
::key($value, $counties);
1929 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1933 $this->_qill
[$grouping][] = ts('County') . " $op '$value'";
1936 $this->_qill
[$grouping][] = ts('County') . " ($lType) $op '$value'";
1939 elseif ($name === 'world_region') {
1940 $field['where'] = 'civicrm_worldregion.id';
1941 $this->optionValueQuery(
1942 $name, $op, $value, $grouping,
1943 CRM_Core_PseudoConstant
::worldRegion(),
1948 elseif ($name === 'birth_date') {
1949 $date = CRM_Utils_Date
::processDate($value);
1950 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
1953 $date = CRM_Utils_Date
::customFormat($date);
1954 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
1957 $this->_qill
[$grouping][] = "$field[title] $op";
1959 self
::$_openedPanes[ts('Demographics')] = TRUE;
1961 elseif ($name === 'deceased_date') {
1962 $date = CRM_Utils_Date
::processDate($value);
1963 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
1965 $date = CRM_Utils_Date
::customFormat($date);
1966 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
1969 $this->_qill
[$grouping][] = "$field[title] $op";
1971 self
::$_openedPanes[ts('Demographics')] = TRUE;
1973 elseif ($name === 'is_deceased') {
1974 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
1975 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
1976 self
::$_openedPanes[ts('Demographics')] = TRUE;
1978 elseif ($name === 'contact_id') {
1979 if (is_int($value)) {
1980 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
1981 $this->_qill
[$grouping][] = "$field[title] $op $value";
1984 elseif ($name === 'name') {
1985 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
1987 $value = "%$value%";
1990 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
1991 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
1992 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
1994 elseif ($name === 'current_employer') {
1995 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
1997 $value = "%$value%";
2000 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
2001 $ceWhereClause = self
::buildClause($wc, $op,
2004 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2005 $this->_where
[$grouping][] = $ceWhereClause;
2006 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2008 elseif ($name === 'email_greeting') {
2009 $filterCondition = array('greeting_type' => 'email_greeting');
2010 $this->optionValueQuery(
2011 $name, $op, $value, $grouping,
2012 CRM_Core_PseudoConstant
::greeting($filterCondition),
2014 ts('Email Greeting')
2017 elseif ($name === 'postal_greeting') {
2018 $filterCondition = array('greeting_type' => 'postal_greeting');
2019 $this->optionValueQuery(
2020 $name, $op, $value, $grouping,
2021 CRM_Core_PseudoConstant
::greeting($filterCondition),
2023 ts('Postal Greeting')
2026 elseif ($name === 'addressee') {
2027 $filterCondition = array('greeting_type' => 'addressee');
2028 $this->optionValueQuery(
2029 $name, $op, $value, $grouping,
2030 CRM_Core_PseudoConstant
::greeting($filterCondition),
2035 elseif (substr($name, 0, 4) === 'url-') {
2036 $tName = 'civicrm_website';
2037 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2038 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2040 $value = "%$value%";
2044 $wc = 'civicrm_website.url';
2045 $this->_where
[$grouping][] = $d = self
::buildClause($wc, $op, $value);
2046 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2048 elseif ($name === 'contact_is_deleted') {
2049 $this->_where
[$grouping][] = self
::buildClause("contact_a.is_deleted", $op, $value);
2050 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2053 // sometime the value is an array, need to investigate and fix
2054 if (is_array($value)) {
2055 CRM_Core_Error
::fatal();
2058 if (!empty($field['where'])) {
2060 $value = $strtolower($value);
2063 $value = "%$value%";
2067 if (isset($locType[1]) &&
2068 is_numeric($locType[1])
2072 //get the location name
2073 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2075 $where = "`$tName`.$fldName";
2077 $this->_where
[$grouping][] = self
::buildClause("LOWER($where)", $op, $value);
2078 $this->_whereTables
[$tName] = $this->_tables
[$tName];
2079 $this->_qill
[$grouping][] = "$field[title] $op '$value'";
2082 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2083 if ($tableName == 'civicrm_contact') {
2084 $fieldName = "LOWER(contact_a.{$fieldName})";
2087 if ($op != 'IN' && !is_numeric($value)) {
2088 $fieldName = "LOWER({$field['where']})";
2091 $fieldName = "{$field['where']}";
2096 if (CRM_Utils_Array
::value('type', $field)) {
2097 $type = CRM_Utils_Type
::typeToString($field['type']);
2100 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2101 $this->_qill
[$grouping][] = "$field[title] $op $value";
2106 if ($setTables && isset($field['where'])) {
2107 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2108 if (isset($tableName)) {
2109 $this->_tables
[$tableName] = 1;
2110 $this->_whereTables
[$tableName] = 1;
2116 static function getLocationTableName(&$where, &$locType) {
2117 if (isset($locType[1]) && is_numeric($locType[1])) {
2118 list($tbName, $fldName) = explode(".", $where);
2120 //get the location name
2121 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2122 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2123 if (in_array($locType[0], $specialFields)) {
2124 //hack to fix / special handing for phone_ext
2125 if ($locType[0] == 'phone_ext') {
2126 $locType[0] = 'phone';
2128 if (isset($locType[2]) && $locType[2]) {
2129 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2132 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2135 elseif (in_array($locType[0],
2137 'address_name', 'street_address', 'supplemental_address_1', 'supplemental_address_2',
2138 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
2141 //fix for search by profile with address fields.
2142 $tName = "{$locationType[$locType[1]]}-address";
2144 elseif ($locType[0] == 'on_hold') {
2145 $tName = "{$locationType[$locType[1]]}-email";
2148 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2150 $tName = str_replace(' ', '_', $tName);
2151 return array($tName, $fldName);
2153 CRM_Core_Error
::fatal();
2157 * Given a result dao, extract the values and return that array
2159 * @param Object $dao
2161 * @return array values for this query
2163 function store($dao) {
2166 foreach ($this->_element
as $key => $dontCare) {
2167 if (property_exists($dao, $key)) {
2168 if (strpos($key, '-') !== FALSE) {
2169 $values = explode('-', $key);
2170 $lastElement = array_pop($values);
2172 $cnt = count($values);
2174 foreach ($values as $v) {
2175 if (!array_key_exists($v, $current)) {
2176 $current[$v] = array();
2178 //bad hack for im_provider
2179 if ($lastElement == 'provider_id') {
2180 if ($count < $cnt) {
2181 $current = &$current[$v];
2184 $lastElement = "{$v}_{$lastElement}";
2188 $current = &$current[$v];
2193 $current[$lastElement] = $dao->$key;
2196 $value[$key] = $dao->$key;
2204 * getter for tables array
2210 return $this->_tables
;
2213 function whereTables() {
2214 return $this->_whereTables
;
2218 * generate the where clause (used in match contacts and permissions)
2220 * @param array $params
2221 * @param array $fields
2222 * @param array $tables
2223 * @param boolean $strict
2229 static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2230 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2234 $tables = array_merge($query->tables(), $tables);
2235 $whereTables = array_merge($query->whereTables(), $whereTables);
2237 return $query->_whereClause
;
2241 * create the from clause
2243 * @param array $tables tables that need to be included in this from clause
2244 * if null, return mimimal from clause (i.e. civicrm_contact)
2245 * @param array $inner tables that should be inner-joined
2246 * @param array $right tables that should be right-joined
2248 * @return string the from clause
2252 static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2254 $from = ' FROM civicrm_contact contact_a';
2255 if (empty($tables)) {
2259 if (CRM_Utils_Array
::value('civicrm_worldregion', $tables)) {
2260 $tables = array_merge(array('civicrm_country' => 1), $tables);
2263 if ((CRM_Utils_Array
::value('civicrm_state_province', $tables) ||
2264 CRM_Utils_Array
::value('civicrm_country', $tables) ||
2265 CRM_Utils_Array
::value('civicrm_county', $tables)
2267 !CRM_Utils_Array
::value('civicrm_address', $tables)
2269 $tables = array_merge(array('civicrm_address' => 1),
2274 // add group_contact table if group table is present
2275 if (CRM_Utils_Array
::value('civicrm_group', $tables) &&
2276 !CRM_Utils_Array
::value('civicrm_group_contact', $tables)
2278 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
2281 // add group_contact and group table is subscription history is present
2282 if (CRM_Utils_Array
::value('civicrm_subscription_history', $tables)
2283 && !CRM_Utils_Array
::value('civicrm_group', $tables)
2285 $tables = array_merge(array(
2286 'civicrm_group' => 1,
2287 'civicrm_group_contact' => 1,
2293 // to handle table dependencies of components
2294 CRM_Core_Component
::tableNames($tables);
2295 // to handle table dependencies of hook injected tables
2296 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2298 //format the table list according to the weight
2299 $info = CRM_Core_TableHierarchy
::info();
2301 foreach ($tables as $key => $value) {
2303 if (strpos($key, '-') !== FALSE) {
2304 $keyArray = explode('-', $key);
2305 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2307 elseif (strpos($key, '_') !== FALSE) {
2308 $keyArray = explode('_', $key);
2309 if (is_numeric(array_pop($keyArray))) {
2310 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2313 $k = CRM_Utils_Array
::value($key, $info, 99);
2317 $k = CRM_Utils_Array
::value($key, $info, 99);
2319 $tempTable[$k . ".$key"] = $key;
2322 $newTables = array();
2323 foreach ($tempTable as $key) {
2324 $newTables[$key] = $tables[$key];
2327 $tables = $newTables;
2329 foreach ($tables as $name => $value) {
2334 if (CRM_Utils_Array
::value($name, $inner)) {
2337 elseif (CRM_Utils_Array
::value($name, $right)) {
2345 // if there is already a join statement in value, use value itself
2346 if (strpos($value, 'JOIN')) {
2347 $from .= " $value ";
2350 $from .= " $side JOIN $name ON ( $value ) ";
2355 case 'civicrm_address':
2356 if ($primaryLocation) {
2357 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2360 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2364 case 'civicrm_phone':
2365 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2368 case 'civicrm_email':
2369 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2373 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2377 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2378 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2379 $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)";
2382 case 'civicrm_openid':
2383 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2386 case 'civicrm_worldregion':
2387 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2388 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2391 case 'civicrm_location_type':
2392 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2395 case 'civicrm_group':
2396 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2399 case 'civicrm_group_contact':
2400 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2403 case 'civicrm_activity':
2404 case 'civicrm_activity_tag':
2405 case 'activity_type':
2406 case 'activity_status':
2407 case 'civicrm_activity_contact':
2408 case 'source_contact':
2409 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2412 case 'civicrm_entity_tag':
2413 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2414 civicrm_entity_tag.entity_id = contact_a.id ) ";
2417 case 'civicrm_note':
2418 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2419 contact_a.id = civicrm_note.entity_id ) ";
2422 case 'civicrm_subscription_history':
2423 $from .= " $side JOIN civicrm_subscription_history
2424 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2425 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2428 case 'civicrm_relationship':
2429 if (self
::$_relType == 'reciprocal') {
2430 if(self
::$_relationshipTempTable) {
2431 // we have a temptable to join on
2432 $tbl = self
::$_relationshipTempTable;
2433 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2436 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2437 $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)";
2440 elseif (self
::$_relType == 'b') {
2441 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2442 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2445 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2446 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2451 $from .= " $side JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2452 $from .= " $side JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2456 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2459 case 'civicrm_grant':
2460 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2463 case 'civicrm_website':
2464 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2468 $from .= CRM_Core_Component
::from($name, $mode, $side);
2469 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2479 * WHERE / QILL clause for deleted_contacts
2483 function deletedContacts($values) {
2484 list($_, $_, $value, $grouping, $_) = $values;
2486 // *prepend* to the relevant grouping as this is quite an important factor
2487 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2492 * where / qill clause for contact_type
2497 function contactType(&$values) {
2498 list($name, $op, $value, $grouping, $wildcard) = $values;
2500 $subTypes = array();
2503 // account for search builder mapping multiple values
2504 if (!is_array($value)) {
2505 $values = self
::parseSearchBuilderString($value, 'String');
2506 if (is_array($values)) {
2507 $value = array_flip($values);
2511 if (is_array($value)) {
2512 foreach ($value as $k => $v) {
2517 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2518 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2521 if (!empty($subType)) {
2522 $subTypes[$subType] = 1;
2524 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2529 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2530 $contactType = $contactTypeANDSubType[0];
2531 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2532 if (!empty($subType)) {
2533 $subTypes[$subType] = 1;
2535 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2539 if (!empty($clause)) {
2540 if ($op == 'IN' ||
$op == 'NOT IN') {
2541 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2545 $type = array_pop($clause);
2546 $this->_where
[$grouping][] = "contact_a.contact_type $op $type";
2549 $this->_qill
[$grouping][] = ts('Contact Type') . ' - ' . implode(' ' . ts('or') . ' ', $quill);
2551 if (!empty($subTypes)) {
2552 $this->includeContactSubTypes($subTypes, $grouping);
2558 * where / qill clause for contact_sub_type
2563 function contactSubType(&$values) {
2564 list($name, $op, $value, $grouping, $wildcard) = $values;
2565 $this->includeContactSubTypes($value, $grouping);
2568 function includeContactSubTypes($value, $grouping) {
2571 $alias = "contact_a.contact_sub_type";
2573 if (is_array($value)) {
2574 foreach ($value as $k => $v) {
2576 $clause[$k] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($k, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2581 $clause[$value] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2584 if (!empty($clause)) {
2585 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2586 $this->_qill
[$grouping][] = ts('Contact Subtype') . ' - ' . implode(' ' . ts('or') . ' ', array_keys($clause));
2591 * where / qill clause for groups
2596 function group(&$values) {
2597 list($name, $op, $value, $grouping, $wildcard) = $values;
2599 if (count($value) > 1) {
2600 $this->_useDistinct
= TRUE;
2603 $groupNames = CRM_Core_PseudoConstant
::group();
2604 $groupIds = implode(',', array_keys($value));
2607 foreach ($value as $id => $dontCare) {
2608 if (array_key_exists($id, $groupNames) && $dontCare) {
2609 $names[] = $groupNames[$id];
2615 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2617 is_array($gcsValues[2])
2619 foreach ($gcsValues[2] as $k => $v) {
2621 if ($k == 'Added') {
2624 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2629 $statii[] = '"Added"';
2634 if (count($value) == 1 &&
2635 count($statii) == 1 &&
2636 $statii[0] == '"Added"'
2638 // check if smart group, if so we can get rid of that one additional
2640 $groupIDs = array_keys($value);
2642 if (CRM_Utils_Array
::value(0, $groupIDs) &&
2643 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
2653 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2654 $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 ) )";
2657 $qill = ts('Contacts %1', array(1 => $op));
2658 $qill .= ' ' . implode(' ' . ts('or') . ' ', $names);
2660 $groupClause = NULL;
2663 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2664 if (!empty($statii)) {
2665 $groupClause .= " AND {$gcTable}.status IN (" . implode(', ', $statii) . ")";
2666 $qill .= " " . ts('AND') . " " . ts('Group Status') . ' - ' . implode(' ' . ts('or') . ' ', $statii);
2671 $ssClause = $this->savedSearch($values);
2674 $groupClause = "( ( $groupClause ) OR ( $ssClause ) )";
2677 $groupClause = $ssClause;
2682 $this->_where
[$grouping][] = $groupClause;
2683 $this->_qill
[$grouping][] = $qill;
2686 * Function translates selection of group type into a list of groups
2688 function getGroupsFromTypeCriteria($value){
2689 $groupIds = array();
2690 foreach ($value as $groupTypeValue) {
2691 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2692 $groupIds = ($groupIds +
$groupList);
2698 * where / qill clause for smart groups
2703 function savedSearch(&$values) {
2704 list($name, $op, $value, $grouping, $wildcard) = $values;
2705 return $this->addGroupContactCache(array_keys($value));
2709 * @param array $groups
2710 * @param string $tableAlias
2711 * @param string $joinTable
2713 * @return null|string
2715 function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
2716 $config = CRM_Core_Config
::singleton();
2718 // Find all the groups that are part of a saved search.
2719 $groupIDs = implode(',', $groups);
2720 if (empty($groupIDs)) {
2725 SELECT id, cache_date, saved_search_id, children
2727 WHERE id IN ( $groupIDs )
2728 AND ( saved_search_id != 0
2729 OR saved_search_id IS NOT NULL
2730 OR children IS NOT NULL )
2733 $group = CRM_Core_DAO
::executeQuery($sql);
2734 $groupsFiltered = array();
2736 while ($group->fetch()) {
2737 $groupsFiltered[] = $group->id
;
2739 $this->_useDistinct
= TRUE;
2741 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
2742 CRM_Contact_BAO_GroupContactCache
::load($group);
2746 if (count($groupsFiltered)) {
2747 $groupIDsFiltered = implode(',', $groupsFiltered);
2749 if ($tableAlias == NULL) {
2750 $tableAlias = "civicrm_group_contact_cache_{$groupIDsFiltered}";
2753 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache `{$tableAlias}` ON {$joinTable}.id = `{$tableAlias}`.contact_id ";
2755 return "`{$tableAlias}`.group_id IN (" . $groupIDsFiltered . ")";
2762 * where / qill clause for cms users
2767 function ufUser(&$values) {
2768 list($name, $op, $value, $grouping, $wildcard) = $values;
2771 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2773 $this->_qill
[$grouping][] = ts('CMS User');
2775 elseif ($value == 0) {
2776 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2778 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2779 $this->_qill
[$grouping][] = ts('Not a CMS User');
2784 * all tag search specific
2789 function tagSearch(&$values) {
2790 list($name, $op, $value, $grouping, $wildcard) = $values;
2793 $value = "%{$value}%";
2796 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2797 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2799 $etTable = "`civicrm_entity_tag-" . $value . "`";
2800 $tTable = "`civicrm_tag-" . $value . "`";
2802 if ($useAllTagTypes[2]) {
2803 $this->_tables
[$etTable] =
2804 $this->_whereTables
[$etTable] =
2805 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
2806 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
2808 // search tag in cases
2809 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2810 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
2811 $this->_tables
[$etCaseTable] =
2812 $this->_whereTables
[$etCaseTable] =
2813 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2814 LEFT JOIN civicrm_case
2815 ON (civicrm_case_contact.case_id = civicrm_case.id
2816 AND civicrm_case.is_deleted = 0 )
2817 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
2818 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
2819 // search tag in activities
2820 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2821 $tActTable = "`civicrm_act_tag-" . $value . "`";
2822 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2823 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2825 $this->_tables
[$etActTable] =
2826 $this->_whereTables
[$etActTable] =
2827 " LEFT JOIN civicrm_activity_contact
2828 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
2829 LEFT JOIN civicrm_activity
2830 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
2831 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2832 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
2833 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
2835 $this->_where
[$grouping][] = "({$tTable}.name $op '". $value . "' OR {$tCaseTable}.name $op '". $value . "' OR {$tActTable}.name $op '". $value . "')";
2836 $this->_qill
[$grouping][] = ts('Tag %1 %2 ', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
2838 $etTable = "`civicrm_entity_tag-" . $value . "`";
2839 $tTable = "`civicrm_tag-" . $value . "`";
2840 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
2841 {$etTable}.entity_table = 'civicrm_contact' )
2842 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
2844 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
2845 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
2850 * where / qill clause for tag
2855 function tag(&$values) {
2856 list($name, $op, $value, $grouping, $wildcard) = $values;
2858 $tagNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
2859 if (is_array($value)) {
2860 if (count($value) > 1) {
2861 $this->_useDistinct
= TRUE;
2863 foreach ($value as $id => $dontCare) {
2864 $names[] = CRM_Utils_Array
::value($id, $tagNames);
2866 $names = implode(' ' . ts('or') . ' ', $names);
2867 $value = implode(',', array_keys($value));
2870 $names = CRM_Utils_Array
::value($value, $tagNames);
2874 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2875 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2877 $etTable = "`civicrm_entity_tag-" . $value . "`";
2879 if ($useAllTagTypes[2]) {
2880 $this->_tables
[$etTable] =
2881 $this->_whereTables
[$etTable] =
2882 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2884 // search tag in cases
2885 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2886 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2887 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2889 $this->_tables
[$etCaseTable] =
2890 $this->_whereTables
[$etCaseTable] =
2891 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2892 LEFT JOIN civicrm_case
2893 ON (civicrm_case_contact.case_id = civicrm_case.id
2894 AND civicrm_case.is_deleted = 0 )
2895 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
2896 // search tag in activities
2897 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2898 $this->_tables
[$etActTable] =
2899 $this->_whereTables
[$etActTable] =
2900 " LEFT JOIN civicrm_activity_contact
2901 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
2902 LEFT JOIN civicrm_activity
2903 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
2904 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2905 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
2908 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
2909 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
2912 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (". $value . ") OR {$etCaseTable}.tag_id $op (". $value . ") OR {$etActTable}.tag_id $op (". $value . "))";
2914 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
2916 $this->_tables
[$etTable] =
2917 $this->_whereTables
[$etTable] =
2918 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2921 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
2922 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
2923 $op = str_replace('EMPTY', 'NULL', $op);
2924 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
2927 $this->_where
[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
2929 $this->_qill
[$grouping][] = ts('Tagged %1', array( 1 => $op)) . ' ' . $names;
2935 * where/qill clause for notes
2940 function notes(&$values) {
2941 list($name, $op, $value, $grouping, $wildcard) = $values;
2943 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
2944 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
2945 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
2947 $this->_useDistinct
= TRUE;
2949 $this->_tables
['civicrm_note'] =
2950 $this->_whereTables
['civicrm_note'] =
2951 " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
2953 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2955 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
2956 if ($wildcard ||
$op == 'LIKE') {
2957 if (strpos($value, '%') === FALSE) {
2958 $value = "%$value%";
2962 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
2968 if ( $noteOption %
2 == 0 ) {
2969 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
2970 $label = ts('Note: Body Only');
2972 if ( $noteOption %
3 == 0 ) {
2973 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
2974 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
2976 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
2977 $this->_qill
[$grouping][] = $label . " $op - '$n'";
2980 function nameNullOrEmptyOp($name, $op, $grouping) {
2984 $this->_where
[$grouping][] = "contact_a.$name $op";
2985 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
2989 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
2990 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
2993 case 'IS NOT EMPTY':
2994 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
2995 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3004 * where / qill clause for sort_name
3009 function sortName(&$values) {
3010 list($name, $op, $value, $grouping, $wildcard) = $values;
3012 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3013 if ( $this->nameNullOrEmptyOp( $name, $op, $grouping ) ) {
3018 $name = trim($value);
3024 $config = CRM_Core_Config
::singleton();
3028 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3031 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3032 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3034 if (substr($name, 0, 1) == '"' &&
3035 substr($name, -1, 1) == '"'
3037 //If name is encased in double quotes, the value should be taken to be the string in entirety and the
3038 $value = substr($name, 1, -1);
3039 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
3040 $wc = ($newName == 'sort_name') ?
'LOWER(contact_a.sort_name)' : 'LOWER(contact_a.display_name)';
3041 $sub[] = " ( $wc = '$value' ) ";
3042 if ($config->includeEmailInName
) {
3043 $sub[] = " ( civicrm_email.email = '$value' ) ";
3046 elseif (strpos($name, ',') !== FALSE) {
3047 // if we have a comma in the string, search for the entire string
3048 $value = $strtolower(CRM_Core_DAO
::escapeString($name));
3050 if ($config->includeWildCardInName
) {
3051 $value = "'%$value%'";
3054 $value = "'$value%'";
3059 $value = "'$value'";
3061 if ($newName == 'sort_name') {
3062 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3065 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3067 $sub[] = " ( $wc $op $value )";
3068 if ($config->includeNickNameInName
) {
3069 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3070 $sub[] = " ( $wc $op $value )";
3072 if ($config->includeEmailInName
) {
3073 $sub[] = " ( civicrm_email.email $op $value ) ";
3077 // the string should be treated as a series of keywords to be matched with match ANY OR
3078 // match ALL depending on Civi config settings (see CiviAdmin)
3080 // The Civi configuration setting can be overridden if the string *starts* with the case
3081 // insenstive strings 'AND:' or 'OR:'TO THINK ABOUT: what happens when someone searches
3082 // for the following "AND: 'a string in quotes'"? - probably nothing - it would make the
3083 // AND OR variable reduntant because there is only one search string?
3085 // Check to see if the $subGlue is overridden in the search text
3086 if (strtolower(substr($name, 0, 4)) == 'and:') {
3087 $name = substr($name, 4);
3090 if (strtolower(substr($name, 0, 3)) == 'or:') {
3091 $name = substr($name, 3);
3095 $firstChar = substr($name, 0, 1);
3096 $lastChar = substr($name, -1, 1);
3097 $quotes = array("'", '"');
3098 if ((strlen($name) > 2) && in_array($firstChar, $quotes) &&
3099 in_array($lastChar, $quotes)
3101 $name = substr($name, 1);
3102 $name = substr($name, 0, -1);
3103 $pieces = array($name);
3106 $pieces = explode(' ', $name);
3108 foreach ($pieces as $piece) {
3109 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($piece)));
3110 if (strlen($value)) {
3111 // Added If as a sanitization - without it, when you do an OR search, any string with
3112 // double spaces (i.e. " ") or that has a space after the keyword (e.g. "OR: ") will
3113 // return all contacts because it will include a condition similar to "OR contact
3114 // name LIKE '%'". It might be better to replace this with array_filter.
3115 $fieldsub = array();
3117 if ($config->includeWildCardInName
) {
3118 $value = "'%$value%'";
3121 $value = "'$value%'";
3126 $value = "'$value'";
3128 if ($newName == 'sort_name') {
3129 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3132 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3134 $fieldsub[] = " ( $wc $op $value )";
3135 if ($config->includeNickNameInName
) {
3136 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3137 $fieldsub[] = " ( $wc $op $value )";
3139 if ($config->includeEmailInName
) {
3140 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3142 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3143 // I seperated the glueing in two. The first stage should always be OR because we are searching for matches in *ANY* of these fields
3148 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3150 $this->_where
[$grouping][] = $sub;
3151 if ($config->includeEmailInName
) {
3152 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3153 $this->_qill
[$grouping][] = ts('Name or Email ') . "$op - '$name'";
3156 $this->_qill
[$grouping][] = ts('Name like') . " - '$name'";
3161 * where / qill clause for email
3166 function email(&$values) {
3167 list($name, $op, $value, $grouping, $wildcard) = $values;
3171 $config = CRM_Core_Config
::singleton();
3173 if (substr($n, 0, 1) == '"' &&
3174 substr($n, -1, 1) == '"'
3176 $n = substr($n, 1, -1);
3177 $value = strtolower(CRM_Core_DAO
::escapeString($n));
3178 $value = "'$value'";
3182 $value = strtolower($n);
3184 if (strpos($value, '%') === FALSE) {
3185 $value = "%{$value}%";
3190 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3191 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3194 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3195 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3198 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3202 * where / qill clause for phone number
3207 function phone_numeric(&$values) {
3208 list($name, $op, $value, $grouping, $wildcard) = $values;
3209 // Strip non-numeric characters; allow wildcards
3210 $number = preg_replace('/[^\d%]/', '', $value);
3212 if ( strpos($number, '%') === FALSE ) {
3213 $number = "%$number%";
3216 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3217 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3218 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3223 * where / qill clause for phone type/location
3228 function phone_option_group($values) {
3229 list($name, $op, $value, $grouping, $wildcard) = $values;
3230 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3231 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3232 $optionName = $options[$value];
3233 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3234 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3235 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3239 * where / qill clause for street_address
3244 function street_address(&$values) {
3245 list($name, $op, $value, $grouping, $wildcard) = $values;
3254 $value = strtolower($n);
3255 if (strpos($value, '%') === FALSE) {
3256 // only add wild card if not there
3257 $value = "%{$value}%";
3260 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3261 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3264 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3265 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3268 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3272 * where / qill clause for street_unit
3277 function street_number(&$values) {
3278 list($name, $op, $value, $grouping, $wildcard) = $values;
3286 if (strtolower($n) == 'odd') {
3287 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3288 $this->_qill
[$grouping][] = ts('Street Number is odd');
3290 elseif (strtolower($n) == 'even') {
3291 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3292 $this->_qill
[$grouping][] = ts('Street Number is even');
3295 $value = strtolower($n);
3297 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3298 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3301 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3305 * where / qill clause for sorting by character
3310 function sortByCharacter(&$values) {
3311 list($name, $op, $value, $grouping, $wildcard) = $values;
3313 $name = trim($value);
3314 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3315 $this->_where
[$grouping][] = $cond;
3316 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3320 * where / qill clause for including contact ids
3325 function includeContactIDs() {
3326 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3330 $contactIds = array();
3331 foreach ($this->_params
as $id => $values) {
3332 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3333 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3336 if (!empty($contactIds)) {
3337 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3342 * where / qill clause for postal code
3347 function postalCode(&$values) {
3348 // skip if the fields dont have anything to do with postal_code
3349 if (!CRM_Utils_Array
::value('postal_code', $this->_fields
)) {
3353 list($name, $op, $value, $grouping, $wildcard) = $values;
3355 // Handle numeric postal code range searches properly by casting the column as numeric
3356 if (is_numeric($value)) {
3357 $field = 'ROUND(civicrm_address.postal_code)';
3358 $val = CRM_Utils_Type
::escape($value, 'Integer');
3361 $field = 'civicrm_address.postal_code';
3362 $val = CRM_Utils_Type
::escape($value, 'String');
3365 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3367 if ($name == 'postal_code') {
3368 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3369 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3371 elseif ($name == 'postal_code_low') {
3372 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3373 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3375 elseif ($name == 'postal_code_high') {
3376 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3377 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3382 * where / qill clause for location type
3387 function locationType(&$values, $status = NULL) {
3388 list($name, $op, $value, $grouping, $wildcard) = $values;
3390 if (is_array($value)) {
3391 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', array_keys($value)) . ')';
3392 $this->_tables
['civicrm_address'] = 1;
3393 $this->_whereTables
['civicrm_address'] = 1;
3395 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3397 foreach (array_keys($value) as $id) {
3398 $names[] = $locationType[$id];
3401 $this->_primaryLocation
= FALSE;
3404 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3407 return implode(' ' . ts('or') . ' ', $names);
3412 function country(&$values, $fromStateProvince = TRUE) {
3413 list($name, $op, $value, $grouping, $wildcard) = $values;
3415 if (!$fromStateProvince) {
3416 $stateValues = $this->getWhereValues('state_province', $grouping);
3417 if (!empty($stateValues)) {
3418 // return back to caller if there are state province values
3419 // since that handles this case
3424 $countryClause = $countryQill = NULL;
3430 $this->_tables
['civicrm_address'] = 1;
3431 $this->_whereTables
['civicrm_address'] = 1;
3433 $countries = CRM_Core_PseudoConstant
::country();
3434 if (is_numeric($value)) {
3435 $countryClause = self
::buildClause(
3436 'civicrm_address.country_id',
3441 $countryName = $countries[(int ) $value];
3445 $intValues = self
::parseSearchBuilderString($value);
3446 if ($intValues && ($op == 'IN' ||
$op == 'NOT IN')) {
3447 $countryClause = self
::buildClause(
3448 'civicrm_address.country_id',
3453 $countryNames = array();
3454 foreach ($intValues as $v) {
3455 $countryNames[] = $countries[$v];
3457 $countryName = implode(',', $countryNames);
3460 $countries = CRM_Core_PseudoConstant
::country();
3461 $intVal = CRM_Utils_Array
::key($value, $countries);
3462 $countryClause = self
::buildClause(
3463 'civicrm_address.country_id',
3468 $countryName = $value;
3471 $countryQill = ts('Country') . " {$op} '$countryName'";
3473 if (!$fromStateProvince) {
3474 $this->_where
[$grouping][] = $countryClause;
3475 $this->_qill
[$grouping][] = $countryQill;
3479 if ($fromStateProvince) {
3480 if (!empty($countryClause)) {
3483 " ...AND... " . $countryQill,
3487 return array(NULL, NULL);
3493 * where / qill clause for county (if present)
3498 function county(&$values, $status = null) {
3499 list($name, $op, $value, $grouping, $wildcard) = $values;
3501 if (! is_array($value)) {
3502 // force the county to be an array
3503 $value = array($value);
3506 // check if the values are ids OR names of the counties
3507 $inputFormat = 'id';
3508 foreach ($value as $v) {
3509 if (!is_numeric($v)) {
3510 $inputFormat = 'name';
3518 else if ($op == '!=') {
3522 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3523 $op = str_replace('EMPTY', 'NULL', $op);
3526 if (in_array( $op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3527 $clause = "civicrm_address.county_id $op";
3529 elseif ($inputFormat == 'id') {
3530 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3532 $county = CRM_Core_PseudoConstant
::county();
3533 foreach ($value as $id) {
3534 $names[] = CRM_Utils_Array
::value($id, $county);
3538 $inputClause = array();
3539 $county = CRM_Core_PseudoConstant
::county();
3540 foreach ($value as $name) {
3541 $name = trim($name);
3542 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3544 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3547 $this->_tables
['civicrm_address'] = 1;
3548 $this->_whereTables
['civicrm_address'] = 1;
3550 $this->_where
[$grouping][] = $clause;
3552 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3554 return implode(' ' . ts('or') . ' ', $names);
3559 * where / qill clause for state/province AND country (if present)
3564 function stateProvince(&$values, $status = NULL) {
3565 list($name, $op, $value, $grouping, $wildcard) = $values;
3567 // quick escape for IS NULL
3568 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3571 else if (!is_array($value)) {
3572 // force the state to be an array
3573 // check if its in the mapper format!
3574 $values = self
::parseSearchBuilderString($value);
3575 if (is_array($values)) {
3579 $value = array($value);
3583 // check if the values are ids OR names of the states
3584 $inputFormat = 'id';
3586 foreach ($value as $v) {
3587 if (!is_numeric($v)) {
3588 $inputFormat = 'name';
3598 else if ($op == '!=') {
3602 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3603 $op = str_replace('EMPTY', 'NULL', $op);
3605 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3606 $stateClause = "civicrm_address.state_province_id $op";
3608 else if ($inputFormat == 'id') {
3609 if ($op != 'NOT IN') {
3612 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
3614 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3615 foreach ($value as $id) {
3616 $names[] = CRM_Utils_Array
::value($id, $stateProvince);
3620 $inputClause = array();
3621 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3622 foreach ($value as $name) {
3623 $name = trim($name);
3624 $inputClause[] = CRM_Utils_Array
::key($name, $stateProvince);
3626 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
3629 $this->_tables
['civicrm_address'] = 1;
3630 $this->_whereTables
['civicrm_address'] = 1;
3632 $countryValues = $this->getWhereValues('country', $grouping);
3633 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3635 if ($countryClause) {
3636 $clause = "( $stateClause AND $countryClause )";
3639 $clause = $stateClause;
3642 $this->_where
[$grouping][] = $clause;
3644 $this->_qill
[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3647 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
3652 * where / qill clause for change log
3657 function changeLog(&$values) {
3658 list($name, $op, $value, $grouping, $wildcard) = $values;
3660 $targetName = $this->getWhereValues('changed_by', $grouping);
3665 $name = trim($targetName[2]);
3666 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3667 $name = $targetName[4] ?
"%$name%" : $name;
3668 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3669 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3670 $this->_qill
[$grouping][] = ts('Changed by') . ": $name";
3673 function modifiedDates($values) {
3674 $this->_useDistinct
= TRUE;
3676 // CRM-11281, default to added date if not set
3677 $fieldTitle = ts('Added Date');
3679 foreach (array_keys($this->_params
) as $id) {
3680 if ($this->_params
[$id][0] == 'log_date') {
3681 if ($this->_params
[$id][2] == 2) {
3682 $fieldTitle = ts('Modified Date');
3687 $this->dateQueryBuilder($values,
3688 'civicrm_log', 'log_date', 'modified_date', $fieldTitle
3692 function demographics(&$values) {
3693 list($name, $op, $value, $grouping, $wildcard) = $values;
3695 if (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3697 $this->dateQueryBuilder($values,
3698 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3701 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3703 $this->dateQueryBuilder($values,
3704 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3708 self
::$_openedPanes[ts('Demographics')] = TRUE;
3711 function privacy(&$values) {
3712 list($name, $op, $value, $grouping, $wildcard) = $values;
3713 //fixed for profile search listing CRM-4633
3714 if (strpbrk($value, "[")) {
3715 $value = "'{$value}'";
3717 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3720 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3722 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3723 $title = $field ?
$field['title'] : $name;
3724 $this->_qill
[$grouping][] = "$title $op $value";
3727 function privacyOptions($values) {
3728 list($name, $op, $value, $grouping, $wildcard) = $values;
3730 if (empty($value) ||
!is_array($value)) {
3734 // get the operator and toggle values
3735 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3738 strtolower($opValues[2] == 'AND')
3743 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3745 if ($toggleValues &&
3746 $toggleValues[2] == 2
3753 foreach ($value as $dontCare => $pOption) {
3754 $clauses[] = " ( contact_a.{$pOption} $compareOP 1 ) ";
3755 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3756 $title = $field ?
$field['title'] : $pOption;
3757 $qill[] = " $title $compareOP 1 ";
3760 $this->_where
[$grouping][] = '( ' . implode($operator, $clauses) . ' )';
3761 $this->_qill
[$grouping][] = implode($operator, $qill);
3764 function preferredCommunication(&$values) {
3765 list($name, $op, $value, $grouping, $wildcard) = $values;
3768 if (in_array($op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3771 elseif (!is_array($value)) {
3773 $value = trim($value, ' ()');
3774 if (strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
3775 $v = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
3778 $v = explode(",", $value);
3781 foreach ($v as $item) {
3788 foreach ($value as $key => $checked) {
3795 $commPref = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
3797 $sqlValue = array();
3798 $showValue = array();
3799 $sql = "contact_a.preferred_communication_method";
3800 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3801 $sqlValue[] = "{$sql} {$op}";
3804 foreach ($pref as $val) {
3805 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $val . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' ) ";
3806 $showValue[] = $commPref[$val];
3809 $this->_where
[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
3810 $this->_qill
[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
3814 * where / qill clause for relationship
3819 function relationship(&$values) {
3820 list($name, $op, $value, $grouping, $wildcard) = $values;
3821 if($this->_relationshipValuesAdded
){
3824 // also get values array for relation_target_name
3825 // for relatinship search we always do wildcard
3826 $targetName = $this->getWhereValues('relation_target_name', $grouping);
3827 $relStatus = $this->getWhereValues('relation_status', $grouping);
3828 $relPermission = $this->getWhereValues('relation_permission', $grouping);
3829 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
3831 $nameClause = $name = NULL;
3833 $name = trim($targetName[2]);
3834 if (substr($name, 0, 1) == '"' &&
3835 substr($name, -1, 1) == '"'
3837 $name = substr($name, 1, -1);
3838 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3839 $nameClause = "= '$name'";
3842 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3843 $nameClause = "LIKE '%{$name}%'";
3847 $rel = explode('_', $value);
3849 self
::$_relType = $rel[1];
3850 $params = array('id' => $rel[0]);
3851 $rTypeValues = array();
3852 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
3853 if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
3854 // if we don't know which end of the relationship we are dealing with we'll create a temp table
3855 //@todo unless we are dealing with a target group
3856 self
::$_relType = 'reciprocal';
3858 // if we are creating a temp table we build our own where for the relationship table
3859 $relationshipTempTable = NULL;
3860 if(self
::$_relType == 'reciprocal' && empty($targetGroup)) {
3862 self
::$_relationshipTempTable =
3863 $relationshipTempTable =
3864 CRM_Core_DAO
::createTempTableName( 'civicrm_rel');
3866 $where[$grouping][] = " sort_name $nameClause ";
3870 $where = &$this->_where
;
3872 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
3877 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
3878 $relTypeOrg = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
3879 $relTypeHou = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Household');
3880 $allRelationshipType = array();
3881 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
3882 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
3884 if ($nameClause ||
!$targetGroup) {
3885 $this->_qill
[$grouping][] = "$allRelationshipType[$value] $name";
3889 //check to see if the target contact is in specified group
3891 //add contacts from static groups
3892 $this->_tables
['civicrm_relationship_group_contact'] =
3893 $this->_whereTables
['civicrm_relationship_group_contact'] =
3894 " 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'";
3896 "( civicrm_relationship_group_contact.group_id IN (" .
3897 implode(",", $targetGroup[2]) . ") ) ";
3899 //add contacts from saved searches
3900 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
3902 //set the group where clause
3904 $groupWhere[] = "( " . $ssWhere . " )";
3906 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
3908 //Get the names of the target groups for the qill
3909 $groupNames = CRM_Core_PseudoConstant
::group();
3910 $qillNames = array();
3911 foreach ($targetGroup[2] as $groupId) {
3912 if (array_key_exists($groupId, $groupNames)) {
3913 $qillNames[] = $groupNames[$groupId];
3916 $this->_qill
[$grouping][] = "$allRelationshipType[$value] ( " . implode(", ", $qillNames) . " )";
3919 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
3920 $today = date('Ymd');
3921 //check for active, inactive and all relation status
3922 if ($relStatus[2] == 0) {
3923 $where[$grouping][] = "(
3924 civicrm_relationship.is_active = 1 AND
3925 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
3926 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
3928 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
3930 elseif ($relStatus[2] == 1) {
3931 $where[$grouping][] = "(
3932 civicrm_relationship.is_active = 0 OR
3933 civicrm_relationship.end_date < {$today} OR
3934 civicrm_relationship.start_date > {$today}
3936 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
3939 //check for permissioned, non-permissioned and all permissioned relations
3940 if ($relPermission[2] == 1) {
3941 $this->_where
[$grouping][] = "(
3942 civicrm_relationship.is_permission_a_b = 1
3944 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
3945 } elseif ($relPermission[2] == 2) {
3946 //non-allowed permission relationship.
3947 $this->_where
[$grouping][] = "(
3948 civicrm_relationship.is_permission_a_b = 0
3950 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
3953 $this->addRelationshipDateClauses($grouping, $where);
3954 if(!empty($rType) && isset($rType->id
)){
3955 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
3957 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
3958 $this->_useDistinct
= TRUE;
3959 $this->_relationshipValuesAdded
= TRUE;
3960 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
3962 // @todo creating a temp table could be expanded to group filter
3963 // as even creating a temp table of all relationships is much much more efficient than
3964 // an OR in the join
3965 if($relationshipTempTable) {
3966 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
3968 CREATE TEMPORARY TABLE {$relationshipTempTable}
3969 (SELECT contact_id_b as contact_id, civicrm_relationship.id
3970 FROM civicrm_relationship
3971 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
3974 (SELECT contact_id_a as contact_id, civicrm_relationship.id
3975 FROM civicrm_relationship
3976 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
3979 CRM_Core_DAO
::executeQuery($sql);
3984 * Add start & end date criteria in
3985 * @param string $grouping
3986 * @param array $where = array to add where clauses to, in case you are generating a temp table
3987 * not the main query.
3989 function addRelationshipDateClauses($grouping, &$where){
3990 $dateValues = array();
3996 foreach ($dateTypes as $dateField){
3997 $dateValueLow = $this->getWhereValues('relation_'. $dateField .'_low', $grouping);
3998 $dateValueHigh= $this->getWhereValues('relation_'. $dateField .'_high', $grouping);
3999 if(!empty($dateValueLow)){
4000 $date = date('Ymd', strtotime($dateValueLow[2]));
4001 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4002 $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);
4004 if(!empty($dateValueHigh)){
4005 $date = date('Ymd', strtotime($dateValueHigh[2]));
4006 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4007 $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);
4012 * default set of return properties
4017 static function &defaultReturnProperties($mode = 1) {
4018 if (!isset(self
::$_defaultReturnProperties)) {
4019 self
::$_defaultReturnProperties = array();
4022 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4023 // add activity return properties
4024 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4025 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4028 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4031 if (empty(self
::$_defaultReturnProperties[$mode])) {
4032 self
::$_defaultReturnProperties[$mode] = array(
4035 'legal_identifier' => 1,
4036 'external_identifier' => 1,
4037 'contact_type' => 1,
4038 'contact_sub_type' => 1,
4040 'display_name' => 1,
4041 'preferred_mail_format' => 1,
4048 'formal_title' => 1,
4049 'communication_style_id' => 1,
4052 'street_address' => 1,
4053 'supplemental_address_1' => 1,
4054 'supplemental_address_2' => 1,
4057 'postal_code_suffix' => 1,
4058 'state_province' => 1,
4060 'world_region' => 1,
4067 'household_name' => 1,
4068 'organization_name' => 1,
4069 'deceased_date' => 1,
4074 'current_employer' => 1,
4075 // FIXME: should we use defaultHierReturnProperties() for the below?
4076 'do_not_email' => 1,
4079 'do_not_phone' => 1,
4080 'do_not_trade' => 1,
4082 'contact_is_deleted' => 1,
4083 'preferred_communication_method' => 1,
4084 'preferred_language' => 1,
4088 return self
::$_defaultReturnProperties[$mode];
4092 * get primary condition for a sql clause
4099 static function getPrimaryCondition($value) {
4100 if (is_numeric($value)) {
4101 $value = (int ) $value;
4102 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4108 * wrapper for a simple search query
4110 * @param array $params
4111 * @param array $returnProperties
4112 * @param \bolean|bool $count
4117 static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4118 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4119 list($select, $from, $where, $having) = $query->query();
4121 return "$select $from $where $having";
4125 * These are stub comments as this function needs more explanation - particularly in terms of how it
4126 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4128 * This function was originally written as a wrapper for the api query but is called from multiple places
4129 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4130 * but it is unclear as to whehter that is historical or there is a reason
4131 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4133 * @param array $params
4134 * @param array $returnProperties
4135 * @param null $fields
4136 * @param string $sort
4137 * @param int $offset
4138 * @param int $row_count
4139 * @param bool $smartGroupCache
4140 * @param bool $count return count obnly
4141 * @param bool $skipPermissions Should permissions be ignored or should the logged in user's permissions be applied
4143 * @params bool $smartGroupCache ?? update smart group cache?
4148 static function apiQuery(
4150 $returnProperties = NULL,
4155 $smartGroupCache = TRUE,
4157 $skipPermissions = TRUE
4160 $query = new CRM_Contact_BAO_Query(
4161 $params, $returnProperties,
4162 NULL, TRUE, FALSE, 1,
4164 TRUE, $smartGroupCache
4167 //this should add a check for view deleted if permissions are enabled
4168 if ($skipPermissions){
4169 $query->_skipDeleteClause
= TRUE;
4171 $query->generatePermissionClause(FALSE, $count);
4173 // note : this modifies _fromClause and _simpleFromClause
4174 $query->includePseudoFieldsJoin($sort);
4176 list($select, $from, $where, $having) = $query->query($count);
4178 $options = $query->_options
;
4179 if(!empty($query->_permissionWhereClause
)){
4180 if (empty($where)) {
4181 $where = "WHERE $query->_permissionWhereClause";
4184 $where = "$where AND $query->_permissionWhereClause";
4188 $sql = "$select $from $where $having";
4191 if ($query->_useGroupBy
) {
4192 $sql .= ' GROUP BY contact_a.id';
4194 if (!empty($sort)) {
4195 $sort = CRM_Utils_Type
::escape($sort, 'String');
4196 $sql .= " ORDER BY $sort ";
4198 if ($row_count > 0 && $offset >= 0) {
4199 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4200 $rowCount = CRM_Utils_Type
::escape($row_count, 'Int');
4201 $sql .= " LIMIT $offset, $row_count ";
4204 $dao = CRM_Core_DAO
::executeQuery($sql);
4207 while ($dao->fetch()) {
4209 $noRows = $dao->rowCount
;
4211 return array($noRows,NULL);
4213 $val = $query->store($dao);
4214 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4216 if (!empty($convertedVals)) {
4217 $val = array_replace_recursive($val, $convertedVals);
4219 $values[$dao->contact_id
] = $val;
4222 return array($values, $options);
4226 * create and query the db for an contact search
4228 * @param int $offset the offset for the query
4229 * @param int $rowCount the number of rows to return
4230 * @param string $sort the order by string
4231 * @param boolean $count is this a count only query ?
4232 * @param boolean $includeContactIds should we include contact ids?
4233 * @param boolean $sortByChar if true returns the distinct array of first characters for search results
4234 * @param boolean $groupContacts if true, return only the contact ids
4235 * @param boolean $returnQuery should we return the query as a string
4236 * @param string $additionalWhereClause if the caller wants to further restrict the search (used for components)
4237 * @param string $additionalFromClause should be clause with proper joins, effective to reduce where clause load.
4239 * @return CRM_Contact_DAO_Contact
4242 function searchQuery(
4243 $offset = 0, $rowCount = 0, $sort = NULL,
4244 $count = FALSE, $includeContactIds = FALSE,
4245 $sortByChar = FALSE, $groupContacts = FALSE,
4246 $returnQuery = FALSE,
4247 $additionalWhereClause = NULL, $sortOrder = NULL,
4248 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4251 if ($includeContactIds) {
4252 $this->_includeContactIds
= TRUE;
4253 $this->_whereClause
= $this->whereClause();
4256 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4258 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4259 // and that contact happens to be deleted, set $onlyDeleted to true
4260 foreach ($this->_params
as $values) {
4261 $name = CRM_Utils_Array
::value(0, $values);
4262 $op = CRM_Utils_Array
::value(1, $values);
4263 $value = CRM_Utils_Array
::value(2, $values);
4264 if ($name == 'contact_id' and $op == '=') {
4265 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4266 $onlyDeleted = TRUE;
4271 $this->generatePermissionClause($onlyDeleted, $count);
4273 // building the query string
4276 if (isset($this->_groupByComponentClause
)) {
4277 $groupBy = $this->_groupByComponentClause
;
4279 elseif ($this->_useGroupBy
) {
4280 $groupBy = ' GROUP BY contact_a.id';
4283 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4284 $groupBy = 'GROUP BY civicrm_activity.id ';
4287 $order = $orderBy = $limit = '';
4289 $config = CRM_Core_Config
::singleton();
4290 if ($config->includeOrderByClause ||
4291 isset($this->_distinctComponentClause
)
4294 if (is_string($sort)) {
4298 $orderBy = trim($sort->orderBy());
4300 if (!empty($orderBy)) {
4301 // this is special case while searching for
4302 // changelog CRM-1718
4303 if (preg_match('/sort_name/i', $orderBy)) {
4304 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4307 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
4308 $order = " ORDER BY $orderBy";
4311 $sortOrder = CRM_Utils_Type
::escape($sortOrder, 'String');
4312 $order .= " $sortOrder";
4315 // always add contact_a.id to the ORDER clause
4316 // so the order is deterministic
4317 if (strpos('contact_a.id', $order) === FALSE) {
4318 $order .= ", contact_a.id";
4322 elseif ($sortByChar) {
4323 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4326 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4330 // hack for order clause
4332 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4333 $fieldOrder = explode(' ', $fieldStr);
4334 $field = $fieldOrder[0];
4340 $this->_whereTables
["civicrm_address"] = 1;
4341 $order = str_replace($field, "civicrm_address.{$field}", $order);
4345 case 'state_province':
4346 $this->_whereTables
["civicrm_{$field}"] = 1;
4347 $order = str_replace($field, "civicrm_{$field}.name", $order);
4351 $this->_whereTables
["civicrm_email"] = 1;
4352 $order = str_replace($field, "civicrm_email.{$field}", $order);
4355 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4356 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4360 if ($rowCount > 0 && $offset >= 0) {
4361 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4362 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4363 $limit = " LIMIT $offset, $rowCount ";
4367 // note : this modifies _fromClause and _simpleFromClause
4368 $this->includePseudoFieldsJoin($sort);
4370 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts);
4372 if(!empty($this->_permissionWhereClause
)){
4373 if (empty($where)) {
4374 $where = "WHERE $this->_permissionWhereClause";
4377 $where = "$where AND $this->_permissionWhereClause";
4381 if ($additionalWhereClause) {
4382 $where = $where . ' AND ' . $additionalWhereClause;
4385 //additional from clause should be w/ proper joins.
4386 if ($additionalFromClause) {
4387 $from .= "\n" . $additionalFromClause;
4390 // if we are doing a transform, do it here
4391 // use the $from, $where and $having to get the contact ID
4392 if ($this->_displayRelationshipType
) {
4393 $this->filterRelatedContacts($from, $where, $having);
4396 if ($skipOrderAndLimit) {
4397 $query = "$select $from $where $having $groupBy";
4400 $query = "$select $from $where $having $groupBy $order $limit";
4408 return CRM_Core_DAO
::singleValueQuery($query);
4411 $dao = CRM_Core_DAO
::executeQuery($query);
4412 if ($groupContacts) {
4414 while ($dao->fetch()) {
4417 return implode(',', $ids);
4424 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4426 * @param string $cacheKey
4427 * @param int $offset
4428 * @param int $rowCount
4429 * @param bool $includeContactIds
4430 * @return CRM_Core_DAO
4432 function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4433 $this->_includeContactIds
= $includeContactIds;
4434 list($select, $from, $where) = $this->query();
4435 $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);
4436 $order = " ORDER BY pnc.id";
4437 $groupBy = " GROUP BY contact_a.id";
4438 $limit = " LIMIT $offset, $rowCount";
4439 $query = "$select $from $where $groupBy $order $limit";
4441 return CRM_Core_DAO
::executeQuery($query);
4445 * Populate $this->_permissionWhereClause with permission related clause and update other
4446 * query related properties.
4448 * Function calls ACL permission class and hooks to filter the query appropriately
4450 * Note that these 2 params were in the code when extracted from another function
4451 * and a second round extraction would be to make them properties of the class
4453 * @param bool $onlyDeleted Only get deleted contacts
4454 * @param bool $count Return Count only
4458 function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4459 if (!$this->_skipPermission
) {
4460 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4461 CRM_Core_Permission
::VIEW
,
4463 $this->_whereTables
,
4466 $this->_skipDeleteClause
4469 // regenerate fromClause since permission might have added tables
4470 if ($this->_permissionWhereClause
) {
4471 //fix for row count in qill (in contribute/membership find)
4473 $this->_useDistinct
= TRUE;
4475 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4476 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4480 // add delete clause if needed even if we are skipping permission
4482 if (!$this->_skipDeleteClause
) {
4483 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4484 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4488 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4494 function setSkipPermission($val) {
4495 $this->_skipPermission
= $val;
4498 function &summaryContribution($context = NULL) {
4499 list($select, $from, $where, $having) = $this->query(TRUE);
4503 SELECT COUNT( civicrm_contribution.total_amount ) as total_count,
4504 SUM( civicrm_contribution.total_amount ) as total_amount,
4505 AVG( civicrm_contribution.total_amount ) as total_avg,
4506 civicrm_contribution.currency as currency";
4508 // make sure contribution is completed - CRM-4989
4509 $where .= " AND civicrm_contribution.contribution_status_id = 1 ";
4510 if ($context == 'search') {
4511 $where .= " AND contact_a.is_deleted = 0 ";
4515 $summary['total'] = array();
4516 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4518 $query = "$select $from $where GROUP BY currency";
4521 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4523 $summary['total']['count'] = 0;
4524 $summary['total']['amount'] = $summary['total']['avg'] = array();
4525 while ($dao->fetch()) {
4526 $summary['total']['count'] +
= $dao->total_count
;
4527 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4528 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4530 if (!empty($summary['total']['amount'])) {
4531 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4532 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4535 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4540 SELECT COUNT( civicrm_contribution.total_amount ) as cancel_count,
4541 SUM( civicrm_contribution.total_amount ) as cancel_amount,
4542 AVG( civicrm_contribution.total_amount ) as cancel_avg,
4543 civicrm_contribution.currency as currency";
4545 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4546 if ($context == 'search') {
4547 $where .= " AND contact_a.is_deleted = 0 ";
4550 $query = "$select $from $where GROUP BY currency";
4551 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4554 if ($dao->fetch()) {
4555 $summary['cancel']['count'] = $dao->cancel_count
;
4556 $summary['cancel']['amount'] = $dao->cancel_amount
;
4557 $summary['cancel']['avg'] = $dao->cancel_avg
;
4561 $summary['cancel']['count'] = 0;
4562 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4563 while ($dao->fetch()) {
4564 $summary['cancel']['count'] +
= $dao->cancel_count
;
4565 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4566 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4568 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4569 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
4576 * getter for the qill object
4582 return $this->_qill
;
4586 * default set of return default hier return properties
4591 static function &defaultHierReturnProperties() {
4592 if (!isset(self
::$_defaultHierReturnProperties)) {
4593 self
::$_defaultHierReturnProperties = array(
4596 'legal_identifier' => 1,
4597 'external_identifier' => 1,
4598 'contact_type' => 1,
4599 'contact_sub_type' => 1,
4601 'display_name' => 1,
4608 'formal_title' => 1,
4609 'communication_style_id' => 1,
4610 'email_greeting' => 1,
4611 'postal_greeting' => 1,
4615 'preferred_communication_method' => 1,
4616 'do_not_phone' => 1,
4617 'do_not_email' => 1,
4620 'do_not_trade' => 1,
4623 '1' => array('location_type' => 1,
4624 'street_address' => 1,
4626 'state_province' => 1,
4628 'postal_code_suffix' => 1,
4631 'phone-Mobile' => 1,
4644 'location_type' => 1,
4645 'street_address' => 1,
4647 'state_province' => 1,
4649 'postal_code_suffix' => 1,
4652 'phone-Mobile' => 1,
4666 return self
::$_defaultHierReturnProperties;
4669 function dateQueryBuilder(
4670 &$values, $tableName, $fieldName,
4671 $dbFieldName, $fieldTitle,
4672 $appendTimeStamp = TRUE
4674 list($name, $op, $value, $grouping, $wildcard) = $values;
4680 if ($name == "{$fieldName}_low" ||
4681 $name == "{$fieldName}_high"
4683 if (isset($this->_rangeCache
[$fieldName])) {
4686 $this->_rangeCache
[$fieldName] = 1;
4688 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4690 if ($name == $fieldName . '_low') {
4692 $firstPhrase = ts('greater than or equal to');
4693 $firstDate = CRM_Utils_Date
::processDate($value);
4695 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4696 if (!empty($secondValues) && $secondValues[2]) {
4698 $secondPhrase = ts('less than or equal to');
4699 $secondValue = $secondValues[2];
4701 if ($appendTimeStamp && strlen($secondValue) == 10) {
4702 $secondValue .= ' 23:59:59';
4704 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4707 elseif ($name == $fieldName . '_high') {
4709 $firstPhrase = ts('less than or equal to');
4711 if ($appendTimeStamp && strlen($value) == 10) {
4712 $value .= ' 23:59:59';
4714 $firstDate = CRM_Utils_Date
::processDate($value);
4716 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4717 if (!empty($secondValues) && $secondValues[2]) {
4719 $secondPhrase = ts('greater than or equal to');
4720 $secondValue = $secondValues[2];
4721 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4725 if (!$appendTimeStamp) {
4726 $firstDate = substr($firstDate, 0, 8);
4728 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
4731 if (!$appendTimeStamp) {
4732 $secondDate = substr($secondDate, 0, 8);
4734 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
4737 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4739 $this->_where
[$grouping][] = "
4740 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
4741 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
4743 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
4746 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
4747 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
4751 if ($name == $fieldName) {
4755 $date = CRM_Utils_Date
::processDate($value);
4757 if (!$appendTimeStamp) {
4758 $date = substr($date, 0, 8);
4761 $format = CRM_Utils_Date
::customFormat($date);
4764 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'";
4767 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op";
4769 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4770 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$format\"";
4774 $tableName == 'civicrm_log' &&
4775 $fieldTitle == ts('Added Date')
4777 //CRM-6903 --hack to check modified date of first record.
4778 //as added date means first modified date of object.
4779 $addedDateQuery = 'select id from civicrm_log group by entity_id order by id';
4780 $this->_where
[$grouping][] = "civicrm_log.id IN ( {$addedDateQuery} )";
4784 function numberRangeBuilder(&$values,
4785 $tableName, $fieldName,
4786 $dbFieldName, $fieldTitle,
4789 list($name, $op, $value, $grouping, $wildcard) = $values;
4791 if ($name == "{$fieldName}_low" ||
4792 $name == "{$fieldName}_high"
4794 if (isset($this->_rangeCache
[$fieldName])) {
4797 $this->_rangeCache
[$fieldName] = 1;
4799 $secondOP = $secondPhrase = $secondValue = NULL;
4801 if ($name == "{$fieldName}_low") {
4803 $firstPhrase = ts('greater than');
4805 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4806 if (!empty($secondValues)) {
4808 $secondPhrase = ts('less than');
4809 $secondValue = $secondValues[2];
4814 $firstPhrase = ts('less than');
4816 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4817 if (!empty($secondValues)) {
4819 $secondPhrase = ts('greater than');
4820 $secondValue = $secondValues[2];
4825 $this->_where
[$grouping][] = "
4826 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
4827 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
4829 $displayValue = $options ?
$options[$value] : $value;
4830 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
4832 $this->_qill
[$grouping][] =
4833 "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
4836 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
4837 $displayValue = $options ?
$options[$value] : $value;
4838 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
4840 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4845 if ($name == $fieldName) {
4849 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
4851 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4852 $displayValue = $options ?
$options[$value] : $value;
4853 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
4860 * Given the field name, operator, value & its data type
4861 * builds the where Clause for the query
4862 * used for handling 'IS NULL'/'IS NOT NULL' operators
4864 * @param string $field fieldname
4865 * @param string $op operator
4866 * @param string $value value
4867 * @param string $dataType data type of the field
4869 * @return where clause for the query
4872 static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
4874 $clause = "$field $op";
4882 $clause = " ( $field IS NULL OR $field = '' ) ";
4885 case 'IS NOT EMPTY':
4886 $clause = " ( $field IS NOT NULL AND $field <> '' ) ";
4891 if (isset($dataType)) {
4892 if (is_array($value)) {
4896 $value = CRM_Utils_Type
::escape($value, "String");
4897 $values = explode(',', CRM_Utils_Array
::value(0, explode(')', CRM_Utils_Array
::value(1, explode('(', $value)))));
4899 // supporting multiple values in IN clause
4901 foreach ($values as $v) {
4903 $val[] = "'" . CRM_Utils_Type
::escape($v, $dataType) . "'";
4905 $value = "(" . implode($val, ",") . ")";
4907 return "$clause $value";
4910 if (empty($dataType)) {
4911 $dataType = 'String';
4914 $value = CRM_Utils_Type
::escape($value, $dataType);
4915 // if we dont have a dataType we should assume
4916 if ($dataType == 'String' ||
$dataType == 'Text') {
4917 $value = "'" . strtolower($value) . "'";
4919 return "$clause $value";
4923 function openedSearchPanes($reset = FALSE) {
4924 if (!$reset ||
empty($this->_whereTables
)) {
4925 return self
::$_openedPanes;
4928 // pane name to table mapper
4929 $panesMapper = array(
4930 ts('Contributions') => 'civicrm_contribution',
4931 ts('Memberships') => 'civicrm_membership',
4932 ts('Events') => 'civicrm_participant',
4933 ts('Relationships') => 'civicrm_relationship',
4934 ts('Activities') => 'civicrm_activity',
4935 ts('Pledges') => 'civicrm_pledge',
4936 ts('Cases') => 'civicrm_case',
4937 ts('Grants') => 'civicrm_grant',
4938 ts('Address Fields') => 'civicrm_address',
4939 ts('Notes') => 'civicrm_note',
4940 ts('Change Log') => 'civicrm_log',
4941 ts('Mailings') => 'civicrm_mailing_event_queue',
4943 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
4945 foreach (array_keys($this->_whereTables
) as $table) {
4946 if ($panName = array_search($table, $panesMapper)) {
4947 self
::$_openedPanes[$panName] = TRUE;
4951 return self
::$_openedPanes;
4954 function setOperator($operator) {
4955 $validOperators = array('AND', 'OR');
4956 if (!in_array($operator, $validOperators)) {
4959 $this->_operator
= $operator;
4962 function getOperator() {
4963 return $this->_operator
;
4966 function filterRelatedContacts(&$from, &$where, &$having) {
4967 static $_rTypeProcessed = NULL;
4968 static $_rTypeFrom = NULL;
4969 static $_rTypeWhere = NULL;
4971 if (!$_rTypeProcessed) {
4972 $_rTypeProcessed = TRUE;
4974 // create temp table with contact ids
4975 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
4976 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
4977 CRM_Core_DAO
::executeQuery($sql);
4980 REPLACE INTO $tableName ( contact_id )
4986 CRM_Core_DAO
::executeQuery($sql);
4988 $qillMessage = ts('Contacts with a Relationship Type of: ');
4989 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
4991 if (is_numeric($this->_displayRelationshipType
)) {
4992 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
4994 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
4995 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
4998 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
4999 AND displayRelType.is_active = 1
5003 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5004 if ($dirOne == 'a') {
5005 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5007 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5008 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5012 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5014 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5015 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5019 WHERE displayRelType.relationship_type_id = $relType
5020 AND displayRelType.is_active = 1
5023 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5026 if (strpos($from, $_rTypeFrom) === FALSE) {
5027 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5028 // this happens when we have an event_type in the quert (CRM-7969)
5029 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5030 $from .= $_rTypeFrom;
5031 $where = $_rTypeWhere;
5037 static function caseImportant( $op ) {
5039 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5042 static function componentPresent( &$returnProperties, $prefix ) {
5043 foreach ($returnProperties as $name => $dontCare ) {
5044 if (substr($name, 0, strlen($prefix)) == $prefix) {
5052 * Builds the necessary structures for all fields that are similar to option value lookups
5054 * @param $name string the name of the field
5055 * @param $op string the sql operator, this function should handle ALL SQL operators
5056 * @param $value any string / integer / array depends on the operator and whos calling the query builder
5057 * @param $grouping int the index where to place the where clause
5058 * @param $selectValues
5059 * @param $field array an array that contains various properties of the field identified by $name
5060 * @param $label string The label for this field element
5061 * @param $dataType string The data type for this element
5063 * @param bool $useIDsOnly
5065 * @internal param array $selectValue the key value pairs for this element. This allows us to use this function for things besides option-value pairs
5066 * @return void adds the where clause and qill to the query object
5068 function optionValueQuery(
5076 $dataType = 'String',
5080 if (!empty($selectValues)) {
5081 $qill = $selectValues[$value];
5087 $pseudoFields = array('email_greeting', 'postal_greeting', 'addressee', 'gender_id', 'prefix_id', 'suffix_id', 'communication_style_id');
5089 if (is_numeric($value)) {
5090 $qill = $selectValues[(int ) $value];
5092 elseif ($op == 'IN' ||
$op == 'NOT IN') {
5093 $values = self
::parseSearchBuilderString($value);
5094 if (is_array($values)) {
5096 $newValues = array();
5097 foreach ($values as $v) {
5098 $intVals[] = (int) $v;
5099 $newValues[] = $selectValues[(int ) $v];
5102 $value = (in_array($name, $pseudoFields)) ?
$intVals : $newValues;
5103 $qill = implode(', ', $newValues);
5106 elseif (!array_key_exists($value, $selectValues)) {
5107 // its a string, lets get the int value
5108 $value = array_search($value, $selectValues);
5111 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5112 if ($tableName == 'civicrm_contact') {
5113 $wc = "contact_a.$fieldName";
5117 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5120 if (in_array($name, $pseudoFields)) {
5121 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5122 $wc = "contact_a.{$name}_id";
5124 $dataType = 'Positive';
5125 $value = (!$value) ?
0 : $value;
5128 $this->_qill
[$grouping][] = $label . " $op '$qill'";
5129 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' ||
$op == 'RLIKE')) ?
'=' : $op;
5130 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5134 * function to check and explode a user defined numeric string into an array
5135 * this was the protocol used by search builder in the old old days before we had
5136 * super nice js widgets to do the hard work
5138 * @param the $string
5139 * @param string $dataType the dataType we should check for the values, default integer
5141 * @return FALSE if string does not match the patter
5142 * array of numeric values if string does match the pattern
5145 static function parseSearchBuilderString($string, $dataType = 'Integer') {
5146 $string = trim($string);
5147 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5151 $string = substr($string, 1, -1);
5152 $values = explode(',', $string);
5153 if (empty($values)) {
5157 $returnValues = array();
5158 foreach ($values as $v) {
5159 if ($dataType == 'Integer' && ! is_numeric($v)) {
5162 else if ($dataType == 'String' && ! is_string($v)) {
5165 $returnValues[] = trim($v);
5168 if (empty($returnValues)) {
5172 return $returnValues;
5176 * convert the pseudo constants id's to their names
5178 * @param reference parameter $dao
5179 * @param bool $return
5183 function convertToPseudoNames(&$dao, $return = FALSE) {
5184 if (empty($this->_pseudoConstantsSelect
)) {
5188 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5189 if (CRM_Utils_Array
::value('sorting', $this->_pseudoConstantsSelect
[$key])) {
5193 if (property_exists($dao, $value['idCol'])) {
5194 $val = $dao->$value['idCol'];
5196 if (CRM_Utils_System
::isNull($val)) {
5199 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5201 $idColumn = "{$key}_id";
5202 $dao->$idColumn = $val;
5203 $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5205 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5206 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5209 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5210 $dao->$key = $labels[$val];
5213 // return converted values in array format
5215 if (strpos($key, '-') !== FALSE) {
5216 $keyVal = explode('-', $key);
5217 $current = &$values;
5218 $lastElement = array_pop($keyVal);
5219 foreach ($keyVal as $v) {
5220 if (!array_key_exists($v, $current)) {
5221 $current[$v] = array();
5223 $current = &$current[$v];
5225 $current[$lastElement] = $dao->$key;
5228 $values[$key] = $dao->$key;
5237 * include pseudo fields LEFT JOIN
5238 * @param $sort can be a object or string
5242 function includePseudoFieldsJoin($sort) {
5243 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5246 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5249 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5250 if (CRM_Utils_Array
::value('table', $value)) {
5251 $regex = "/({$value['table']}\.|{$name})/";
5252 if (preg_match($regex, $sort)) {
5253 $this->_elemnt
[$value['element']] = 1;
5254 $this->_select
[$value['element']] = $value['select'];
5255 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5256 $present[$value['table']] = $value['join'];
5260 $presentSimpleFrom = $present;
5262 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5263 array_key_exists('civicrm_country', $presentSimpleFrom)) {
5264 unset($presentSimpleFrom['civicrm_country']);
5266 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5267 array_key_exists('civicrm_country', $present)) {
5268 unset($present['civicrm_country']);
5271 $presentClause = $presentSimpleFromClause = NULL;
5272 if (!empty($present)) {
5273 $presentClause = implode(' ', $present);
5275 if (!empty($presentSimpleFrom)) {
5276 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5279 $this->_fromClause
= $this->_fromClause
. $presentClause;
5280 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5282 return array($presentClause, $presentSimpleFromClause);