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 * For search builder - which custom fields are location-dependent
345 public $_locationSpecificCustomFields = array();
348 * The tables which have a dependency on location and/or address
353 static $_dependencies = array(
354 'civicrm_state_province' => 1,
355 'civicrm_country' => 1,
356 'civicrm_county' => 1,
357 'civicrm_address' => 1,
358 'civicrm_location_type' => 1,
362 * List of location specific fields
364 static $_locationSpecificFields = array(
369 'supplemental_address_1',
370 'supplemental_address_2',
373 'postal_code_suffix',
386 * Rememeber if we handle either end of a number or date range
387 * so we can skip the other
389 protected $_rangeCache = array();
391 * Set to true when $this->relationship is run to avoid adding twice
394 protected $_relationshipValuesAdded = FALSE;
397 * Set to the name of the temp table if one has been created
400 static $_relationshipTempTable = NULL;
402 public $_pseudoConstantsSelect = array();
405 * class constructor which also does all the work
407 * @param array $params
408 * @param array $returnProperties
409 * @param array $fields
410 * @param boolean $includeContactIds
411 * @param boolean $strict
412 * @param boolean $mode - mode the search is operating on
417 function __construct(
418 $params = NULL, $returnProperties = NULL, $fields = NULL,
419 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
420 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
421 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
424 $this->_params
= &$params;
425 if ($this->_params
== NULL) {
426 $this->_params
= array();
429 if (empty($returnProperties)) {
430 $this->_returnProperties
= self
::defaultReturnProperties($mode);
433 $this->_returnProperties
= &$returnProperties;
436 $this->_includeContactIds
= $includeContactIds;
437 $this->_strict
= $strict;
438 $this->_mode
= $mode;
439 $this->_skipPermission
= $skipPermission;
440 $this->_smartGroupCache
= $smartGroupCache;
441 $this->_displayRelationshipType
= $displayRelationshipType;
442 $this->setOperator($operator);
445 $this->_fields
= &$fields;
446 $this->_search
= FALSE;
447 $this->_skipPermission
= TRUE;
450 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE);
452 $fields = CRM_Core_Component
::getQueryFields();
453 unset($fields['note']);
454 $this->_fields
= array_merge($this->_fields
, $fields);
456 // add activity fields
457 $fields = CRM_Activity_BAO_Activity
::exportableFields();
458 $this->_fields
= array_merge($this->_fields
, $fields);
460 // add any fields provided by hook implementers
461 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
462 $this->_fields
= array_merge($this->_fields
, $extFields);
465 // basically do all the work once, and then reuse it
470 * function which actually does all the work for the constructor
475 function initialize() {
476 $this->_select
= array();
477 $this->_element
= array();
478 $this->_tables
= array();
479 $this->_whereTables
= array();
480 $this->_where
= array();
481 $this->_qill
= array();
482 $this->_options
= array();
483 $this->_cfIDs
= array();
484 $this->_paramLookup
= array();
485 $this->_having
= array();
487 $this->_customQuery
= NULL;
489 // reset cached static variables - CRM-5803
490 self
::$_activityRole = NULL;
491 self
::$_considerCompActivities = NULL;
492 self
::$_withContactActivitiesOnly = NULL;
494 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
495 $this->_element
['contact_id'] = 1;
496 $this->_tables
['civicrm_contact'] = 1;
498 if (!empty($this->_params
)) {
499 $this->buildParamsLookup();
502 $this->_whereTables
= $this->_tables
;
504 $this->selectClause();
505 $this->_whereClause
= $this->whereClause();
507 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
508 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
510 $this->openedSearchPanes(TRUE);
513 function buildParamsLookup() {
514 // first fix and handle contact deletion nicely
515 // this code is primarily for search builder use case
516 // where different clauses can specify if they want deleted
519 $trashParamExists = FALSE;
520 $paramByGroup = array();
521 foreach ( $this->_params
as $k => $param ) {
522 if (!empty($param[0]) && $param[0] == 'contact_is_deleted' ) {
523 $trashParamExists = TRUE;
525 if (!empty($param[3])) {
526 $paramByGroup[$param[3]][$k] = $param;
530 if ( $trashParamExists ) {
531 $this->_skipDeleteClause
= TRUE;
533 //cycle through group sets and explicitly add trash param if not set
534 foreach ( $paramByGroup as $setID => $set ) {
536 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params
) &&
537 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params
) ) {
538 $this->_params
[] = array(
539 'contact_is_deleted',
549 foreach ($this->_params
as $value) {
550 if (!CRM_Utils_Array
::value(0, $value)) {
553 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
555 if (!array_key_exists($cfID, $this->_cfIDs
)) {
556 $this->_cfIDs
[$cfID] = array();
558 $this->_cfIDs
[$cfID][] = $value;
561 if (!array_key_exists($value[0], $this->_paramLookup
)) {
562 $this->_paramLookup
[$value[0]] = array();
564 $this->_paramLookup
[$value[0]][] = $value;
569 * Some composite fields do not appear in the fields array
570 * hack to make them part of the query
575 function addSpecialFields() {
576 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
577 foreach ($special as $name) {
578 if (CRM_Utils_Array
::value($name, $this->_returnProperties
)) {
579 $this->_select
[$name] = "contact_a.{$name} as $name";
580 $this->_element
[$name] = 1;
586 * Given a list of conditions in params and a list of desired
587 * return Properties generate the required select and from
588 * clauses. Note that since the where clause introduces new
589 * tables, the initial attempt also retrieves all variables used
595 function selectClause() {
597 $this->addSpecialFields();
599 foreach ($this->_fields
as $name => $field) {
600 // skip component fields
601 // there are done by the alter query below
602 // and need not be done on every field
604 (substr($name, 0, 12) == 'participant_') ||
605 (substr($name, 0, 7) == 'pledge_') ||
606 (substr($name, 0, 5) == 'case_')
611 // redirect to activity select clause
612 if (substr($name, 0, 9) == 'activity_') {
613 CRM_Activity_BAO_Query
::select($this);
617 // if this is a hierarchical name, we ignore it
618 $names = explode('-', $name);
619 if (count($names > 1) && isset($names[1]) && is_numeric($names[1])) {
623 // make an exception for special cases, to add the field in select clause
624 $makeException = FALSE;
626 //special handling for groups/tags
627 if (in_array($name, array('groups', 'tags', 'notes'))
628 && isset($this->_returnProperties
[substr($name, 0, -1)])
630 $makeException = TRUE;
633 // since note has 3 different options we need special handling
634 // note / note_subject / note_body
635 if ($name == 'notes') {
636 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
637 if (isset($this->_returnProperties
[$noteField])) {
638 $makeException = TRUE;
644 if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id'))) {
645 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
646 $makeException = TRUE;
650 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
652 CRM_Utils_Array
::value($name, $this->_paramLookup
) ||
653 CRM_Utils_Array
::value($name, $this->_returnProperties
) ||
657 // add to cfIDs array if not present
658 if (!array_key_exists($cfID, $this->_cfIDs
)) {
659 $this->_cfIDs
[$cfID] = array();
662 elseif (isset($field['where'])) {
663 list($tableName, $fieldName) = explode('.', $field['where'], 2);
664 if (isset($tableName)) {
665 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
666 $this->_tables
['civicrm_address'] = 1;
667 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
668 $this->_element
['address_id'] = 1;
671 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
672 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
674 if ($tableName == 'im_provider') {
675 CRM_Core_OptionValue
::select($this);
678 if (in_array($tableName,
679 array('email_greeting', 'postal_greeting', 'addressee'))) {
680 $this->_element
["{$name}_id"] = 1;
681 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
682 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
683 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
684 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
686 if ($tableName == 'email_greeting') {
687 $this->_pseudoConstantsSelect
[$name]['join'] =
688 " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
689 $this->_pseudoConstantsSelect
[$name]['join'] .=
690 " 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 ) ";
692 elseif ($tableName == 'postal_greeting') {
693 $this->_pseudoConstantsSelect
[$name]['join'] =
694 " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
695 $this->_pseudoConstantsSelect
[$name]['join'] .=
696 " 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 ) ";
698 elseif ($tableName == 'addressee') {
699 $this->_pseudoConstantsSelect
[$name]['join'] =
700 " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
701 $this->_pseudoConstantsSelect
[$name]['join'] .=
702 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
704 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
707 $greetField = "{$name}_display";
708 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
709 $this->_element
[$greetField] = 1;
711 $greetField = "{$name}_custom";
712 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
713 $this->_element
[$greetField] = 1;
717 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
718 $this->_tables
[$tableName] = 1;
721 // also get the id of the tableName
722 $tName = substr($tableName, 8);
723 if (in_array($tName, array('country', 'state_province', 'county'))) {
724 if ($tName == 'state_province') {
725 $this->_pseudoConstantsSelect
['state_province_name'] =
726 array('pseudoField' => "{$tName}", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address',
727 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
729 $this->_pseudoConstantsSelect
[$tName] =
730 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id",
731 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
734 $this->_pseudoConstantsSelect
[$name] =
735 array('pseudoField' => "{$tName}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address',
736 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
739 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
740 $this->_element
["{$tName}_id"] = 1;
742 elseif ($tName != 'contact') {
743 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
744 $this->_element
["{$tName}_id"] = 1;
747 //special case for phone
748 if ($name == 'phone') {
749 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
750 $this->_element
['phone_type_id'] = 1;
753 // if IM then select provider_id also
754 // to get "IM Service Provider" in a file to be exported, CRM-3140
756 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
757 $this->_element
['provider_id'] = 1;
760 if ($tName == 'contact') {
761 // special case, when current employer is set for Individual contact
762 if ($fieldName == 'organization_name') {
763 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
765 elseif ($fieldName != 'id') {
766 if ($fieldName == 'prefix_id') {
767 $this->_pseudoConstantsSelect
['individual_prefix'] = array('pseudoField' => 'prefix_id', 'idCol' => "prefix_id", 'bao' => 'CRM_Contact_BAO_Contact');
769 if ($fieldName == 'suffix_id') {
770 $this->_pseudoConstantsSelect
['individual_suffix'] = array('pseudoField' => 'suffix_id', 'idCol' => "suffix_id", 'bao' => 'CRM_Contact_BAO_Contact');
772 if ($fieldName == 'gender_id') {
773 $this->_pseudoConstantsSelect
['gender'] = array('pseudoField' => 'gender_id', 'idCol' => "gender_id", 'bao' => 'CRM_Contact_BAO_Contact');
775 $this->_select
[$name] = "contact_a.{$fieldName} as `$name`";
778 elseif (in_array($tName, array('country', 'county'))) {
779 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
780 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
782 elseif ($tName == 'state_province') {
783 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
784 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
787 $this->_select
[$name] = "{$field['where']} as `$name`";
789 if (!in_array($tName, array('state_province', 'country', 'county'))) {
790 $this->_element
[$name] = 1;
795 elseif ($name === 'tags') {
796 $this->_useGroupBy
= TRUE;
797 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
798 $this->_element
[$name] = 1;
799 $this->_tables
['civicrm_tag'] = 1;
800 $this->_tables
['civicrm_entity_tag'] = 1;
802 elseif ($name === 'groups') {
803 $this->_useGroupBy
= TRUE;
804 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
805 $this->_element
[$name] = 1;
806 $this->_tables
['civicrm_group'] = 1;
808 elseif ($name === 'notes') {
809 // if note field is subject then return subject else body of the note
810 $noteColumn = 'note';
811 if (isset($noteField) && $noteField == 'note_subject') {
812 $noteColumn = 'subject';
815 $this->_useGroupBy
= TRUE;
816 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
817 $this->_element
[$name] = 1;
818 $this->_tables
['civicrm_note'] = 1;
820 elseif ($name === 'current_employer') {
821 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
822 $this->_element
[$name] = 1;
827 CRM_Utils_Array
::value('is_search_range', $field)
829 // this is a custom field with range search enabled, so we better check for two/from values
830 if (CRM_Utils_Array
::value($name . '_from', $this->_paramLookup
)) {
831 if (!array_key_exists($cfID, $this->_cfIDs
)) {
832 $this->_cfIDs
[$cfID] = array();
834 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
835 // search in the cdID array for the same grouping
837 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
838 if ($c[3] == $p[3]) {
839 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
844 $p[2] = array('from' => $p[2]);
845 $this->_cfIDs
[$cfID][] = $p;
849 if (CRM_Utils_Array
::value($name . '_to', $this->_paramLookup
)) {
850 if (!array_key_exists($cfID, $this->_cfIDs
)) {
851 $this->_cfIDs
[$cfID] = array();
853 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
854 // search in the cdID array for the same grouping
856 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
857 if ($c[4] == $p[4]) {
858 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
863 $p[2] = array('to' => $p[2]);
864 $this->_cfIDs
[$cfID][] = $p;
871 // add location as hierarchical elements
872 $this->addHierarchicalElements();
874 // add multiple field like website
875 $this->addMultipleElements();
878 CRM_Core_Component
::alterQuery($this, 'select');
880 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
882 if (!empty($this->_cfIDs
)) {
883 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
884 $this->_customQuery
->query();
885 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
886 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
887 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
888 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
889 $this->_options
= $this->_customQuery
->_options
;
894 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
900 function addHierarchicalElements() {
901 if (!CRM_Utils_Array
::value('location', $this->_returnProperties
)) {
904 if (!is_array($this->_returnProperties
['location'])) {
908 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
909 $processed = array();
912 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
913 $addressCustomFieldIds = array();
915 foreach ($this->_returnProperties
['location'] as $name => $elements) {
916 $lCond = self
::getPrimaryCondition($name);
919 $locationTypeId = array_search($name, $locationTypes);
920 if ($locationTypeId === FALSE) {
923 $lCond = "location_type_id = $locationTypeId";
924 $this->_useDistinct
= TRUE;
926 //commented for CRM-3256
927 $this->_useGroupBy
= TRUE;
930 $name = str_replace(' ', '_', $name);
932 $tName = "$name-location_type";
933 $ltName = "`$name-location_type`";
934 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
935 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
936 $this->_element
["{$tName}_id"] = 1;
937 $this->_element
["{$tName}"] = 1;
939 $locationTypeName = $tName;
940 $locationTypeJoin = array();
944 foreach ($elements as $elementFullName => $dontCare) {
946 $elementName = $elementCmpName = $elementFullName;
948 if (substr($elementCmpName, 0, 5) == 'phone') {
949 $elementCmpName = 'phone';
952 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
953 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
954 $addressCustomFieldIds[$cfID][$name] = 1;
957 //add address table only once
958 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
960 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
962 $tName = "$name-address";
963 $aName = "`$name-address`";
964 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
965 $this->_element
["{$tName}_id"] = 1;
966 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
967 $this->_tables
[$tName] = $addressJoin;
968 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
969 $processed[$aName] = 1;
973 $cond = $elementType = '';
974 if (strpos($elementName, '-') !== FALSE) {
975 // this is either phone, email or IM
976 list($elementName, $elementType) = explode('-', $elementName);
979 if (($elementName != 'phone') && ($elementName != 'im')) {
980 $cond = self
::getPrimaryCondition($elementType);
982 // CRM-13011 : If location type is primary, do not restrict search to the phone
983 // type id - we want the primary phone, regardless of what type it is.
984 // Otherwise, restrict to the specified phone type for the given field.
985 if ((!$cond) && ($elementName == 'phone') && $elements['location_type'] != 'Primary') {
986 $cond = "phone_type_id = '$elementType'";
988 elseif ((!$cond) && ($elementName == 'im')) {
989 // IM service provider id, CRM-3140
990 $cond = "provider_id = '$elementType'";
992 $elementType = '-' . $elementType;
995 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
997 // hack for profile, add location id
1000 // fix for CRM-882( to handle phone types )
1001 !is_numeric($elementType)
1003 if (is_numeric($name)) {
1004 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1007 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1010 elseif (is_numeric($name)) {
1011 //this for phone type to work
1012 if (in_array($elementName, array('phone', 'phone_ext'))) {
1013 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1016 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1020 //this is for phone type to work for profile edit
1021 if (in_array($elementName, array('phone', 'phone_ext'))) {
1022 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1025 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1030 // Check if there is a value, if so also add to where Clause
1032 if ($this->_params
) {
1034 if (isset($locationTypeId)) {
1035 $nm .= "-$locationTypeId";
1037 if (!is_numeric($elementType)) {
1038 $nm .= "$elementType";
1041 foreach ($this->_params
as $id => $values) {
1042 if ($values[0] == $nm ||
1043 (in_array($elementName, array('phone', 'im'))
1044 && (strpos($values[0], $nm) !== FALSE)
1054 if ($field && isset($field['where'])) {
1055 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1056 $pf = substr($tableName, 8);
1057 $tName = $name . '-' . $pf . $elementType;
1058 if (isset($tableName)) {
1059 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1060 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1063 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1066 $this->_element
["{$tName}_id"] = 1;
1067 if (substr($tName, -15) == '-state_province') {
1068 // FIXME: hack to fix CRM-1900
1069 $a = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1073 if (substr_count($a, 'state_province_name') > 0) {
1074 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1075 array('pseudoField' => '{$pf}_id', 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1076 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1079 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1080 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id");
1081 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1085 if (substr($elementFullName, 0, 2) == 'im') {
1086 $provider = "{$name}-{$elementFullName}-provider_id";
1087 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1088 $this->_element
[$provider] = 1;
1090 if ($pf == 'country' ||
$pf == 'county') {
1091 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array('pseudoField' => "{$pf}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1092 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1095 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1099 if (in_array($pf, array('state_province', 'country', 'county'))) {
1100 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1103 $this->_element
["{$name}-{$elementFullName}"] = 1;
1106 if (!CRM_Utils_Array
::value("`$tName`", $processed)) {
1107 $processed["`$tName`"] = 1;
1108 $newName = $tableName . '_' . $index;
1109 switch ($tableName) {
1110 case 'civicrm_phone':
1111 case 'civicrm_email':
1113 case 'civicrm_openid':
1115 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id AND `$tName`.$lCond";
1116 // this special case to add phone type
1118 $phoneTypeCondition = " AND `$tName`.$cond ";
1119 //gross hack to pickup corrupted data also, CRM-7603
1120 if (strpos($cond, 'phone_type_id') !== FALSE) {
1121 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1123 $this->_tables
[$tName] .= $phoneTypeCondition;
1126 //build locationType join
1127 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1130 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1134 case 'civicrm_state_province':
1135 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1136 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1137 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1139 $this->_whereTables
["{$name}-address"] = $addressJoin;
1143 case 'civicrm_country':
1144 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1145 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1146 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1148 $this->_whereTables
["{$name}-address"] = $addressJoin;
1152 case 'civicrm_county':
1153 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1154 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1155 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1157 $this->_whereTables
["{$name}-address"] = $addressJoin;
1163 $this->_whereTables
["{$name}-address"] = $addressJoin;
1172 // add location type join
1173 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1174 $this->_tables
[$locationTypeName] = $ltypeJoin;
1176 // table should be present in $this->_whereTables,
1177 // to add its condition in location type join, CRM-3939.
1178 if ($addWhereCount) {
1179 $locClause = array();
1180 foreach ($this->_whereTables
as $tableName => $clause) {
1181 if (CRM_Utils_Array
::value($tableName, $locationTypeJoin)) {
1182 $locClause[] = $locationTypeJoin[$tableName];
1186 if (!empty($locClause)) {
1187 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1192 if (!empty($addressCustomFieldIds)) {
1193 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1194 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1195 foreach ($locTypeName as $name => $dnc) {
1196 $this->_locationSpecificCustomFields
[$cfID] = array($name, array_search($name, $locationTypes));
1197 $fieldName = "$name-custom_{$cfID}";
1198 $tName = "$name-address-custom-{$cfID}";
1199 $aName = "`$name-address-custom-{$cfID}`";
1200 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1201 $this->_element
["{$tName}_id"] = 1;
1202 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1203 $this->_element
[$fieldName] = 1;
1204 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1211 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
1217 function addMultipleElements() {
1218 if (!CRM_Utils_Array
::value('website', $this->_returnProperties
)) {
1221 if (!is_array($this->_returnProperties
['website'])) {
1225 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1226 foreach ($elements as $elementFullName => $dontCare) {
1227 $tName = "website-{$key}-{$elementFullName}";
1228 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1229 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1230 $this->_element
["{$tName}_id"] = 1;
1231 $this->_element
["{$tName}"] = 1;
1233 $type = "website-{$key}-website_type_id";
1234 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1235 $this->_element
[$type] = 1;
1236 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id )";
1242 * generate the query based on what type of query we need
1244 * @param boolean $count
1245 * @param boolean $sortByChar
1246 * @param boolean $groupContacts
1248 * @return the sql string for that query (this will most likely
1252 function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE) {
1254 if (isset($this->_distinctComponentClause
)) {
1255 // we add distinct to get the right count for components
1256 // for the more complex result set, we use GROUP BY the same id
1258 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1261 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1263 $from = $this->_simpleFromClause
;
1264 if ($this->_useDistinct
) {
1265 $this->_useGroupBy
= TRUE;
1268 elseif ($sortByChar) {
1269 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1270 $from = $this->_simpleFromClause
;
1272 elseif ($groupContacts) {
1273 $select = 'SELECT contact_a.id as id';
1274 if ($this->_useDistinct
) {
1275 $this->_useGroupBy
= TRUE;
1277 $from = $this->_simpleFromClause
;
1280 if (CRM_Utils_Array
::value('group', $this->_paramLookup
)) {
1281 // make sure there is only one element
1282 // this is used when we are running under smog and need to know
1283 // how the contact was added (CRM-1203)
1284 if ((count($this->_paramLookup
['group']) == 1) &&
1285 (count($this->_paramLookup
['group'][0][2]) == 1)
1287 $groups = array_keys($this->_paramLookup
['group'][0][2]);
1288 $groupId = $groups[0];
1290 //check if group is saved search
1291 $group = new CRM_Contact_BAO_Group();
1292 $group->id
= $groupId;
1295 if (!isset($group->saved_search_id
)) {
1296 $tbName = "`civicrm_group_contact-{$groupId}`";
1297 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1298 $this->_element
['group_contact_id'] = 1;
1299 $this->_select
['status'] = "$tbName.status as status";
1300 $this->_element
['status'] = 1;
1303 $this->_useGroupBy
= TRUE;
1305 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1306 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1308 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1309 $this->_useDistinct
= FALSE;
1310 $this->_useGroupBy
= TRUE;
1314 $select = "SELECT ";
1315 if (isset($this->_distinctComponentClause
)) {
1316 $select .= "{$this->_distinctComponentClause}, ";
1318 $select .= implode(', ', $this->_select
);
1319 $from = $this->_fromClause
;
1323 if (!empty($this->_whereClause
)) {
1324 $where = "WHERE {$this->_whereClause}";
1328 if (!empty($this->_having
)) {
1329 foreach ($this->_having
as $havingsets) {
1330 foreach ($havingsets as $havingset) {
1331 $havingvalue[] = $havingset;
1334 $having = ' HAVING ' . implode(' AND ', $havingvalue);
1337 // if we are doing a transform, do it here
1338 // use the $from, $where and $having to get the contact ID
1339 if ($this->_displayRelationshipType
) {
1340 $this->filterRelatedContacts($from, $where, $having);
1343 return array($select, $from, $where, $having);
1346 function &getWhereValues($name, $grouping) {
1348 foreach ($this->_params
as $values) {
1349 if ($values[0] == $name && $values[3] == $grouping) {
1357 static function fixDateValues($relative, &$from, &$to) {
1359 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1363 static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE) {
1365 if (empty($formValues)) {
1369 foreach ($formValues as $id => $values) {
1370 if ($id == 'privacy') {
1371 if (is_array($formValues['privacy'])) {
1372 $op = CRM_Utils_Array
::value('do_not_toggle', $formValues['privacy']) ?
'=' : '!=';
1373 foreach ($formValues['privacy'] as $key => $value) {
1375 $params[] = array($key, $op, $value, 0, 0);
1380 elseif ($id == 'email_on_hold') {
1381 if ($formValues['email_on_hold']['on_hold']) {
1382 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1385 elseif (preg_match('/_date_relative$/', $id) ||
1386 $id == 'event_relative' ||
1387 $id == 'case_from_relative' ||
1388 $id == 'case_to_relative'
1390 if ($id == 'event_relative') {
1391 $fromRange = 'event_start_date_low';
1392 $toRange = 'event_end_date_high';
1394 else if ($id == 'case_from_relative') {
1395 $fromRange = 'case_from_start_date_low';
1396 $toRange = 'case_from_start_date_high';
1398 else if ($id == 'case_to_relative') {
1399 $fromRange = 'case_to_end_date_low';
1400 $toRange = 'case_to_end_date_high';
1403 $dateComponent = explode('_date_relative', $id);
1404 $fromRange = "{$dateComponent[0]}_date_low";
1405 $toRange = "{$dateComponent[0]}_date_high";
1408 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1409 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1414 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals);
1419 $params[] = $values;
1425 static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE) {
1426 // skip a few search variables
1427 static $skipWhere = NULL;
1428 static $arrayValues = NULL;
1429 static $likeNames = NULL;
1432 if (CRM_Utils_System
::isNull($values)) {
1438 'task', 'radio_ts', 'uf_group_id',
1439 'component_mode', 'qfKey', 'operator',
1440 'display_relationship_type',
1444 if (in_array($id, $skipWhere) ||
1445 substr($id, 0, 4) == '_qf_' ||
1446 substr($id, 0, 7) == 'hidden_'
1452 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1455 // email comes in via advanced search
1456 // so use wildcard always
1457 if ($id == 'email') {
1461 if (!$useEquals && in_array($id, $likeNames)) {
1462 $result = array($id, 'LIKE', $values, 0, 1);
1464 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1465 $result = array($id, 'LIKE', $values, 0, 0);
1467 elseif ($id == 'group') {
1468 if (is_array($values)) {
1469 foreach ($values as $groupIds => $val) {
1471 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1472 if (strlen($matches[1]) > 0) {
1473 $values[$matches[1]] = 1;
1474 unset($values[$groupIds]);
1480 $groupIds = explode(',', $values);
1482 foreach ($groupIds as $groupId) {
1483 $values[$groupId] = 1;
1487 $result = array($id, 'IN', $values, 0, 0);
1489 elseif ($id == 'contact_tags' ||
$id == 'tag') {
1490 if (!is_array($values)) {
1491 $tagIds = explode(',', $values);
1493 foreach ($tagIds as $tagId) {
1494 $values[$tagId] = 1;
1497 $result = array($id, 'IN', $values, 0, 0);
1500 $result = array($id, '=', $values, 0, $wildcard);
1506 function whereClauseSingle(&$values) {
1507 // do not process custom fields or prefixed contact ids or component params
1508 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1509 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1510 (substr($values[0], 0, 13) == 'contribution_') ||
1511 (substr($values[0], 0, 6) == 'event_') ||
1512 (substr($values[0], 0, 12) == 'participant_') ||
1513 (substr($values[0], 0, 7) == 'member_') ||
1514 (substr($values[0], 0, 6) == 'grant_') ||
1515 (substr($values[0], 0, 7) == 'pledge_') ||
1516 (substr($values[0], 0, 5) == 'case_') ||
1517 (substr($values[0], 0, 10) == 'financial_') ||
1518 (substr($values[0], 0, 11) == 'membership_')
1523 // skip for hook injected fields / params
1524 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1525 if (array_key_exists($values[0], $extFields)) {
1529 switch ($values[0]) {
1530 case 'deleted_contacts':
1531 $this->deletedContacts($values);
1534 case 'contact_type':
1535 $this->contactType($values);
1538 case 'contact_sub_type':
1539 $this->contactSubType($values);
1543 $this->group($values);
1547 // so we resolve this into a list of groups & proceed as if they had been
1549 list($name, $op, $value, $grouping, $wildcard) = $values;
1550 $values[0] = 'group';
1552 $this->_paramLookup
['group'][0][0] ='group';
1553 $this->_paramLookup
['group'][0][1] = 'IN';
1554 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1555 $this->group($values);
1558 // case tag comes from find contacts
1560 $this->tagSearch($values);
1564 case 'contact_tags':
1565 $this->tag($values);
1570 case 'note_subject':
1571 $this->notes($values);
1575 $this->ufUser($values);
1579 case 'display_name':
1580 $this->sortName($values);
1584 $this->email($values);
1587 case 'phone_numeric':
1588 $this->phone_numeric($values);
1591 case 'phone_phone_type_id':
1592 case 'phone_location_type_id':
1593 $this->phone_option_group($values);
1596 case 'street_address':
1597 $this->street_address($values);
1600 case 'street_number':
1601 $this->street_number($values);
1604 case 'sortByCharacter':
1605 $this->sortByCharacter($values);
1608 case 'location_type':
1609 $this->locationType($values);
1613 $this->county($values);
1616 case 'state_province':
1617 $this->stateProvince($values);
1621 $this->country($values, FALSE);
1625 case 'postal_code_low':
1626 case 'postal_code_high':
1627 $this->postalCode($values);
1630 case 'activity_date':
1631 case 'activity_date_low':
1632 case 'activity_date_high':
1633 case 'activity_role':
1634 case 'activity_status':
1635 case 'activity_subject':
1636 case 'test_activities':
1637 case 'activity_type_id':
1638 case 'activity_type':
1639 case 'activity_survey_id':
1640 case 'activity_tags':
1641 case 'activity_taglist':
1642 case 'activity_test':
1643 case 'activity_campaign_id':
1644 case 'activity_engagement_level':
1646 case 'activity_result':
1647 case 'source_contact':
1648 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1651 case 'birth_date_low':
1652 case 'birth_date_high':
1653 case 'deceased_date_low':
1654 case 'deceased_date_high':
1655 $this->demographics($values);
1658 case 'log_date_low':
1659 case 'log_date_high':
1660 $this->modifiedDates($values);
1664 $this->changeLog($values);
1667 case 'do_not_phone':
1668 case 'do_not_email':
1671 case 'do_not_trade':
1673 $this->privacy($values);
1676 case 'privacy_options':
1677 $this->privacyOptions($values);
1680 case 'privacy_operator':
1681 case 'privacy_toggle':
1682 // these are handled by privacy options
1685 case 'preferred_communication_method':
1686 $this->preferredCommunication($values);
1689 case 'relation_type_id':
1690 case 'relation_start_date_high':
1691 case 'relation_start_date_low':
1692 case 'relation_end_date_high':
1693 case 'relation_end_date_low':
1694 case 'relation_target_name':
1695 case 'relation_status':
1696 case 'relation_date_low':
1697 case 'relation_date_high':
1698 $this->relationship($values);
1699 $this->_relationshipValuesAdded
= TRUE;
1702 case 'task_status_id':
1703 $this->task($values);
1707 // since this case is handled with the above
1710 case 'prox_distance':
1711 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1714 case 'prox_street_address':
1716 case 'prox_postal_code':
1717 case 'prox_state_province_id':
1718 case 'prox_country_id':
1719 // handled by the proximity_distance clause
1723 $this->restWhere($values);
1729 * Given a list of conditions in params generate the required
1735 function whereClause() {
1736 $this->_where
[0] = array();
1737 $this->_qill
[0] = array();
1739 $this->includeContactIds();
1740 if (!empty($this->_params
)) {
1741 foreach (array_keys($this->_params
) as $id) {
1742 if (!CRM_Utils_Array
::value(0, $this->_params
[$id])) {
1745 // check for both id and contact_id
1746 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
1748 $this->_params
[$id][1] == 'IS NULL' ||
1749 $this->_params
[$id][1] == 'IS NOT NULL'
1751 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]}";
1753 elseif (is_array($this->_params
[$id][2])) {
1754 $idList = implode("','", $this->_params
[$id][2]);
1755 //why on earth do they put ' in the middle & not on the outside? We have to assume it's
1756 //to support 'something' so lets add them conditionally to support the api (which is a tested flow
1757 // so if you are looking to alter this check api test results
1758 if(strpos(trim($idList), "'") > 0) {
1759 $idList = "'" . $idList . "'";
1762 $this->_where
[0][] = "contact_a.id IN ({$idList})";
1765 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]} {$this->_params[$id][2]}";
1769 $this->whereClauseSingle($this->_params
[$id]);
1773 CRM_Core_Component
::alterQuery($this, 'where');
1775 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
1778 if ($this->_customQuery
) {
1779 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1780 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1781 if (!empty($this->_customQuery
->_where
)) {
1782 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
1785 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
1789 $andClauses = array();
1792 if (!empty($this->_where
)) {
1793 foreach ($this->_where
as $grouping => $values) {
1794 if ($grouping > 0 && !empty($values)) {
1795 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1800 if (!empty($this->_where
[0])) {
1801 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
1803 if (!empty($clauses)) {
1804 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1807 if ($validClauses > 1) {
1808 $this->_useDistinct
= TRUE;
1812 return implode(' AND ', $andClauses);
1815 function restWhere(&$values) {
1816 $name = CRM_Utils_Array
::value(0, $values);
1817 $op = CRM_Utils_Array
::value(1, $values);
1818 $value = CRM_Utils_Array
::value(2, $values);
1819 $grouping = CRM_Utils_Array
::value(3, $values);
1820 $wildcard = CRM_Utils_Array
::value(4, $values);
1822 if (isset($grouping) && !CRM_Utils_Array
::value($grouping, $this->_where
)) {
1823 $this->_where
[$grouping] = array();
1826 $multipleFields = array('url');
1828 //check if the location type exits for fields
1830 $locType = explode('-', $name);
1832 if (!in_array($locType[0], $multipleFields)) {
1833 //add phone type if exists
1834 if (isset($locType[2]) && $locType[2]) {
1835 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
1839 $field = CRM_Utils_Array
::value($name, $this->_fields
);
1842 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
1851 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
1852 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1854 if (substr($name, 0, 14) === 'state_province') {
1855 if (isset($locType[1]) && is_numeric($locType[1])) {
1857 $aName = "{$locationType[$locType[1]]}-address";
1858 $where = "`$aName`.state_province_id";
1861 $where = "civicrm_address.state_province_id";
1864 $states = CRM_Core_PseudoConstant
::stateProvince();
1865 if (is_numeric($value)) {
1866 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1867 $value = $states[(int ) $value];
1870 $intVal = CRM_Utils_Array
::key($value, $states);
1871 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1874 $this->_qill
[$grouping][] = ts('State') . " $op '$value'";
1877 $this->_qill
[$grouping][] = ts('State') . " ($lType) $op '$value'";
1880 elseif (!empty($field['pseudoconstant'])) {
1881 $this->optionValueQuery(
1882 $name, $op, $value, $grouping,
1883 CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', $field['name']),
1889 if ($name == 'gender_id') {
1890 self
::$_openedPanes[ts('Demographics')] = TRUE;
1893 elseif (substr($name, 0, 7) === 'country') {
1894 if (isset($locType[1]) && is_numeric($locType[1])) {
1896 $aName = "{$locationType[$locType[1]]}-address";
1897 $where = "`$aName`.country_id";
1900 $where = "civicrm_address.country_id";
1903 $countries = CRM_Core_PseudoConstant
::country();
1904 if (is_numeric($value)) {
1905 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1906 $value = $countries[(int ) $value];
1909 $intVal = CRM_Utils_Array
::key($value, $countries);
1910 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1914 $this->_qill
[$grouping][] = ts('Country') . " $op '$value'";
1917 $this->_qill
[$grouping][] = ts('Country') . " ($lType) $op '$value'";
1920 elseif (substr($name, 0, 6) === 'county') {
1921 if (isset($locType[1]) && is_numeric($locType[1])) {
1923 $aName = "{$locationType[$locType[1]]}-address";
1924 $where = "`$aName`.county_id";
1927 $where = "civicrm_address.county_id";
1930 $counties = CRM_Core_PseudoConstant
::county();
1931 if (is_numeric($value)) {
1932 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1933 $value = $counties[(int ) $value];
1936 $intVal = CRM_Utils_Array
::key($value, $counties);
1937 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1941 $this->_qill
[$grouping][] = ts('County') . " $op '$value'";
1944 $this->_qill
[$grouping][] = ts('County') . " ($lType) $op '$value'";
1947 elseif ($name === 'world_region') {
1948 $this->optionValueQuery(
1949 $name, $op, $value, $grouping,
1950 CRM_Core_PseudoConstant
::worldRegion(),
1957 elseif ($name === 'birth_date') {
1958 $date = CRM_Utils_Date
::processDate($value);
1959 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
1962 $date = CRM_Utils_Date
::customFormat($date);
1963 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
1966 $this->_qill
[$grouping][] = "$field[title] $op";
1968 self
::$_openedPanes[ts('Demographics')] = TRUE;
1970 elseif ($name === 'deceased_date') {
1971 $date = CRM_Utils_Date
::processDate($value);
1972 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
1974 $date = CRM_Utils_Date
::customFormat($date);
1975 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
1978 $this->_qill
[$grouping][] = "$field[title] $op";
1980 self
::$_openedPanes[ts('Demographics')] = TRUE;
1982 elseif ($name === 'is_deceased') {
1983 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
1984 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
1985 self
::$_openedPanes[ts('Demographics')] = TRUE;
1987 elseif ($name === 'contact_id') {
1988 if (is_int($value)) {
1989 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
1990 $this->_qill
[$grouping][] = "$field[title] $op $value";
1993 elseif ($name === 'name') {
1994 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
1996 $value = "%$value%";
1999 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2000 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2001 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2003 elseif ($name === 'current_employer') {
2004 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2006 $value = "%$value%";
2009 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
2010 $ceWhereClause = self
::buildClause($wc, $op,
2013 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2014 $this->_where
[$grouping][] = $ceWhereClause;
2015 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2017 elseif ($name === 'email_greeting') {
2018 $filterCondition = array('greeting_type' => 'email_greeting');
2019 $this->optionValueQuery(
2020 $name, $op, $value, $grouping,
2021 CRM_Core_PseudoConstant
::greeting($filterCondition),
2023 ts('Email Greeting')
2026 elseif ($name === 'postal_greeting') {
2027 $filterCondition = array('greeting_type' => 'postal_greeting');
2028 $this->optionValueQuery(
2029 $name, $op, $value, $grouping,
2030 CRM_Core_PseudoConstant
::greeting($filterCondition),
2032 ts('Postal Greeting')
2035 elseif ($name === 'addressee') {
2036 $filterCondition = array('greeting_type' => 'addressee');
2037 $this->optionValueQuery(
2038 $name, $op, $value, $grouping,
2039 CRM_Core_PseudoConstant
::greeting($filterCondition),
2044 elseif (substr($name, 0, 4) === 'url-') {
2045 $tName = 'civicrm_website';
2046 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2047 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2049 $value = "%$value%";
2053 $wc = 'civicrm_website.url';
2054 $this->_where
[$grouping][] = $d = self
::buildClause($wc, $op, $value);
2055 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2057 elseif ($name === 'contact_is_deleted') {
2058 $this->_where
[$grouping][] = self
::buildClause("contact_a.is_deleted", $op, $value);
2059 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2062 // sometime the value is an array, need to investigate and fix
2063 if (is_array($value)) {
2064 CRM_Core_Error
::fatal();
2067 if (!empty($field['where'])) {
2069 $value = $strtolower($value);
2072 $value = "%$value%";
2076 if (isset($locType[1]) &&
2077 is_numeric($locType[1])
2081 //get the location name
2082 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2084 $where = "`$tName`.$fldName";
2086 $this->_where
[$grouping][] = self
::buildClause("LOWER($where)", $op, $value);
2087 $this->_whereTables
[$tName] = $this->_tables
[$tName];
2088 $this->_qill
[$grouping][] = "$field[title] $op '$value'";
2091 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2092 if ($tableName == 'civicrm_contact') {
2093 $fieldName = "LOWER(contact_a.{$fieldName})";
2096 if ($op != 'IN' && !is_numeric($value)) {
2097 $fieldName = "LOWER({$field['where']})";
2100 $fieldName = "{$field['where']}";
2105 if (CRM_Utils_Array
::value('type', $field)) {
2106 $type = CRM_Utils_Type
::typeToString($field['type']);
2109 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2110 $this->_qill
[$grouping][] = "$field[title] $op $value";
2115 if ($setTables && isset($field['where'])) {
2116 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2117 if (isset($tableName)) {
2118 $this->_tables
[$tableName] = 1;
2119 $this->_whereTables
[$tableName] = 1;
2125 static function getLocationTableName(&$where, &$locType) {
2126 if (isset($locType[1]) && is_numeric($locType[1])) {
2127 list($tbName, $fldName) = explode(".", $where);
2129 //get the location name
2130 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2131 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2132 if (in_array($locType[0], $specialFields)) {
2133 //hack to fix / special handing for phone_ext
2134 if ($locType[0] == 'phone_ext') {
2135 $locType[0] = 'phone';
2137 if (isset($locType[2]) && $locType[2]) {
2138 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2141 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2144 elseif (in_array($locType[0],
2146 'address_name', 'street_address', 'supplemental_address_1', 'supplemental_address_2',
2147 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
2150 //fix for search by profile with address fields.
2151 $tName = "{$locationType[$locType[1]]}-address";
2153 elseif ($locType[0] == 'on_hold') {
2154 $tName = "{$locationType[$locType[1]]}-email";
2157 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2159 $tName = str_replace(' ', '_', $tName);
2160 return array($tName, $fldName);
2162 CRM_Core_Error
::fatal();
2166 * Given a result dao, extract the values and return that array
2168 * @param Object $dao
2170 * @return array values for this query
2172 function store($dao) {
2175 foreach ($this->_element
as $key => $dontCare) {
2176 if (property_exists($dao, $key)) {
2177 if (strpos($key, '-') !== FALSE) {
2178 $values = explode('-', $key);
2179 $lastElement = array_pop($values);
2181 $cnt = count($values);
2183 foreach ($values as $v) {
2184 if (!array_key_exists($v, $current)) {
2185 $current[$v] = array();
2187 //bad hack for im_provider
2188 if ($lastElement == 'provider_id') {
2189 if ($count < $cnt) {
2190 $current = &$current[$v];
2193 $lastElement = "{$v}_{$lastElement}";
2197 $current = &$current[$v];
2202 $current[$lastElement] = $dao->$key;
2205 $value[$key] = $dao->$key;
2213 * getter for tables array
2219 return $this->_tables
;
2222 function whereTables() {
2223 return $this->_whereTables
;
2227 * generate the where clause (used in match contacts and permissions)
2229 * @param array $params
2230 * @param array $fields
2231 * @param array $tables
2232 * @param boolean $strict
2238 static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2239 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2243 $tables = array_merge($query->tables(), $tables);
2244 $whereTables = array_merge($query->whereTables(), $whereTables);
2246 return $query->_whereClause
;
2250 * create the from clause
2252 * @param array $tables tables that need to be included in this from clause
2253 * if null, return mimimal from clause (i.e. civicrm_contact)
2254 * @param array $inner tables that should be inner-joined
2255 * @param array $right tables that should be right-joined
2257 * @return string the from clause
2261 static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2263 $from = ' FROM civicrm_contact contact_a';
2264 if (empty($tables)) {
2268 if (CRM_Utils_Array
::value('civicrm_worldregion', $tables)) {
2269 $tables = array_merge(array('civicrm_country' => 1), $tables);
2272 if ((CRM_Utils_Array
::value('civicrm_state_province', $tables) ||
2273 CRM_Utils_Array
::value('civicrm_country', $tables) ||
2274 CRM_Utils_Array
::value('civicrm_county', $tables)
2276 !CRM_Utils_Array
::value('civicrm_address', $tables)
2278 $tables = array_merge(array('civicrm_address' => 1),
2283 // add group_contact table if group table is present
2284 if (CRM_Utils_Array
::value('civicrm_group', $tables) &&
2285 !CRM_Utils_Array
::value('civicrm_group_contact', $tables)
2287 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
2290 // add group_contact and group table is subscription history is present
2291 if (CRM_Utils_Array
::value('civicrm_subscription_history', $tables)
2292 && !CRM_Utils_Array
::value('civicrm_group', $tables)
2294 $tables = array_merge(array(
2295 'civicrm_group' => 1,
2296 'civicrm_group_contact' => 1,
2302 // to handle table dependencies of components
2303 CRM_Core_Component
::tableNames($tables);
2304 // to handle table dependencies of hook injected tables
2305 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2307 //format the table list according to the weight
2308 $info = CRM_Core_TableHierarchy
::info();
2310 foreach ($tables as $key => $value) {
2312 if (strpos($key, '-') !== FALSE) {
2313 $keyArray = explode('-', $key);
2314 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2316 elseif (strpos($key, '_') !== FALSE) {
2317 $keyArray = explode('_', $key);
2318 if (is_numeric(array_pop($keyArray))) {
2319 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2322 $k = CRM_Utils_Array
::value($key, $info, 99);
2326 $k = CRM_Utils_Array
::value($key, $info, 99);
2328 $tempTable[$k . ".$key"] = $key;
2331 $newTables = array();
2332 foreach ($tempTable as $key) {
2333 $newTables[$key] = $tables[$key];
2336 $tables = $newTables;
2338 foreach ($tables as $name => $value) {
2343 if (CRM_Utils_Array
::value($name, $inner)) {
2346 elseif (CRM_Utils_Array
::value($name, $right)) {
2354 // if there is already a join statement in value, use value itself
2355 if (strpos($value, 'JOIN')) {
2356 $from .= " $value ";
2359 $from .= " $side JOIN $name ON ( $value ) ";
2364 case 'civicrm_address':
2365 if ($primaryLocation) {
2366 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2369 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2373 case 'civicrm_phone':
2374 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2377 case 'civicrm_email':
2378 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2382 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2386 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2387 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2388 $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)";
2391 case 'civicrm_openid':
2392 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2395 case 'civicrm_worldregion':
2396 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2397 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2400 case 'civicrm_location_type':
2401 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2404 case 'civicrm_group':
2405 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2408 case 'civicrm_group_contact':
2409 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2412 case 'civicrm_activity':
2413 case 'civicrm_activity_tag':
2414 case 'activity_type':
2415 case 'activity_status':
2416 case 'civicrm_activity_contact':
2417 case 'source_contact':
2418 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2421 case 'civicrm_entity_tag':
2422 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2423 civicrm_entity_tag.entity_id = contact_a.id ) ";
2426 case 'civicrm_note':
2427 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2428 contact_a.id = civicrm_note.entity_id ) ";
2431 case 'civicrm_subscription_history':
2432 $from .= " $side JOIN civicrm_subscription_history
2433 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2434 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2437 case 'civicrm_relationship':
2438 if (self
::$_relType == 'reciprocal') {
2439 if(self
::$_relationshipTempTable) {
2440 // we have a temptable to join on
2441 $tbl = self
::$_relationshipTempTable;
2442 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2445 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2446 $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)";
2449 elseif (self
::$_relType == 'b') {
2450 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2451 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2454 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2455 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2460 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2461 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2465 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2468 case 'civicrm_grant':
2469 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2472 case 'civicrm_website':
2473 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2477 $from .= CRM_Core_Component
::from($name, $mode, $side);
2478 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2488 * WHERE / QILL clause for deleted_contacts
2492 function deletedContacts($values) {
2493 list($_, $_, $value, $grouping, $_) = $values;
2495 // *prepend* to the relevant grouping as this is quite an important factor
2496 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2501 * where / qill clause for contact_type
2506 function contactType(&$values) {
2507 list($name, $op, $value, $grouping, $wildcard) = $values;
2509 $subTypes = array();
2512 // account for search builder mapping multiple values
2513 if (!is_array($value)) {
2514 $values = self
::parseSearchBuilderString($value, 'String');
2515 if (is_array($values)) {
2516 $value = array_flip($values);
2520 if (is_array($value)) {
2521 foreach ($value as $k => $v) {
2526 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2527 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2530 if (!empty($subType)) {
2531 $subTypes[$subType] = 1;
2533 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2538 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2539 $contactType = $contactTypeANDSubType[0];
2540 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2541 if (!empty($subType)) {
2542 $subTypes[$subType] = 1;
2544 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2548 if (!empty($clause)) {
2549 if ($op == 'IN' ||
$op == 'NOT IN') {
2550 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2554 $type = array_pop($clause);
2555 $this->_where
[$grouping][] = "contact_a.contact_type $op $type";
2558 $this->_qill
[$grouping][] = ts('Contact Type') . ' - ' . implode(' ' . ts('or') . ' ', $quill);
2560 if (!empty($subTypes)) {
2561 $this->includeContactSubTypes($subTypes, $grouping);
2567 * where / qill clause for contact_sub_type
2572 function contactSubType(&$values) {
2573 list($name, $op, $value, $grouping, $wildcard) = $values;
2574 $this->includeContactSubTypes($value, $grouping);
2577 function includeContactSubTypes($value, $grouping) {
2580 $alias = "contact_a.contact_sub_type";
2582 if (is_array($value)) {
2583 foreach ($value as $k => $v) {
2585 $clause[$k] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($k, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2590 $clause[$value] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2593 if (!empty($clause)) {
2594 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2595 $this->_qill
[$grouping][] = ts('Contact Subtype') . ' - ' . implode(' ' . ts('or') . ' ', array_keys($clause));
2600 * where / qill clause for groups
2605 function group(&$values) {
2606 list($name, $op, $value, $grouping, $wildcard) = $values;
2608 if (count($value) > 1) {
2609 $this->_useDistinct
= TRUE;
2612 $groupNames = CRM_Core_PseudoConstant
::group();
2613 $groupIds = implode(',', array_keys($value));
2616 foreach ($value as $id => $dontCare) {
2617 if (array_key_exists($id, $groupNames) && $dontCare) {
2618 $names[] = $groupNames[$id];
2624 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2626 is_array($gcsValues[2])
2628 foreach ($gcsValues[2] as $k => $v) {
2630 if ($k == 'Added') {
2633 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2638 $statii[] = '"Added"';
2643 if (count($value) == 1 &&
2644 count($statii) == 1 &&
2645 $statii[0] == '"Added"'
2647 // check if smart group, if so we can get rid of that one additional
2649 $groupIDs = array_keys($value);
2651 if (CRM_Utils_Array
::value(0, $groupIDs) &&
2652 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
2662 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2663 $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 ) )";
2666 $qill = ts('Contacts %1', array(1 => $op));
2667 $qill .= ' ' . implode(' ' . ts('or') . ' ', $names);
2669 $groupClause = NULL;
2672 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2673 if (!empty($statii)) {
2674 $groupClause .= " AND {$gcTable}.status IN (" . implode(', ', $statii) . ")";
2675 $qill .= " " . ts('AND') . " " . ts('Group Status') . ' - ' . implode(' ' . ts('or') . ' ', $statii);
2680 $ssClause = $this->savedSearch($values);
2683 $groupClause = "( ( $groupClause ) OR ( $ssClause ) )";
2686 $groupClause = $ssClause;
2691 $this->_where
[$grouping][] = $groupClause;
2692 $this->_qill
[$grouping][] = $qill;
2695 * Function translates selection of group type into a list of groups
2697 function getGroupsFromTypeCriteria($value){
2698 $groupIds = array();
2699 foreach ($value as $groupTypeValue) {
2700 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2701 $groupIds = ($groupIds +
$groupList);
2707 * where / qill clause for smart groups
2712 function savedSearch(&$values) {
2713 list($name, $op, $value, $grouping, $wildcard) = $values;
2714 return $this->addGroupContactCache(array_keys($value));
2717 function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
2718 $config = CRM_Core_Config
::singleton();
2720 // find all the groups that are part of a saved search
2721 $groupIDs = implode(',', $groups);
2722 if (empty($groupIDs)) {
2727 SELECT id, cache_date, saved_search_id, children
2729 WHERE id IN ( $groupIDs )
2730 AND ( saved_search_id != 0
2731 OR saved_search_id IS NOT NULL
2732 OR children IS NOT NULL )
2734 $group = CRM_Core_DAO
::executeQuery($sql);
2736 while ($group->fetch()) {
2737 if ($tableAlias == NULL) {
2738 $alias = "`civicrm_group_contact_cache_{$group->id}`";
2741 $alias = $tableAlias;
2744 $this->_useDistinct
= TRUE;
2746 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
2747 CRM_Contact_BAO_GroupContactCache
::load($group);
2750 $this->_tables
[$alias] = $this->_whereTables
[$alias] = " LEFT JOIN civicrm_group_contact_cache {$alias} ON {$joinTable}.id = {$alias}.contact_id ";
2751 $ssWhere[] = "{$alias}.group_id = {$group->id}";
2754 if (!empty($ssWhere)) {
2755 return implode(' OR ', $ssWhere);
2761 * where / qill clause for cms users
2766 function ufUser(&$values) {
2767 list($name, $op, $value, $grouping, $wildcard) = $values;
2770 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2772 $this->_qill
[$grouping][] = ts('CMS User');
2774 elseif ($value == 0) {
2775 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2777 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2778 $this->_qill
[$grouping][] = ts('Not a CMS User');
2783 * all tag search specific
2788 function tagSearch(&$values) {
2789 list($name, $op, $value, $grouping, $wildcard) = $values;
2792 $value = "%{$value}%";
2795 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2796 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2798 $etTable = "`civicrm_entity_tag-" . $value . "`";
2799 $tTable = "`civicrm_tag-" . $value . "`";
2801 if ($useAllTagTypes[2]) {
2802 $this->_tables
[$etTable] =
2803 $this->_whereTables
[$etTable] =
2804 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
2805 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
2807 // search tag in cases
2808 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2809 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
2810 $this->_tables
[$etCaseTable] =
2811 $this->_whereTables
[$etCaseTable] =
2812 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2813 LEFT JOIN civicrm_case
2814 ON (civicrm_case_contact.case_id = civicrm_case.id
2815 AND civicrm_case.is_deleted = 0 )
2816 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
2817 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
2818 // search tag in activities
2819 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2820 $tActTable = "`civicrm_act_tag-" . $value . "`";
2821 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2822 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2824 $this->_tables
[$etActTable] =
2825 $this->_whereTables
[$etActTable] =
2826 " LEFT JOIN civicrm_activity_contact
2827 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
2828 LEFT JOIN civicrm_activity
2829 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
2830 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2831 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
2832 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
2834 $this->_where
[$grouping][] = "({$tTable}.name $op '". $value . "' OR {$tCaseTable}.name $op '". $value . "' OR {$tActTable}.name $op '". $value . "')";
2835 $this->_qill
[$grouping][] = ts('Tag %1 %2 ', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
2837 $etTable = "`civicrm_entity_tag-" . $value . "`";
2838 $tTable = "`civicrm_tag-" . $value . "`";
2839 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
2840 {$etTable}.entity_table = 'civicrm_contact' )
2841 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
2843 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
2844 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
2849 * where / qill clause for tag
2854 function tag(&$values) {
2855 list($name, $op, $value, $grouping, $wildcard) = $values;
2857 $tagNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
2858 if (is_array($value)) {
2859 if (count($value) > 1) {
2860 $this->_useDistinct
= TRUE;
2862 foreach ($value as $id => $dontCare) {
2863 $names[] = CRM_Utils_Array
::value($id, $tagNames);
2865 $names = implode(' ' . ts('or') . ' ', $names);
2866 $value = implode(',', array_keys($value));
2869 $names = CRM_Utils_Array
::value($value, $tagNames);
2873 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2874 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2876 $etTable = "`civicrm_entity_tag-" . $value . "`";
2878 if ($useAllTagTypes[2]) {
2879 $this->_tables
[$etTable] =
2880 $this->_whereTables
[$etTable] =
2881 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2883 // search tag in cases
2884 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2885 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2886 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2888 $this->_tables
[$etCaseTable] =
2889 $this->_whereTables
[$etCaseTable] =
2890 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2891 LEFT JOIN civicrm_case
2892 ON (civicrm_case_contact.case_id = civicrm_case.id
2893 AND civicrm_case.is_deleted = 0 )
2894 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
2895 // search tag in activities
2896 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2897 $this->_tables
[$etActTable] =
2898 $this->_whereTables
[$etActTable] =
2899 " LEFT JOIN civicrm_activity_contact
2900 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
2901 LEFT JOIN civicrm_activity
2902 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
2903 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2904 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
2907 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
2908 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
2911 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (". $value . ") OR {$etCaseTable}.tag_id $op (". $value . ") OR {$etActTable}.tag_id $op (". $value . "))";
2913 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
2915 $this->_tables
[$etTable] =
2916 $this->_whereTables
[$etTable] =
2917 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2920 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
2921 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
2922 $op = str_replace('EMPTY', 'NULL', $op);
2923 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
2926 $this->_where
[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
2928 $this->_qill
[$grouping][] = ts('Tagged %1', array( 1 => $op)) . ' ' . $names;
2934 * where/qill clause for notes
2939 function notes(&$values) {
2940 list($name, $op, $value, $grouping, $wildcard) = $values;
2942 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
2943 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
2944 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
2946 $this->_useDistinct
= TRUE;
2948 $this->_tables
['civicrm_note'] =
2949 $this->_whereTables
['civicrm_note'] =
2950 " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
2952 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2954 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
2955 if ($wildcard ||
$op == 'LIKE') {
2956 if (strpos($value, '%') === FALSE) {
2957 $value = "%$value%";
2961 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
2967 if ( $noteOption %
2 == 0 ) {
2968 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
2969 $label = ts('Note: Body Only');
2971 if ( $noteOption %
3 == 0 ) {
2972 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
2973 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
2975 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
2976 $this->_qill
[$grouping][] = $label . " $op - '$n'";
2979 function nameNullOrEmptyOp($name, $op, $grouping) {
2983 $this->_where
[$grouping][] = "contact_a.$name $op";
2984 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
2988 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
2989 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
2992 case 'IS NOT EMPTY':
2993 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
2994 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3003 * where / qill clause for sort_name
3008 function sortName(&$values) {
3009 list($name, $op, $value, $grouping, $wildcard) = $values;
3011 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3012 if ( $this->nameNullOrEmptyOp( $name, $op, $grouping ) ) {
3017 $name = trim($value);
3023 $config = CRM_Core_Config
::singleton();
3027 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3030 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3031 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3033 if (substr($name, 0, 1) == '"' &&
3034 substr($name, -1, 1) == '"'
3036 //If name is encased in double quotes, the value should be taken to be the string in entirety and the
3037 $value = substr($name, 1, -1);
3038 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
3039 $wc = ($newName == 'sort_name') ?
'LOWER(contact_a.sort_name)' : 'LOWER(contact_a.display_name)';
3040 $sub[] = " ( $wc = '$value' ) ";
3041 if ($config->includeEmailInName
) {
3042 $sub[] = " ( civicrm_email.email = '$value' ) ";
3045 elseif (strpos($name, ',') !== FALSE) {
3046 // if we have a comma in the string, search for the entire string
3047 $value = $strtolower(CRM_Core_DAO
::escapeString($name));
3049 if ($config->includeWildCardInName
) {
3050 $value = "'%$value%'";
3053 $value = "'$value%'";
3058 $value = "'$value'";
3060 if ($newName == 'sort_name') {
3061 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3064 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3066 $sub[] = " ( $wc $op $value )";
3067 if ($config->includeNickNameInName
) {
3068 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3069 $sub[] = " ( $wc $op $value )";
3071 if ($config->includeEmailInName
) {
3072 $sub[] = " ( civicrm_email.email $op $value ) ";
3076 // the string should be treated as a series of keywords to be matched with match ANY OR
3077 // match ALL depending on Civi config settings (see CiviAdmin)
3079 // The Civi configuration setting can be overridden if the string *starts* with the case
3080 // insenstive strings 'AND:' or 'OR:'TO THINK ABOUT: what happens when someone searches
3081 // for the following "AND: 'a string in quotes'"? - probably nothing - it would make the
3082 // AND OR variable reduntant because there is only one search string?
3084 // Check to see if the $subGlue is overridden in the search text
3085 if (strtolower(substr($name, 0, 4)) == 'and:') {
3086 $name = substr($name, 4);
3089 if (strtolower(substr($name, 0, 3)) == 'or:') {
3090 $name = substr($name, 3);
3094 $firstChar = substr($name, 0, 1);
3095 $lastChar = substr($name, -1, 1);
3096 $quotes = array("'", '"');
3097 if ((strlen($name) > 2) && in_array($firstChar, $quotes) &&
3098 in_array($lastChar, $quotes)
3100 $name = substr($name, 1);
3101 $name = substr($name, 0, -1);
3102 $pieces = array($name);
3105 $pieces = explode(' ', $name);
3107 foreach ($pieces as $piece) {
3108 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($piece)));
3109 if (strlen($value)) {
3110 // Added If as a sanitization - without it, when you do an OR search, any string with
3111 // double spaces (i.e. " ") or that has a space after the keyword (e.g. "OR: ") will
3112 // return all contacts because it will include a condition similar to "OR contact
3113 // name LIKE '%'". It might be better to replace this with array_filter.
3114 $fieldsub = array();
3116 if ($config->includeWildCardInName
) {
3117 $value = "'%$value%'";
3120 $value = "'$value%'";
3125 $value = "'$value'";
3127 if ($newName == 'sort_name') {
3128 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3131 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3133 $fieldsub[] = " ( $wc $op $value )";
3134 if ($config->includeNickNameInName
) {
3135 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3136 $fieldsub[] = " ( $wc $op $value )";
3138 if ($config->includeEmailInName
) {
3139 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3141 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3142 // I seperated the glueing in two. The first stage should always be OR because we are searching for matches in *ANY* of these fields
3147 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3149 $this->_where
[$grouping][] = $sub;
3150 if ($config->includeEmailInName
) {
3151 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3152 $this->_qill
[$grouping][] = ts('Name or Email ') . "$op - '$name'";
3155 $this->_qill
[$grouping][] = ts('Name like') . " - '$name'";
3160 * where / qill clause for email
3165 function email(&$values) {
3166 list($name, $op, $value, $grouping, $wildcard) = $values;
3170 $config = CRM_Core_Config
::singleton();
3172 if (substr($n, 0, 1) == '"' &&
3173 substr($n, -1, 1) == '"'
3175 $n = substr($n, 1, -1);
3176 $value = strtolower(CRM_Core_DAO
::escapeString($n));
3177 $value = "'$value'";
3181 $value = strtolower($n);
3183 if (strpos($value, '%') === FALSE) {
3184 $value = "%{$value}%";
3189 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3190 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3193 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3194 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3197 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3201 * where / qill clause for phone number
3206 function phone_numeric(&$values) {
3207 list($name, $op, $value, $grouping, $wildcard) = $values;
3208 // Strip non-numeric characters; allow wildcards
3209 $number = preg_replace('/[^\d%]/', '', $value);
3211 if ( strpos($number, '%') === FALSE ) {
3212 $number = "%$number%";
3215 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3216 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3217 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3222 * where / qill clause for phone type/location
3227 function phone_option_group($values) {
3228 list($name, $op, $value, $grouping, $wildcard) = $values;
3229 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3230 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3231 $optionName = $options[$value];
3232 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3233 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3234 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3238 * where / qill clause for street_address
3243 function street_address(&$values) {
3244 list($name, $op, $value, $grouping, $wildcard) = $values;
3253 $value = strtolower($n);
3254 if (strpos($value, '%') === FALSE) {
3255 // only add wild card if not there
3256 $value = "%{$value}%";
3259 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3260 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3263 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3264 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3267 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3271 * where / qill clause for street_unit
3276 function street_number(&$values) {
3277 list($name, $op, $value, $grouping, $wildcard) = $values;
3285 if (strtolower($n) == 'odd') {
3286 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3287 $this->_qill
[$grouping][] = ts('Street Number is odd');
3289 elseif (strtolower($n) == 'even') {
3290 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3291 $this->_qill
[$grouping][] = ts('Street Number is even');
3294 $value = strtolower($n);
3296 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3297 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3300 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3304 * where / qill clause for sorting by character
3309 function sortByCharacter(&$values) {
3310 list($name, $op, $value, $grouping, $wildcard) = $values;
3312 $name = trim($value);
3313 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3314 $this->_where
[$grouping][] = $cond;
3315 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3319 * where / qill clause for including contact ids
3324 function includeContactIDs() {
3325 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3329 $contactIds = array();
3330 foreach ($this->_params
as $id => $values) {
3331 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3332 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3335 if (!empty($contactIds)) {
3336 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3341 * where / qill clause for postal code
3346 function postalCode(&$values) {
3347 // skip if the fields dont have anything to do with postal_code
3348 if (!CRM_Utils_Array
::value('postal_code', $this->_fields
)) {
3352 list($name, $op, $value, $grouping, $wildcard) = $values;
3354 // Handle numeric postal code range searches properly by casting the column as numeric
3355 if (is_numeric($value)) {
3356 $field = 'ROUND(civicrm_address.postal_code)';
3357 $val = CRM_Utils_Type
::escape($value, 'Integer');
3360 $field = 'civicrm_address.postal_code';
3361 $val = CRM_Utils_Type
::escape($value, 'String');
3364 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3366 if ($name == 'postal_code') {
3367 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3368 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3370 elseif ($name == 'postal_code_low') {
3371 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3372 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3374 elseif ($name == 'postal_code_high') {
3375 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3376 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3381 * where / qill clause for location type
3386 function locationType(&$values, $status = NULL) {
3387 list($name, $op, $value, $grouping, $wildcard) = $values;
3389 if (is_array($value)) {
3390 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', array_keys($value)) . ')';
3391 $this->_tables
['civicrm_address'] = 1;
3392 $this->_whereTables
['civicrm_address'] = 1;
3394 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3396 foreach (array_keys($value) as $id) {
3397 $names[] = $locationType[$id];
3400 $this->_primaryLocation
= FALSE;
3403 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3406 return implode(' ' . ts('or') . ' ', $names);
3411 function country(&$values, $fromStateProvince = TRUE) {
3412 list($name, $op, $value, $grouping, $wildcard) = $values;
3414 if (!$fromStateProvince) {
3415 $stateValues = $this->getWhereValues('state_province', $grouping);
3416 if (!empty($stateValues)) {
3417 // return back to caller if there are state province values
3418 // since that handles this case
3423 $countryClause = $countryQill = NULL;
3429 $this->_tables
['civicrm_address'] = 1;
3430 $this->_whereTables
['civicrm_address'] = 1;
3432 $countries = CRM_Core_PseudoConstant
::country();
3433 if (is_numeric($value)) {
3434 $countryClause = self
::buildClause(
3435 'civicrm_address.country_id',
3440 $countryName = $countries[(int ) $value];
3444 $intValues = self
::parseSearchBuilderString($value);
3445 if ($intValues && ($op == 'IN' ||
$op == 'NOT IN')) {
3446 $countryClause = self
::buildClause(
3447 'civicrm_address.country_id',
3452 $countryNames = array();
3453 foreach ($intValues as $v) {
3454 $countryNames[] = $countries[$v];
3456 $countryName = implode(',', $countryNames);
3459 $countries = CRM_Core_PseudoConstant
::country();
3460 $intVal = CRM_Utils_Array
::key($value, $countries);
3461 $countryClause = self
::buildClause(
3462 'civicrm_address.country_id',
3467 $countryName = $value;
3470 $countryQill = ts('Country') . " {$op} '$countryName'";
3472 if (!$fromStateProvince) {
3473 $this->_where
[$grouping][] = $countryClause;
3474 $this->_qill
[$grouping][] = $countryQill;
3478 if ($fromStateProvince) {
3479 if (!empty($countryClause)) {
3482 " ...AND... " . $countryQill,
3486 return array(NULL, NULL);
3492 * where / qill clause for county (if present)
3497 function county(&$values, $status = null) {
3498 list($name, $op, $value, $grouping, $wildcard) = $values;
3500 if (! is_array($value)) {
3501 // force the county to be an array
3502 $value = array($value);
3505 // check if the values are ids OR names of the counties
3506 $inputFormat = 'id';
3507 foreach ($value as $v) {
3508 if (!is_numeric($v)) {
3509 $inputFormat = 'name';
3517 else if ($op == '!=') {
3521 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3522 $op = str_replace('EMPTY', 'NULL', $op);
3525 if (in_array( $op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3526 $clause = "civicrm_address.county_id $op";
3528 elseif ($inputFormat == 'id') {
3529 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3531 $county = CRM_Core_PseudoConstant
::county();
3532 foreach ($value as $id) {
3533 $names[] = CRM_Utils_Array
::value($id, $county);
3537 $inputClause = array();
3538 $county = CRM_Core_PseudoConstant
::county();
3539 foreach ($value as $name) {
3540 $name = trim($name);
3541 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3543 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3546 $this->_tables
['civicrm_address'] = 1;
3547 $this->_whereTables
['civicrm_address'] = 1;
3549 $this->_where
[$grouping][] = $clause;
3551 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3553 return implode(' ' . ts('or') . ' ', $names);
3558 * where / qill clause for state/province AND country (if present)
3563 function stateProvince(&$values, $status = NULL) {
3564 list($name, $op, $value, $grouping, $wildcard) = $values;
3566 // quick escape for IS NULL
3567 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3570 else if (!is_array($value)) {
3571 // force the state to be an array
3572 // check if its in the mapper format!
3573 $values = self
::parseSearchBuilderString($value);
3574 if (is_array($values)) {
3578 $value = array($value);
3582 // check if the values are ids OR names of the states
3583 $inputFormat = 'id';
3585 foreach ($value as $v) {
3586 if (!is_numeric($v)) {
3587 $inputFormat = 'name';
3597 else if ($op == '!=') {
3601 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3602 $op = str_replace('EMPTY', 'NULL', $op);
3604 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3605 $stateClause = "civicrm_address.state_province_id $op";
3607 else if ($inputFormat == 'id') {
3608 if ($op != 'NOT IN') {
3611 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
3613 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3614 foreach ($value as $id) {
3615 $names[] = CRM_Utils_Array
::value($id, $stateProvince);
3619 $inputClause = array();
3620 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3621 foreach ($value as $name) {
3622 $name = trim($name);
3623 $inputClause[] = CRM_Utils_Array
::key($name, $stateProvince);
3625 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
3628 $this->_tables
['civicrm_address'] = 1;
3629 $this->_whereTables
['civicrm_address'] = 1;
3631 $countryValues = $this->getWhereValues('country', $grouping);
3632 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3634 if ($countryClause) {
3635 $clause = "( $stateClause AND $countryClause )";
3638 $clause = $stateClause;
3641 $this->_where
[$grouping][] = $clause;
3643 $this->_qill
[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3646 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
3651 * where / qill clause for change log
3656 function changeLog(&$values) {
3657 list($name, $op, $value, $grouping, $wildcard) = $values;
3659 $targetName = $this->getWhereValues('changed_by', $grouping);
3664 $name = trim($targetName[2]);
3665 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3666 $name = $targetName[4] ?
"%$name%" : $name;
3667 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3668 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3669 $this->_qill
[$grouping][] = ts('Modified by') . ": $name";
3672 function modifiedDates($values) {
3673 $this->_useDistinct
= TRUE;
3675 // CRM-11281, default to added date if not set
3676 $fieldTitle = ts('Added Date');
3677 $fieldName = 'created_date';
3678 foreach (array_keys($this->_params
) as $id) {
3679 if ($this->_params
[$id][0] == 'log_date') {
3680 if ($this->_params
[$id][2] == 2) {
3681 $fieldTitle = ts('Modified Date');
3682 $fieldName = 'modified_date';
3688 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3690 self
::$_openedPanes[ts('Change Log')] = TRUE;
3693 function demographics(&$values) {
3694 list($name, $op, $value, $grouping, $wildcard) = $values;
3696 if (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3698 $this->dateQueryBuilder($values,
3699 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3702 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3704 $this->dateQueryBuilder($values,
3705 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3709 self
::$_openedPanes[ts('Demographics')] = TRUE;
3712 function privacy(&$values) {
3713 list($name, $op, $value, $grouping, $wildcard) = $values;
3714 //fixed for profile search listing CRM-4633
3715 if (strpbrk($value, "[")) {
3716 $value = "'{$value}'";
3718 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3721 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3723 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3724 $title = $field ?
$field['title'] : $name;
3725 $this->_qill
[$grouping][] = "$title $op $value";
3728 function privacyOptions($values) {
3729 list($name, $op, $value, $grouping, $wildcard) = $values;
3731 if (empty($value) ||
!is_array($value)) {
3735 // get the operator and toggle values
3736 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3739 strtolower($opValues[2] == 'AND')
3744 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3746 if ($toggleValues &&
3747 $toggleValues[2] == 2
3754 foreach ($value as $dontCare => $pOption) {
3755 $clauses[] = " ( contact_a.{$pOption} $compareOP 1 ) ";
3756 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3757 $title = $field ?
$field['title'] : $pOption;
3758 $qill[] = " $title $compareOP 1 ";
3761 $this->_where
[$grouping][] = '( ' . implode($operator, $clauses) . ' )';
3762 $this->_qill
[$grouping][] = implode($operator, $qill);
3765 function preferredCommunication(&$values) {
3766 list($name, $op, $value, $grouping, $wildcard) = $values;
3769 if (in_array($op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3772 elseif (!is_array($value)) {
3774 $value = trim($value, ' ()');
3775 if (strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
3776 $v = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
3779 $v = explode(",", $value);
3782 foreach ($v as $item) {
3789 foreach ($value as $key => $checked) {
3796 $commPref = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
3798 $sqlValue = array();
3799 $showValue = array();
3800 $sql = "contact_a.preferred_communication_method";
3801 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3802 $sqlValue[] = "{$sql} {$op}";
3805 foreach ($pref as $val) {
3806 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $val . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' ) ";
3807 $showValue[] = $commPref[$val];
3810 $this->_where
[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
3811 $this->_qill
[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
3815 * where / qill clause for relationship
3820 function relationship(&$values) {
3821 list($name, $op, $value, $grouping, $wildcard) = $values;
3822 if($this->_relationshipValuesAdded
){
3825 // also get values array for relation_target_name
3826 // for relatinship search we always do wildcard
3827 $targetName = $this->getWhereValues('relation_target_name', $grouping);
3828 $relStatus = $this->getWhereValues('relation_status', $grouping);
3829 $relPermission = $this->getWhereValues('relation_permission', $grouping);
3830 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
3832 $nameClause = $name = NULL;
3834 $name = trim($targetName[2]);
3835 if (substr($name, 0, 1) == '"' &&
3836 substr($name, -1, 1) == '"'
3838 $name = substr($name, 1, -1);
3839 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3840 $nameClause = "= '$name'";
3843 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3844 $nameClause = "LIKE '%{$name}%'";
3848 $rel = explode('_', $value);
3850 self
::$_relType = $rel[1];
3851 $params = array('id' => $rel[0]);
3852 $rTypeValues = array();
3853 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
3854 if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
3855 // if we don't know which end of the relationship we are dealing with we'll create a temp table
3856 //@todo unless we are dealing with a target group
3857 self
::$_relType = 'reciprocal';
3859 // if we are creating a temp table we build our own where for the relationship table
3860 $relationshipTempTable = NULL;
3861 if(self
::$_relType == 'reciprocal' && empty($targetGroup)) {
3863 self
::$_relationshipTempTable =
3864 $relationshipTempTable =
3865 CRM_Core_DAO
::createTempTableName( 'civicrm_rel');
3867 $where[$grouping][] = " sort_name $nameClause ";
3871 $where = &$this->_where
;
3873 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
3878 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
3879 $relTypeOrg = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
3880 $relTypeHou = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Household');
3881 $allRelationshipType = array();
3882 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
3883 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
3885 if ($nameClause ||
!$targetGroup) {
3886 $this->_qill
[$grouping][] = "$allRelationshipType[$value] $name";
3890 //check to see if the target contact is in specified group
3892 //add contacts from static groups
3893 $this->_tables
['civicrm_relationship_group_contact'] =
3894 $this->_whereTables
['civicrm_relationship_group_contact'] =
3895 " 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'";
3897 "( civicrm_relationship_group_contact.group_id IN (" .
3898 implode(",", $targetGroup[2]) . ") ) ";
3900 //add contacts from saved searches
3901 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
3903 //set the group where clause
3905 $groupWhere[] = "( " . $ssWhere . " )";
3907 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
3909 //Get the names of the target groups for the qill
3910 $groupNames = CRM_Core_PseudoConstant
::group();
3911 $qillNames = array();
3912 foreach ($targetGroup[2] as $groupId) {
3913 if (array_key_exists($groupId, $groupNames)) {
3914 $qillNames[] = $groupNames[$groupId];
3917 $this->_qill
[$grouping][] = "$allRelationshipType[$value] ( " . implode(", ", $qillNames) . " )";
3920 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
3921 $today = date('Ymd');
3922 //check for active, inactive and all relation status
3923 if ($relStatus[2] == 0) {
3924 $where[$grouping][] = "(
3925 civicrm_relationship.is_active = 1 AND
3926 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
3927 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
3929 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
3931 elseif ($relStatus[2] == 1) {
3932 $where[$grouping][] = "(
3933 civicrm_relationship.is_active = 0 OR
3934 civicrm_relationship.end_date < {$today} OR
3935 civicrm_relationship.start_date > {$today}
3937 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
3940 //check for permissioned, non-permissioned and all permissioned relations
3941 if ($relPermission[2] == 1) {
3942 $this->_where
[$grouping][] = "(
3943 civicrm_relationship.is_permission_a_b = 1
3945 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
3946 } elseif ($relPermission[2] == 2) {
3947 //non-allowed permission relationship.
3948 $this->_where
[$grouping][] = "(
3949 civicrm_relationship.is_permission_a_b = 0
3951 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
3954 $this->addRelationshipDateClauses($grouping, $where);
3955 if(!empty($rType) && isset($rType->id
)){
3956 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
3958 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
3959 $this->_useDistinct
= TRUE;
3960 $this->_relationshipValuesAdded
= TRUE;
3961 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
3963 // @todo creating a temp table could be expanded to group filter
3964 // as even creating a temp table of all relationships is much much more efficient than
3965 // an OR in the join
3966 if($relationshipTempTable) {
3967 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
3969 CREATE TEMPORARY TABLE {$relationshipTempTable}
3970 (SELECT contact_id_b as contact_id, civicrm_relationship.id
3971 FROM civicrm_relationship
3972 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
3975 (SELECT contact_id_a as contact_id, civicrm_relationship.id
3976 FROM civicrm_relationship
3977 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
3980 CRM_Core_DAO
::executeQuery($sql);
3985 * Add start & end date criteria in
3986 * @param string $grouping
3987 * @param array $where = array to add where clauses to, in case you are generating a temp table
3988 * not the main query.
3990 function addRelationshipDateClauses($grouping, &$where){
3991 $dateValues = array();
3997 foreach ($dateTypes as $dateField){
3998 $dateValueLow = $this->getWhereValues('relation_'. $dateField .'_low', $grouping);
3999 $dateValueHigh= $this->getWhereValues('relation_'. $dateField .'_high', $grouping);
4000 if(!empty($dateValueLow)){
4001 $date = date('Ymd', strtotime($dateValueLow[2]));
4002 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4003 $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);
4005 if(!empty($dateValueHigh)){
4006 $date = date('Ymd', strtotime($dateValueHigh[2]));
4007 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4008 $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);
4013 * default set of return properties
4018 static function &defaultReturnProperties($mode = 1) {
4019 if (!isset(self
::$_defaultReturnProperties)) {
4020 self
::$_defaultReturnProperties = array();
4023 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4024 // add activity return properties
4025 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4026 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4029 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4032 if (empty(self
::$_defaultReturnProperties[$mode])) {
4033 self
::$_defaultReturnProperties[$mode] = array(
4036 'legal_identifier' => 1,
4037 'external_identifier' => 1,
4038 'contact_type' => 1,
4039 'contact_sub_type' => 1,
4041 'display_name' => 1,
4042 'preferred_mail_format' => 1,
4051 'street_address' => 1,
4052 'supplemental_address_1' => 1,
4053 'supplemental_address_2' => 1,
4056 'postal_code_suffix' => 1,
4057 'state_province' => 1,
4059 'world_region' => 1,
4066 'household_name' => 1,
4067 'organization_name' => 1,
4068 'deceased_date' => 1,
4073 'current_employer' => 1,
4074 // FIXME: should we use defaultHierReturnProperties() for the below?
4075 'do_not_email' => 1,
4078 'do_not_phone' => 1,
4079 'do_not_trade' => 1,
4081 'contact_is_deleted' => 1,
4082 'preferred_communication_method' => 1,
4083 'preferred_language' => 1,
4087 return self
::$_defaultReturnProperties[$mode];
4091 * get primary condition for a sql clause
4098 static function getPrimaryCondition($value) {
4099 if (is_numeric($value)) {
4100 $value = (int ) $value;
4101 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4107 * wrapper for a simple search query
4109 * @param array $params
4110 * @param array $returnProperties
4111 * @param \bolean|bool $count
4116 static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4117 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4118 list($select, $from, $where, $having) = $query->query();
4120 return "$select $from $where $having";
4124 * These are stub comments as this function needs more explanation - particularly in terms of how it
4125 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4127 * This function was originally written as a wrapper for the api query but is called from multiple places
4128 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4129 * but it is unclear as to whehter that is historical or there is a reason
4130 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4132 * @param array $params
4133 * @param array $returnProperties
4134 * @param null $fields
4135 * @param string $sort
4136 * @param int $offset
4137 * @param int $row_count
4138 * @param bool $smartGroupCache
4139 * @param bool $count return count obnly
4140 * @param bool $skipPermissions Should permissions be ignored or should the logged in user's permissions be applied
4142 * @params bool $smartGroupCache ?? update smart group cache?
4147 static function apiQuery(
4149 $returnProperties = NULL,
4154 $smartGroupCache = TRUE,
4156 $skipPermissions = TRUE
4159 $query = new CRM_Contact_BAO_Query(
4160 $params, $returnProperties,
4161 NULL, TRUE, FALSE, 1,
4163 TRUE, $smartGroupCache
4166 //this should add a check for view deleted if permissions are enabled
4167 if ($skipPermissions){
4168 $query->_skipDeleteClause
= TRUE;
4170 $query->generatePermissionClause(FALSE, $count);
4172 // note : this modifies _fromClause and _simpleFromClause
4173 $query->includePseudoFieldsJoin($sort);
4175 list($select, $from, $where, $having) = $query->query($count);
4177 $options = $query->_options
;
4178 if(!empty($query->_permissionWhereClause
)){
4179 if (empty($where)) {
4180 $where = "WHERE $query->_permissionWhereClause";
4183 $where = "$where AND $query->_permissionWhereClause";
4187 $sql = "$select $from $where $having";
4190 if ($query->_useGroupBy
) {
4191 $sql .= ' GROUP BY contact_a.id';
4193 if (!empty($sort)) {
4194 $sort = CRM_Utils_Type
::escape($sort, 'String');
4195 $sql .= " ORDER BY $sort ";
4197 if ($row_count > 0 && $offset >= 0) {
4198 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4199 $rowCount = CRM_Utils_Type
::escape($row_count, 'Int');
4200 $sql .= " LIMIT $offset, $row_count ";
4203 $dao = CRM_Core_DAO
::executeQuery($sql);
4206 while ($dao->fetch()) {
4208 $noRows = $dao->rowCount
;
4210 return array($noRows,NULL);
4212 $val = $query->store($dao);
4213 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4215 if (!empty($convertedVals)) {
4216 $val = array_replace_recursive($val, $convertedVals);
4218 $values[$dao->contact_id
] = $val;
4221 return array($values, $options);
4225 * create and query the db for an contact search
4227 * @param int $offset the offset for the query
4228 * @param int $rowCount the number of rows to return
4229 * @param string $sort the order by string
4230 * @param boolean $count is this a count only query ?
4231 * @param boolean $includeContactIds should we include contact ids?
4232 * @param boolean $sortByChar if true returns the distinct array of first characters for search results
4233 * @param boolean $groupContacts if true, return only the contact ids
4234 * @param boolean $returnQuery should we return the query as a string
4235 * @param string $additionalWhereClause if the caller wants to further restrict the search (used for components)
4236 * @param string $additionalFromClause should be clause with proper joins, effective to reduce where clause load.
4238 * @return CRM_Contact_DAO_Contact
4241 function searchQuery(
4242 $offset = 0, $rowCount = 0, $sort = NULL,
4243 $count = FALSE, $includeContactIds = FALSE,
4244 $sortByChar = FALSE, $groupContacts = FALSE,
4245 $returnQuery = FALSE,
4246 $additionalWhereClause = NULL, $sortOrder = NULL,
4247 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4250 if ($includeContactIds) {
4251 $this->_includeContactIds
= TRUE;
4252 $this->_whereClause
= $this->whereClause();
4255 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4257 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4258 // and that contact happens to be deleted, set $onlyDeleted to true
4259 foreach ($this->_params
as $values) {
4260 $name = CRM_Utils_Array
::value(0, $values);
4261 $op = CRM_Utils_Array
::value(1, $values);
4262 $value = CRM_Utils_Array
::value(2, $values);
4263 if ($name == 'contact_id' and $op == '=') {
4264 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4265 $onlyDeleted = TRUE;
4270 $this->generatePermissionClause($onlyDeleted, $count);
4272 // building the query string
4275 if (isset($this->_groupByComponentClause
)) {
4276 $groupBy = $this->_groupByComponentClause
;
4278 elseif ($this->_useGroupBy
) {
4279 $groupBy = ' GROUP BY contact_a.id';
4282 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4283 $groupBy = 'GROUP BY civicrm_activity.id ';
4286 $order = $orderBy = $limit = '';
4288 $config = CRM_Core_Config
::singleton();
4289 if ($config->includeOrderByClause ||
4290 isset($this->_distinctComponentClause
)
4293 if (is_string($sort)) {
4297 $orderBy = trim($sort->orderBy());
4299 if (!empty($orderBy)) {
4300 // this is special case while searching for
4301 // changelog CRM-1718
4302 if (preg_match('/sort_name/i', $orderBy)) {
4303 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4306 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
4307 $order = " ORDER BY $orderBy";
4310 $sortOrder = CRM_Utils_Type
::escape($sortOrder, 'String');
4311 $order .= " $sortOrder";
4314 // always add contact_a.id to the ORDER clause
4315 // so the order is deterministic
4316 if (strpos('contact_a.id', $order) === FALSE) {
4317 $order .= ", contact_a.id";
4321 elseif ($sortByChar) {
4322 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4325 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4329 // hack for order clause
4331 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4332 $fieldOrder = explode(' ', $fieldStr);
4333 $field = $fieldOrder[0];
4339 $this->_whereTables
["civicrm_address"] = 1;
4340 $order = str_replace($field, "civicrm_address.{$field}", $order);
4344 case 'state_province':
4345 $this->_whereTables
["civicrm_{$field}"] = 1;
4346 $order = str_replace($field, "civicrm_{$field}.name", $order);
4350 $this->_whereTables
["civicrm_email"] = 1;
4351 $order = str_replace($field, "civicrm_email.{$field}", $order);
4354 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4355 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4359 if ($rowCount > 0 && $offset >= 0) {
4360 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4361 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4362 $limit = " LIMIT $offset, $rowCount ";
4366 // note : this modifies _fromClause and _simpleFromClause
4367 $this->includePseudoFieldsJoin($sort);
4369 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts);
4371 if(!empty($this->_permissionWhereClause
)){
4372 if (empty($where)) {
4373 $where = "WHERE $this->_permissionWhereClause";
4376 $where = "$where AND $this->_permissionWhereClause";
4380 if ($additionalWhereClause) {
4381 $where = $where . ' AND ' . $additionalWhereClause;
4384 //additional from clause should be w/ proper joins.
4385 if ($additionalFromClause) {
4386 $from .= "\n" . $additionalFromClause;
4389 // if we are doing a transform, do it here
4390 // use the $from, $where and $having to get the contact ID
4391 if ($this->_displayRelationshipType
) {
4392 $this->filterRelatedContacts($from, $where, $having);
4395 if ($skipOrderAndLimit) {
4396 $query = "$select $from $where $having $groupBy";
4399 $query = "$select $from $where $having $groupBy $order $limit";
4406 return CRM_Core_DAO
::singleValueQuery($query);
4409 $dao = CRM_Core_DAO
::executeQuery($query);
4410 if ($groupContacts) {
4412 while ($dao->fetch()) {
4415 return implode(',', $ids);
4422 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4424 * @param string $cacheKey
4425 * @param int $offset
4426 * @param int $rowCount
4427 * @param bool $includeContactIds
4428 * @return CRM_Core_DAO
4430 function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4431 $this->_includeContactIds
= $includeContactIds;
4432 list($select, $from, $where) = $this->query();
4433 $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);
4434 $order = " ORDER BY pnc.id";
4435 $groupBy = " GROUP BY contact_a.id";
4436 $limit = " LIMIT $offset, $rowCount";
4437 $query = "$select $from $where $groupBy $order $limit";
4439 return CRM_Core_DAO
::executeQuery($query);
4443 * Populate $this->_permissionWhereClause with permission related clause and update other
4444 * query related properties.
4446 * Function calls ACL permission class and hooks to filter the query appropriately
4448 * Note that these 2 params were in the code when extracted from another function
4449 * and a second round extraction would be to make them properties of the class
4451 * @param bool $onlyDeleted Only get deleted contacts
4452 * @param bool $count Return Count only
4456 function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4457 if (!$this->_skipPermission
) {
4458 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4459 CRM_Core_Permission
::VIEW
,
4461 $this->_whereTables
,
4464 $this->_skipDeleteClause
4467 // regenerate fromClause since permission might have added tables
4468 if ($this->_permissionWhereClause
) {
4469 //fix for row count in qill (in contribute/membership find)
4471 $this->_useDistinct
= TRUE;
4473 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4474 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4478 // add delete clause if needed even if we are skipping permission
4480 if (!$this->_skipDeleteClause
) {
4481 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4482 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4486 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4492 function setSkipPermission($val) {
4493 $this->_skipPermission
= $val;
4496 function &summaryContribution($context = NULL) {
4497 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4501 SELECT COUNT( conts.total_amount ) as total_count,
4502 SUM( conts.total_amount ) as total_amount,
4503 AVG( conts.total_amount ) as total_avg,
4504 conts.currency as currency";
4505 if($this->_permissionWhereClause
) {
4506 $where .= " AND " . $this->_permissionWhereClause
;
4508 if ($context == 'search') {
4509 $where .= " AND contact_a.is_deleted = 0 ";
4512 // make sure contribution is completed - CRM-4989
4513 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4517 $summary['total'] = array();
4518 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4520 $query = "$select FROM (
4521 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $completedWhere
4522 GROUP BY civicrm_contribution.id
4526 $dao = CRM_Core_DAO
::executeQuery($query);
4528 $summary['total']['count'] = 0;
4529 $summary['total']['amount'] = $summary['total']['avg'] = array();
4530 while ($dao->fetch()) {
4531 $summary['total']['count'] +
= $dao->total_count
;
4532 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4533 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4535 if (!empty($summary['total']['amount'])) {
4536 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4537 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4540 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4544 //@todo - this could be one query using the IF in mysql - eg
4545 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
4546 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
4547 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
4548 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
4549 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
4550 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
4551 // FROM civicrm_contact contact_a
4552 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
4553 // WHERE ( ... where clause....
4554 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
4558 SELECT COUNT( conts.total_amount ) as cancel_count,
4559 SUM( conts.total_amount ) as cancel_amount,
4560 AVG( conts.total_amount ) as cancel_avg,
4561 conts.currency as currency";
4563 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4564 if ($context == 'search') {
4565 $where .= " AND contact_a.is_deleted = 0 ";
4568 $query = "$select FROM (
4569 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
4570 GROUP BY civicrm_contribution.id
4574 $dao = CRM_Core_DAO
::executeQuery($query);
4577 if ($dao->fetch()) {
4578 $summary['cancel']['count'] = $dao->cancel_count
;
4579 $summary['cancel']['amount'] = $dao->cancel_amount
;
4580 $summary['cancel']['avg'] = $dao->cancel_avg
;
4584 $summary['cancel']['count'] = 0;
4585 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4586 while ($dao->fetch()) {
4587 $summary['cancel']['count'] +
= $dao->cancel_count
;
4588 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4589 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4591 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4592 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
4599 * getter for the qill object
4605 return $this->_qill
;
4609 * default set of return default hier return properties
4614 static function &defaultHierReturnProperties() {
4615 if (!isset(self
::$_defaultHierReturnProperties)) {
4616 self
::$_defaultHierReturnProperties = array(
4619 'legal_identifier' => 1,
4620 'external_identifier' => 1,
4621 'contact_type' => 1,
4622 'contact_sub_type' => 1,
4624 'display_name' => 1,
4631 'email_greeting' => 1,
4632 'postal_greeting' => 1,
4636 'preferred_communication_method' => 1,
4637 'do_not_phone' => 1,
4638 'do_not_email' => 1,
4641 'do_not_trade' => 1,
4644 '1' => array('location_type' => 1,
4645 'street_address' => 1,
4647 'state_province' => 1,
4649 'postal_code_suffix' => 1,
4652 'phone-Mobile' => 1,
4665 'location_type' => 1,
4666 'street_address' => 1,
4668 'state_province' => 1,
4670 'postal_code_suffix' => 1,
4673 'phone-Mobile' => 1,
4687 return self
::$_defaultHierReturnProperties;
4690 function dateQueryBuilder(
4691 &$values, $tableName, $fieldName,
4692 $dbFieldName, $fieldTitle,
4693 $appendTimeStamp = TRUE
4695 list($name, $op, $value, $grouping, $wildcard) = $values;
4701 if ($name == "{$fieldName}_low" ||
4702 $name == "{$fieldName}_high"
4704 if (isset($this->_rangeCache
[$fieldName])) {
4707 $this->_rangeCache
[$fieldName] = 1;
4709 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4711 if ($name == $fieldName . '_low') {
4713 $firstPhrase = ts('greater than or equal to');
4714 $firstDate = CRM_Utils_Date
::processDate($value);
4716 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4717 if (!empty($secondValues) && $secondValues[2]) {
4719 $secondPhrase = ts('less than or equal to');
4720 $secondValue = $secondValues[2];
4722 if ($appendTimeStamp && strlen($secondValue) == 10) {
4723 $secondValue .= ' 23:59:59';
4725 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4728 elseif ($name == $fieldName . '_high') {
4730 $firstPhrase = ts('less than or equal to');
4732 if ($appendTimeStamp && strlen($value) == 10) {
4733 $value .= ' 23:59:59';
4735 $firstDate = CRM_Utils_Date
::processDate($value);
4737 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4738 if (!empty($secondValues) && $secondValues[2]) {
4740 $secondPhrase = ts('greater than or equal to');
4741 $secondValue = $secondValues[2];
4742 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4746 if (!$appendTimeStamp) {
4747 $firstDate = substr($firstDate, 0, 8);
4749 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
4752 if (!$appendTimeStamp) {
4753 $secondDate = substr($secondDate, 0, 8);
4755 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
4758 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4760 $this->_where
[$grouping][] = "
4761 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
4762 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
4764 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
4767 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
4768 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
4772 if ($name == $fieldName) {
4776 $date = CRM_Utils_Date
::processDate($value);
4778 if (!$appendTimeStamp) {
4779 $date = substr($date, 0, 8);
4782 $format = CRM_Utils_Date
::customFormat($date);
4785 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'";
4788 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op";
4790 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4791 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$format\"";
4795 function numberRangeBuilder(&$values,
4796 $tableName, $fieldName,
4797 $dbFieldName, $fieldTitle,
4800 list($name, $op, $value, $grouping, $wildcard) = $values;
4802 if ($name == "{$fieldName}_low" ||
4803 $name == "{$fieldName}_high"
4805 if (isset($this->_rangeCache
[$fieldName])) {
4808 $this->_rangeCache
[$fieldName] = 1;
4810 $secondOP = $secondPhrase = $secondValue = NULL;
4812 if ($name == "{$fieldName}_low") {
4814 $firstPhrase = ts('greater than');
4816 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4817 if (!empty($secondValues)) {
4819 $secondPhrase = ts('less than');
4820 $secondValue = $secondValues[2];
4825 $firstPhrase = ts('less than');
4827 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4828 if (!empty($secondValues)) {
4830 $secondPhrase = ts('greater than');
4831 $secondValue = $secondValues[2];
4836 $this->_where
[$grouping][] = "
4837 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
4838 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
4840 $displayValue = $options ?
$options[$value] : $value;
4841 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
4843 $this->_qill
[$grouping][] =
4844 "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
4847 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
4848 $displayValue = $options ?
$options[$value] : $value;
4849 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
4851 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4856 if ($name == $fieldName) {
4860 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
4862 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4863 $displayValue = $options ?
$options[$value] : $value;
4864 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
4871 * Given the field name, operator, value & its data type
4872 * builds the where Clause for the query
4873 * used for handling 'IS NULL'/'IS NOT NULL' operators
4875 * @param string $field fieldname
4876 * @param string $op operator
4877 * @param string $value value
4878 * @param string $dataType data type of the field
4880 * @return where clause for the query
4883 static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
4885 $clause = "$field $op";
4893 $clause = " ( $field IS NULL OR $field = '' ) ";
4896 case 'IS NOT EMPTY':
4897 $clause = " ( $field IS NOT NULL AND $field <> '' ) ";
4902 if (isset($dataType)) {
4903 if (is_array($value)) {
4907 $value = CRM_Utils_Type
::escape($value, "String");
4908 $values = explode(',', CRM_Utils_Array
::value(0, explode(')', CRM_Utils_Array
::value(1, explode('(', $value)))));
4910 // supporting multiple values in IN clause
4912 foreach ($values as $v) {
4914 $val[] = "'" . CRM_Utils_Type
::escape($v, $dataType) . "'";
4916 $value = "(" . implode($val, ",") . ")";
4918 return "$clause $value";
4921 if (empty($dataType)) {
4922 $dataType = 'String';
4925 $value = CRM_Utils_Type
::escape($value, $dataType);
4926 // if we dont have a dataType we should assume
4927 if ($dataType == 'String' ||
$dataType == 'Text') {
4928 $value = "'" . strtolower($value) . "'";
4930 return "$clause $value";
4934 function openedSearchPanes($reset = FALSE) {
4935 if (!$reset ||
empty($this->_whereTables
)) {
4936 return self
::$_openedPanes;
4939 // pane name to table mapper
4940 $panesMapper = array(
4941 ts('Contributions') => 'civicrm_contribution',
4942 ts('Memberships') => 'civicrm_membership',
4943 ts('Events') => 'civicrm_participant',
4944 ts('Relationships') => 'civicrm_relationship',
4945 ts('Activities') => 'civicrm_activity',
4946 ts('Pledges') => 'civicrm_pledge',
4947 ts('Cases') => 'civicrm_case',
4948 ts('Grants') => 'civicrm_grant',
4949 ts('Address Fields') => 'civicrm_address',
4950 ts('Notes') => 'civicrm_note',
4951 ts('Change Log') => 'civicrm_log',
4952 ts('Mailings') => 'civicrm_mailing_event_queue',
4954 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
4956 foreach (array_keys($this->_whereTables
) as $table) {
4957 if ($panName = array_search($table, $panesMapper)) {
4958 self
::$_openedPanes[$panName] = TRUE;
4962 return self
::$_openedPanes;
4965 function setOperator($operator) {
4966 $validOperators = array('AND', 'OR');
4967 if (!in_array($operator, $validOperators)) {
4970 $this->_operator
= $operator;
4973 function getOperator() {
4974 return $this->_operator
;
4977 function filterRelatedContacts(&$from, &$where, &$having) {
4978 static $_rTypeProcessed = NULL;
4979 static $_rTypeFrom = NULL;
4980 static $_rTypeWhere = NULL;
4982 if (!$_rTypeProcessed) {
4983 $_rTypeProcessed = TRUE;
4985 // create temp table with contact ids
4986 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
4987 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
4988 CRM_Core_DAO
::executeQuery($sql);
4991 REPLACE INTO $tableName ( contact_id )
4997 CRM_Core_DAO
::executeQuery($sql);
4999 $qillMessage = ts('Contacts with a Relationship Type of: ');
5000 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5002 if (is_numeric($this->_displayRelationshipType
)) {
5003 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5005 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5006 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5009 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5010 AND displayRelType.is_active = 1
5014 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5015 if ($dirOne == 'a') {
5016 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5018 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5019 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5023 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5025 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5026 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5030 WHERE displayRelType.relationship_type_id = $relType
5031 AND displayRelType.is_active = 1
5034 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5037 if (strpos($from, $_rTypeFrom) === FALSE) {
5038 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5039 // this happens when we have an event_type in the quert (CRM-7969)
5040 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5041 $from .= $_rTypeFrom;
5042 $where = $_rTypeWhere;
5048 static function caseImportant( $op ) {
5050 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5053 static function componentPresent( &$returnProperties, $prefix ) {
5054 foreach ($returnProperties as $name => $dontCare ) {
5055 if (substr($name, 0, strlen($prefix)) == $prefix) {
5063 * Builds the necessary structures for all fields that are similar to option value lookups
5065 * @param $name string the name of the field
5066 * @param $op string the sql operator, this function should handle ALL SQL operators
5067 * @param $value any string / integer / array depends on the operator and whos calling the query builder
5068 * @param $grouping int the index where to place the where clause
5069 * @param $selectValues
5070 * @param $field array an array that contains various properties of the field identified by $name
5071 * @param $label string The label for this field element
5072 * @param $dataType string The data type for this element
5074 * @param bool $useIDsOnly
5076 * @internal param array $selectValue the key value pairs for this element. This allows us to use this function for things besides option-value pairs
5077 * @return void adds the where clause and qill to the query object
5079 function optionValueQuery(
5087 $dataType = 'String',
5091 if (!empty($selectValues)) {
5092 $qill = $selectValues[$value];
5098 $pseudoFields = array('email_greeting', 'postal_greeting', 'addressee', 'gender_id', 'prefix_id', 'suffix_id');
5100 if (is_numeric($value)) {
5101 $qill = $selectValues[(int ) $value];
5103 elseif ($op == 'IN' ||
$op == 'NOT IN') {
5104 $values = self
::parseSearchBuilderString($value);
5105 if (is_array($values)) {
5107 $newValues = array();
5108 foreach ($values as $v) {
5109 $intVals[] = (int) $v;
5110 $newValues[] = $selectValues[(int ) $v];
5113 $value = (in_array($name, $pseudoFields)) ?
$intVals : $newValues;
5114 $qill = implode(', ', $newValues);
5117 elseif (!array_key_exists($value, $selectValues)) {
5118 // its a string, lets get the int value
5119 $value = array_search($value, $selectValues);
5122 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5123 if ($tableName == 'civicrm_contact') {
5124 $wc = "contact_a.$fieldName";
5127 $wc = "$tableName.id";
5131 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5134 if (in_array($name, $pseudoFields)) {
5135 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id'))) {
5136 $wc = "contact_a.{$name}_id";
5138 $dataType = 'Positive';
5139 $value = (!$value) ?
0 : $value;
5142 $this->_qill
[$grouping][] = $label . " $op '$qill'";
5143 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' ||
$op == 'RLIKE')) ?
'=' : $op;
5144 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5148 * function to check and explode a user defined numeric string into an array
5149 * this was the protocol used by search builder in the old old days before we had
5150 * super nice js widgets to do the hard work
5152 * @param the $string
5153 * @param string $dataType the dataType we should check for the values, default integer
5155 * @return FALSE if string does not match the patter
5156 * array of numeric values if string does match the pattern
5159 static function parseSearchBuilderString($string, $dataType = 'Integer') {
5160 $string = trim($string);
5161 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5165 $string = substr($string, 1, -1);
5166 $values = explode(',', $string);
5167 if (empty($values)) {
5171 $returnValues = array();
5172 foreach ($values as $v) {
5173 if ($dataType == 'Integer' && ! is_numeric($v)) {
5176 else if ($dataType == 'String' && ! is_string($v)) {
5179 $returnValues[] = trim($v);
5182 if (empty($returnValues)) {
5186 return $returnValues;
5190 * convert the pseudo constants id's to their names
5192 * @param reference parameter $dao
5193 * @param bool $return
5197 function convertToPseudoNames(&$dao, $return = FALSE) {
5198 if (empty($this->_pseudoConstantsSelect
)) {
5202 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5203 if (CRM_Utils_Array
::value('sorting', $this->_pseudoConstantsSelect
[$key])) {
5207 if (property_exists($dao, $value['idCol'])) {
5208 $val = $dao->$value['idCol'];
5210 if (CRM_Utils_System
::isNull($val)) {
5213 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5215 $idColumn = "{$key}_id";
5216 $dao->$idColumn = $val;
5217 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5219 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5220 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5223 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5224 $dao->$key = $labels[$val];
5227 // return converted values in array format
5229 if (strpos($key, '-') !== FALSE) {
5230 $keyVal = explode('-', $key);
5231 $current = &$values;
5232 $lastElement = array_pop($keyVal);
5233 foreach ($keyVal as $v) {
5234 if (!array_key_exists($v, $current)) {
5235 $current[$v] = array();
5237 $current = &$current[$v];
5239 $current[$lastElement] = $dao->$key;
5242 $values[$key] = $dao->$key;
5251 * include pseudo fields LEFT JOIN
5252 * @param $sort can be a object or string
5256 function includePseudoFieldsJoin($sort) {
5257 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5260 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5263 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5264 if (CRM_Utils_Array
::value('table', $value)) {
5265 $regex = "/({$value['table']}\.|{$name})/";
5266 if (preg_match($regex, $sort)) {
5267 $this->_elemnt
[$value['element']] = 1;
5268 $this->_select
[$value['element']] = $value['select'];
5269 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5270 $present[$value['table']] = $value['join'];
5274 $presentSimpleFrom = $present;
5276 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5277 array_key_exists('civicrm_country', $presentSimpleFrom)) {
5278 unset($presentSimpleFrom['civicrm_country']);
5280 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5281 array_key_exists('civicrm_country', $present)) {
5282 unset($present['civicrm_country']);
5285 $presentClause = $presentSimpleFromClause = NULL;
5286 if (!empty($present)) {
5287 $presentClause = implode(' ', $present);
5289 if (!empty($presentSimpleFrom)) {
5290 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5293 $this->_fromClause
= $this->_fromClause
. $presentClause;
5294 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5296 return array($presentClause, $presentSimpleFromClause);