3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
37 * This class is a heart of search query building mechanism.
39 class CRM_Contact_BAO_Query
{
42 * The various search modes
52 MODE_PLEDGEBANK
= 256,
61 * the default set of return properties
66 static $_defaultReturnProperties = NULL;
69 * the default set of hier return properties
74 static $_defaultHierReturnProperties;
77 * the set of input params
88 * the set of output params
92 public $_returnProperties;
102 * the name of the elements that are in the select clause
103 * used to extract the values
110 * the tables involved in the query
117 * the table involved in the where clause
121 public $_whereTables;
136 public $_whereClause;
139 * additional permission Where Clause
144 public $_permissionWhereClause;
155 * additional permission from clause
160 public $_permissionFromClause;
163 * the from clause for the simple select and alphabetical
168 public $_simpleFromClause;
179 * The english language version of the query
186 * All the fields that could potentially be involved in
194 * The cache to translate the option values into labels
201 * are we in search mode
205 public $_search = TRUE;
208 * should we skip permission checking
212 public $_skipPermission = FALSE;
215 * should we skip adding of delete clause
219 public $_skipDeleteClause = FALSE;
222 * are we in strict mode (use equality over LIKE)
226 public $_strict = FALSE;
229 * What operator to use to group the clauses
233 public $_operator = 'AND';
238 * Should we only search on primary location
242 public $_primaryLocation = TRUE;
245 * are contact ids part of the query
249 public $_includeContactIds = FALSE;
252 * Should we use the smart group cache
256 public $_smartGroupCache = TRUE;
259 * Should we display contacts with a specific relationship type
263 public $_displayRelationshipType = NULL;
266 * reference to the query object for custom values
270 public $_customQuery;
273 * should we enable the distinct clause, used if we are including
274 * more than one group
278 public $_useDistinct = FALSE;
281 * Should we just display one contact record
283 public $_useGroupBy = FALSE;
286 * the relationship type direction
299 static $_activityRole;
302 * Consider the component activity type
303 * during activity search.
308 static $_considerCompActivities;
311 * Consider with contact activities only,
312 * during activity search.
317 static $_withContactActivitiesOnly;
320 * use distinct component clause for component searches
324 public $_distinctComponentClause;
327 * use groupBy component clause for component searches
331 public $_groupByComponentClause;
334 * Track open panes, useful in advance search
339 public static $_openedPanes = array();
342 * The tables which have a dependency on location and/or address
347 static $_dependencies = array(
348 'civicrm_state_province' => 1,
349 'civicrm_country' => 1,
350 'civicrm_county' => 1,
351 'civicrm_address' => 1,
352 'civicrm_location_type' => 1,
356 * List of location specific fields
358 static $_locationSpecificFields = array(
363 'supplemental_address_1',
364 'supplemental_address_2',
367 'postal_code_suffix',
380 * Rememeber if we handle either end of a number or date range
381 * so we can skip the other
383 protected $_rangeCache = array();
385 * Set to true when $this->relationship is run to avoid adding twice
388 protected $_relationshipValuesAdded = FALSE;
390 public $_pseudoConstantsSelect = array();
393 * class constructor which also does all the work
395 * @param array $params
396 * @param array $returnProperties
397 * @param array $fields
398 * @param boolean $includeContactIds
399 * @param boolean $strict
400 * @param boolean $mode - mode the search is operating on
405 function __construct(
406 $params = NULL, $returnProperties = NULL, $fields = NULL,
407 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
408 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
409 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
412 $this->_params
= &$params;
413 if ($this->_params
== NULL) {
414 $this->_params
= array();
417 if (empty($returnProperties)) {
418 $this->_returnProperties
= self
::defaultReturnProperties($mode);
421 $this->_returnProperties
= &$returnProperties;
424 $this->_includeContactIds
= $includeContactIds;
425 $this->_strict
= $strict;
426 $this->_mode
= $mode;
427 $this->_skipPermission
= $skipPermission;
428 $this->_smartGroupCache
= $smartGroupCache;
429 $this->_displayRelationshipType
= $displayRelationshipType;
430 $this->setOperator($operator);
433 $this->_fields
= &$fields;
434 $this->_search
= FALSE;
435 $this->_skipPermission
= TRUE;
438 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE);
440 $fields = CRM_Core_Component
::getQueryFields();
441 unset($fields['note']);
442 $this->_fields
= array_merge($this->_fields
, $fields);
444 // add activity fields
445 $fields = CRM_Activity_BAO_Activity
::exportableFields();
446 $this->_fields
= array_merge($this->_fields
, $fields);
448 // add any fields provided by hook implementers
449 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
450 $this->_fields
= array_merge($this->_fields
, $extFields);
453 // basically do all the work once, and then reuse it
458 * function which actually does all the work for the constructor
463 function initialize() {
464 $this->_select
= array();
465 $this->_element
= array();
466 $this->_tables
= array();
467 $this->_whereTables
= array();
468 $this->_where
= array();
469 $this->_qill
= array();
470 $this->_options
= array();
471 $this->_cfIDs
= array();
472 $this->_paramLookup
= array();
473 $this->_having
= array();
475 $this->_customQuery
= NULL;
477 // reset cached static variables - CRM-5803
478 self
::$_activityRole = NULL;
479 self
::$_considerCompActivities = NULL;
480 self
::$_withContactActivitiesOnly = NULL;
482 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
483 $this->_element
['contact_id'] = 1;
484 $this->_tables
['civicrm_contact'] = 1;
486 if (!empty($this->_params
)) {
487 $this->buildParamsLookup();
490 $this->_whereTables
= $this->_tables
;
492 $this->selectClause();
493 $this->_whereClause
= $this->whereClause();
495 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
496 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
498 $this->openedSearchPanes(TRUE);
501 function buildParamsLookup() {
502 // first fix and handle contact deletion nicely
503 // this code is primarily for search builder use case
504 // where different clauses can specify if they want deleted
507 $trashParamExists = FALSE;
508 $paramByGroup = array();
509 foreach ( $this->_params
as $k => $param ) {
510 if (!empty($param[0]) && $param[0] == 'contact_is_deleted' ) {
511 $trashParamExists = TRUE;
513 if (!empty($param[3])) {
514 $paramByGroup[$param[3]][$k] = $param;
518 if ( $trashParamExists ) {
519 $this->_skipDeleteClause
= TRUE;
521 //cycle through group sets and explicitly add trash param if not set
522 foreach ( $paramByGroup as $setID => $set ) {
524 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params
) &&
525 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params
) ) {
526 $this->_params
[] = array(
527 'contact_is_deleted',
537 foreach ($this->_params
as $value) {
538 if (!CRM_Utils_Array
::value(0, $value)) {
541 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
543 if (!array_key_exists($cfID, $this->_cfIDs
)) {
544 $this->_cfIDs
[$cfID] = array();
546 $this->_cfIDs
[$cfID][] = $value;
549 if (!array_key_exists($value[0], $this->_paramLookup
)) {
550 $this->_paramLookup
[$value[0]] = array();
552 $this->_paramLookup
[$value[0]][] = $value;
557 * Some composite fields do not appear in the fields array
558 * hack to make them part of the query
563 function addSpecialFields() {
564 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
565 foreach ($special as $name) {
566 if (CRM_Utils_Array
::value($name, $this->_returnProperties
)) {
567 $this->_select
[$name] = "contact_a.{$name} as $name";
568 $this->_element
[$name] = 1;
574 * Given a list of conditions in params and a list of desired
575 * return Properties generate the required select and from
576 * clauses. Note that since the where clause introduces new
577 * tables, the initial attempt also retrieves all variables used
583 function selectClause() {
585 $this->addSpecialFields();
587 foreach ($this->_fields
as $name => $field) {
588 // skip component fields
589 // there are done by the alter query below
590 // and need not be done on every field
592 (substr($name, 0, 12) == 'participant_') ||
593 (substr($name, 0, 7) == 'pledge_') ||
594 (substr($name, 0, 5) == 'case_')
599 // redirect to activity select clause
600 if (substr($name, 0, 9) == 'activity_') {
601 CRM_Activity_BAO_Query
::select($this);
605 // if this is a hierarchical name, we ignore it
606 $names = explode('-', $name);
607 if (count($names > 1) && isset($names[1]) && is_numeric($names[1])) {
611 // make an exception for special cases, to add the field in select clause
612 $makeException = FALSE;
614 //special handling for groups/tags
615 if (in_array($name, array('groups', 'tags', 'notes'))
616 && isset($this->_returnProperties
[substr($name, 0, -1)])
618 $makeException = TRUE;
621 // since note has 3 different options we need special handling
622 // note / note_subject / note_body
623 if ($name == 'notes') {
624 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
625 if (isset($this->_returnProperties
[$noteField])) {
626 $makeException = TRUE;
632 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
634 CRM_Utils_Array
::value($name, $this->_paramLookup
) ||
635 CRM_Utils_Array
::value($name, $this->_returnProperties
) ||
639 // add to cfIDs array if not present
640 if (!array_key_exists($cfID, $this->_cfIDs
)) {
641 $this->_cfIDs
[$cfID] = array();
644 elseif (isset($field['where'])) {
645 list($tableName, $fieldName) = explode('.', $field['where'], 2);
646 if (isset($tableName)) {
647 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
648 $this->_tables
['civicrm_address'] = 1;
649 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
650 $this->_element
['address_id'] = 1;
653 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
654 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
656 if ($tableName == 'im_provider') {
657 CRM_Core_OptionValue
::select($this);
660 if (in_array($tableName,
661 array('email_greeting', 'postal_greeting', 'addressee'))) {
662 $this->_element
["{$name}_id"] = 1;
663 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
664 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
665 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
666 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
668 if ($tableName == 'email_greeting') {
669 $this->_pseudoConstantsSelect
[$name]['join'] =
670 " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
671 $this->_pseudoConstantsSelect
[$name]['join'] .=
672 " 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 ) ";
674 elseif ($tableName == 'postal_greeting') {
675 $this->_pseudoConstantsSelect
[$name]['join'] =
676 " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
677 $this->_pseudoConstantsSelect
[$name]['join'] .=
678 " 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 ) ";
680 elseif ($tableName == 'addressee') {
681 $this->_pseudoConstantsSelect
[$name]['join'] =
682 " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
683 $this->_pseudoConstantsSelect
[$name]['join'] .=
684 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
686 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
689 $greetField = "{$name}_display";
690 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
691 $this->_element
[$greetField] = 1;
693 $greetField = "{$name}_custom";
694 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
695 $this->_element
[$greetField] = 1;
699 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
700 $this->_tables
[$tableName] = 1;
703 // also get the id of the tableName
704 $tName = substr($tableName, 8);
705 if (in_array($tName, array('country', 'state_province', 'county'))) {
706 $pf = ($tName == 'state_province') ?
'state_province_name' : $name;
707 $this->_pseudoConstantsSelect
[$pf] =
708 array('pseudoField' => "{$tName}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address',
709 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
711 if ($tName == 'state_province') {
712 $this->_pseudoConstantsSelect
[$tName] =
713 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id",
714 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
717 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
718 $this->_element
["{$tName}_id"] = 1;
720 elseif ($tName != 'contact') {
721 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
722 $this->_element
["{$tName}_id"] = 1;
725 //special case for phone
726 if ($name == 'phone') {
727 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
728 $this->_element
['phone_type_id'] = 1;
731 // if IM then select provider_id also
732 // to get "IM Service Provider" in a file to be exported, CRM-3140
734 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
735 $this->_element
['provider_id'] = 1;
738 if ($tName == 'contact') {
739 // special case, when current employer is set for Individual contact
740 if ($fieldName == 'organization_name') {
741 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
743 elseif ($fieldName != 'id') {
744 if ($fieldName == 'prefix_id') {
745 $this->_pseudoConstantsSelect
['individual_prefix'] = array('pseudoField' => 'prefix_id', 'idCol' => "prefix_id", 'bao' => 'CRM_Contact_BAO_Contact');
747 if ($fieldName == 'suffix_id') {
748 $this->_pseudoConstantsSelect
['individual_suffix'] = array('pseudoField' => 'suffix_id', 'idCol' => "suffix_id", 'bao' => 'CRM_Contact_BAO_Contact');
750 if ($fieldName == 'gender_id') {
751 $this->_pseudoConstantsSelect
['gender'] = array('pseudoField' => 'gender_id', 'idCol' => "gender_id", 'bao' => 'CRM_Contact_BAO_Contact');
753 $this->_select
[$name] = "contact_a.{$fieldName} as `$name`";
756 elseif (in_array($tName, array('state_province', 'country', 'county'))) {
757 $this->_pseudoConstantsSelect
[$pf]['select'] = "{$field['where']} as `$name`";
758 $this->_pseudoConstantsSelect
[$pf]['element'] = $name;
759 if ($tName == 'state_province') {
760 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
761 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
765 $this->_select
[$name] = "{$field['where']} as `$name`";
767 if (!in_array($tName, array('state_province', 'country', 'county'))) {
768 $this->_element
[$name] = 1;
773 elseif ($name === 'tags') {
774 $this->_useGroupBy
= TRUE;
775 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
776 $this->_element
[$name] = 1;
777 $this->_tables
['civicrm_tag'] = 1;
778 $this->_tables
['civicrm_entity_tag'] = 1;
780 elseif ($name === 'groups') {
781 $this->_useGroupBy
= TRUE;
782 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
783 $this->_element
[$name] = 1;
784 $this->_tables
['civicrm_group'] = 1;
786 elseif ($name === 'notes') {
787 $this->_useGroupBy
= TRUE;
788 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.note)) as notes";
789 $this->_element
[$name] = 1;
790 $this->_tables
['civicrm_note'] = 1;
792 elseif ($name === 'current_employer') {
793 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
794 $this->_element
[$name] = 1;
799 CRM_Utils_Array
::value('is_search_range', $field)
801 // this is a custom field with range search enabled, so we better check for two/from values
802 if (CRM_Utils_Array
::value($name . '_from', $this->_paramLookup
)) {
803 if (!array_key_exists($cfID, $this->_cfIDs
)) {
804 $this->_cfIDs
[$cfID] = array();
806 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
807 // search in the cdID array for the same grouping
809 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
810 if ($c[3] == $p[3]) {
811 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
816 $p[2] = array('from' => $p[2]);
817 $this->_cfIDs
[$cfID][] = $p;
821 if (CRM_Utils_Array
::value($name . '_to', $this->_paramLookup
)) {
822 if (!array_key_exists($cfID, $this->_cfIDs
)) {
823 $this->_cfIDs
[$cfID] = array();
825 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
826 // search in the cdID array for the same grouping
828 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
829 if ($c[4] == $p[4]) {
830 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
835 $p[2] = array('to' => $p[2]);
836 $this->_cfIDs
[$cfID][] = $p;
843 // add location as hierarchical elements
844 $this->addHierarchicalElements();
846 // add multiple field like website
847 $this->addMultipleElements();
850 CRM_Core_Component
::alterQuery($this, 'select');
852 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
854 if (!empty($this->_cfIDs
)) {
855 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE);
856 $this->_customQuery
->query();
857 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
858 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
859 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
860 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
861 $this->_options
= $this->_customQuery
->_options
;
866 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
872 function addHierarchicalElements() {
873 if (!CRM_Utils_Array
::value('location', $this->_returnProperties
)) {
876 if (!is_array($this->_returnProperties
['location'])) {
880 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
881 $processed = array();
884 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
885 $addressCustomFieldIds = array();
887 foreach ($this->_returnProperties
['location'] as $name => $elements) {
888 $lCond = self
::getPrimaryCondition($name);
891 $locationTypeId = array_search($name, $locationTypes);
892 if ($locationTypeId === FALSE) {
895 $lCond = "location_type_id = $locationTypeId";
896 $this->_useDistinct
= TRUE;
898 //commented for CRM-3256
899 $this->_useGroupBy
= TRUE;
902 $name = str_replace(' ', '_', $name);
904 $tName = "$name-location_type";
905 $ltName = "`$name-location_type`";
906 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
907 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
908 $this->_element
["{$tName}_id"] = 1;
909 $this->_element
["{$tName}"] = 1;
911 $locationTypeName = $tName;
912 $locationTypeJoin = array();
916 foreach ($elements as $elementFullName => $dontCare) {
918 $elementName = $elementCmpName = $elementFullName;
920 if (substr($elementCmpName, 0, 5) == 'phone') {
921 $elementCmpName = 'phone';
924 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
925 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
926 $addressCustomFieldIds[$cfID][$name] = 1;
929 //add address table only once
930 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
932 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
934 $tName = "$name-address";
935 $aName = "`$name-address`";
936 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
937 $this->_element
["{$tName}_id"] = 1;
938 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
939 $this->_tables
[$tName] = $addressJoin;
940 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
941 $processed[$aName] = 1;
945 $cond = $elementType = '';
946 if (strpos($elementName, '-') !== FALSE) {
947 // this is either phone, email or IM
948 list($elementName, $elementType) = explode('-', $elementName);
951 if (($elementName != 'phone') && ($elementName != 'im')) {
952 $cond = self
::getPrimaryCondition($elementType);
954 // CRM-13011 : If location type is primary, do not restrict search to the phone
955 // type id - we want the primary phone, regardless of what type it is.
956 // Otherwise, restrict to the specified phone type for the given field.
957 if ((!$cond) && ($elementName == 'phone') && $elements['location_type'] != 'Primary') {
958 $cond = "phone_type_id = '$elementType'";
960 elseif ((!$cond) && ($elementName == 'im')) {
961 // IM service provider id, CRM-3140
962 $cond = "provider_id = '$elementType'";
964 $elementType = '-' . $elementType;
967 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
969 // hack for profile, add location id
972 // fix for CRM-882( to handle phone types )
973 !is_numeric($elementType)
975 if (is_numeric($name)) {
976 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
979 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
982 elseif (is_numeric($name)) {
983 //this for phone type to work
984 if (in_array($elementName, array('phone', 'phone_ext'))) {
985 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
988 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
992 //this is for phone type to work for profile edit
993 if (in_array($elementName, array('phone', 'phone_ext'))) {
994 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
997 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1002 // Check if there is a value, if so also add to where Clause
1004 if ($this->_params
) {
1006 if (isset($locationTypeId)) {
1007 $nm .= "-$locationTypeId";
1009 if (!is_numeric($elementType)) {
1010 $nm .= "$elementType";
1013 foreach ($this->_params
as $id => $values) {
1014 if ($values[0] == $nm ||
1015 (in_array($elementName, array('phone', 'im'))
1016 && (strpos($values[0], $nm) !== FALSE)
1026 if ($field && isset($field['where'])) {
1027 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1028 $pf = substr($tableName, 8);
1029 $tName = $name . '-' . $pf . $elementType;
1030 if (isset($tableName)) {
1031 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1032 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1035 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1038 $this->_element
["{$tName}_id"] = 1;
1039 if (substr($tName, -15) == '-state_province') {
1040 // FIXME: hack to fix CRM-1900
1041 $a = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1045 if (substr_count($a, 'state_province_name') > 0) {
1046 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1047 array('pseudoField' => '{$pf}_id', 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1048 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1051 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1052 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id");
1053 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1057 if (substr($elementFullName, 0, 2) == 'im') {
1058 $provider = "{$name}-{$elementFullName}-provider_id";
1059 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1060 $this->_element
[$provider] = 1;
1062 if ($pf == 'country' ||
$pf == 'county') {
1063 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array('pseudoField' => "{$pf}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1064 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1067 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1071 if (in_array($pf, array('state_province', 'country', 'county'))) {
1072 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1075 $this->_element
["{$name}-{$elementFullName}"] = 1;
1078 if (!CRM_Utils_Array
::value("`$tName`", $processed)) {
1079 $processed["`$tName`"] = 1;
1080 $newName = $tableName . '_' . $index;
1081 switch ($tableName) {
1082 case 'civicrm_phone':
1083 case 'civicrm_email':
1085 case 'civicrm_openid':
1087 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id AND `$tName`.$lCond";
1088 // this special case to add phone type
1090 $phoneTypeCondition = " AND `$tName`.$cond ";
1091 //gross hack to pickup corrupted data also, CRM-7603
1092 if (strpos($cond, 'phone_type_id') !== FALSE) {
1093 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1095 $this->_tables
[$tName] .= $phoneTypeCondition;
1098 //build locationType join
1099 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1102 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1106 case 'civicrm_state_province':
1107 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1108 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1109 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1111 $this->_whereTables
["{$name}-address"] = $addressJoin;
1115 case 'civicrm_country':
1116 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1117 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1118 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1120 $this->_whereTables
["{$name}-address"] = $addressJoin;
1124 case 'civicrm_county':
1125 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1126 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1127 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1129 $this->_whereTables
["{$name}-address"] = $addressJoin;
1135 $this->_whereTables
["{$name}-address"] = $addressJoin;
1144 // add location type join
1145 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1146 $this->_tables
[$locationTypeName] = $ltypeJoin;
1148 // table should be present in $this->_whereTables,
1149 // to add its condition in location type join, CRM-3939.
1150 if ($addWhereCount) {
1151 $locClause = array();
1152 foreach ($this->_whereTables
as $tableName => $clause) {
1153 if (CRM_Utils_Array
::value($tableName, $locationTypeJoin)) {
1154 $locClause[] = $locationTypeJoin[$tableName];
1158 if (!empty($locClause)) {
1159 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1164 if (!empty($addressCustomFieldIds)) {
1165 $cfIDs = $addressCustomFieldIds;
1166 $customQuery = new CRM_Core_BAO_CustomQuery($cfIDs);
1167 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1168 foreach ($locTypeName as $name => $dnc) {
1169 $fieldName = "$name-custom_{$cfID}";
1170 $tName = "$name-address-custom-{$cfID}";
1171 $aName = "`$name-address-custom-{$cfID}`";
1172 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1173 $this->_element
["{$tName}_id"] = 1;
1174 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1175 $this->_element
[$fieldName] = 1;
1176 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1183 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
1189 function addMultipleElements() {
1190 if (!CRM_Utils_Array
::value('website', $this->_returnProperties
)) {
1193 if (!is_array($this->_returnProperties
['website'])) {
1197 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1198 foreach ($elements as $elementFullName => $dontCare) {
1199 $tName = "website-{$key}-{$elementFullName}";
1200 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1201 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1202 $this->_element
["{$tName}_id"] = 1;
1203 $this->_element
["{$tName}"] = 1;
1205 $type = "website-{$key}-website_type_id";
1206 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1207 $this->_element
[$type] = 1;
1208 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id )";
1214 * generate the query based on what type of query we need
1216 * @param boolean $count
1217 * @param boolean $sortByChar
1218 * @param boolean $groupContacts
1220 * @return the sql string for that query (this will most likely
1224 function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE) {
1226 if (isset($this->_distinctComponentClause
)) {
1227 // we add distinct to get the right count for components
1228 // for the more complex result set, we use GROUP BY the same id
1230 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1233 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1235 $from = $this->_simpleFromClause
;
1236 if ($this->_useDistinct
) {
1237 $this->_useGroupBy
= TRUE;
1240 elseif ($sortByChar) {
1241 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1242 $from = $this->_simpleFromClause
;
1244 elseif ($groupContacts) {
1245 $select = 'SELECT contact_a.id as id';
1246 if ($this->_useDistinct
) {
1247 $this->_useGroupBy
= TRUE;
1249 $from = $this->_simpleFromClause
;
1252 if (CRM_Utils_Array
::value('group', $this->_paramLookup
)) {
1253 // make sure there is only one element
1254 // this is used when we are running under smog and need to know
1255 // how the contact was added (CRM-1203)
1256 if ((count($this->_paramLookup
['group']) == 1) &&
1257 (count($this->_paramLookup
['group'][0][2]) == 1)
1259 $groups = array_keys($this->_paramLookup
['group'][0][2]);
1260 $groupId = $groups[0];
1262 //check if group is saved search
1263 $group = new CRM_Contact_BAO_Group();
1264 $group->id
= $groupId;
1267 if (!isset($group->saved_search_id
)) {
1268 $tbName = "`civicrm_group_contact-{$groupId}`";
1269 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1270 $this->_element
['group_contact_id'] = 1;
1271 $this->_select
['status'] = "$tbName.status as status";
1272 $this->_element
['status'] = 1;
1273 $this->_tables
[$tbName] = 1;
1276 $this->_useGroupBy
= TRUE;
1278 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1279 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1281 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1282 $this->_useDistinct
= FALSE;
1283 $this->_useGroupBy
= TRUE;
1287 $select = "SELECT ";
1288 if (isset($this->_distinctComponentClause
)) {
1289 $select .= "{$this->_distinctComponentClause}, ";
1291 $select .= implode(', ', $this->_select
);
1292 $from = $this->_fromClause
;
1296 if (!empty($this->_whereClause
)) {
1297 $where = "WHERE {$this->_whereClause}";
1301 if (!empty($this->_having
)) {
1302 foreach ($this->_having
as $havingsets) {
1303 foreach ($havingsets as $havingset) {
1304 $havingvalue[] = $havingset;
1307 $having = ' HAVING ' . implode(' AND ', $havingvalue);
1310 // if we are doing a transform, do it here
1311 // use the $from, $where and $having to get the contact ID
1312 if ($this->_displayRelationshipType
) {
1313 $this->filterRelatedContacts($from, $where, $having);
1316 return array($select, $from, $where, $having);
1319 function &getWhereValues($name, $grouping) {
1321 foreach ($this->_params
as $values) {
1322 if ($values[0] == $name && $values[3] == $grouping) {
1330 static function fixDateValues($relative, &$from, &$to) {
1332 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1336 static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE) {
1338 if (empty($formValues)) {
1342 foreach ($formValues as $id => $values) {
1343 if ($id == 'privacy') {
1344 if (is_array($formValues['privacy'])) {
1345 $op = CRM_Utils_Array
::value('do_not_toggle', $formValues['privacy']) ?
'=' : '!=';
1346 foreach ($formValues['privacy'] as $key => $value) {
1348 $params[] = array($key, $op, $value, 0, 0);
1353 elseif ($id == 'email_on_hold') {
1354 if ($formValues['email_on_hold']['on_hold']) {
1355 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1358 elseif (preg_match('/_date_relative$/', $id) ||
1359 $id == 'event_relative' ||
1360 $id == 'case_from_relative' ||
1361 $id == 'case_to_relative'
1363 if ($id == 'event_relative') {
1364 $fromRange = 'event_start_date_low';
1365 $toRange = 'event_end_date_high';
1367 else if ($id == 'case_from_relative') {
1368 $fromRange = 'case_from_start_date_low';
1369 $toRange = 'case_from_start_date_high';
1371 else if ($id == 'case_to_relative') {
1372 $fromRange = 'case_to_end_date_low';
1373 $toRange = 'case_to_end_date_high';
1376 $dateComponent = explode('_date_relative', $id);
1377 $fromRange = "{$dateComponent[0]}_date_low";
1378 $toRange = "{$dateComponent[0]}_date_high";
1381 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1382 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1387 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals);
1392 $params[] = $values;
1398 static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE) {
1399 // skip a few search variables
1400 static $skipWhere = NULL;
1401 static $arrayValues = NULL;
1402 static $likeNames = NULL;
1405 if (CRM_Utils_System
::isNull($values)) {
1411 'task', 'radio_ts', 'uf_group_id',
1412 'component_mode', 'qfKey', 'operator',
1413 'display_relationship_type',
1417 if (in_array($id, $skipWhere) ||
1418 substr($id, 0, 4) == '_qf_' ||
1419 substr($id, 0, 7) == 'hidden_'
1425 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1428 // email comes in via advanced search
1429 // so use wildcard always
1430 if ($id == 'email') {
1434 if (!$useEquals && in_array($id, $likeNames)) {
1435 $result = array($id, 'LIKE', $values, 0, 1);
1437 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1438 $result = array($id, 'LIKE', $values, 0, 0);
1440 elseif ($id == 'group') {
1441 if (is_array($values)) {
1442 foreach ($values as $groupIds => $val) {
1444 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1445 if (strlen($matches[1]) > 0) {
1446 $values[$matches[1]] = 1;
1447 unset($values[$groupIds]);
1453 $groupIds = explode(',', $values);
1455 foreach ($groupIds as $groupId) {
1456 $values[$groupId] = 1;
1460 $result = array($id, 'IN', $values, 0, 0);
1462 elseif ($id == 'contact_tags' ||
$id == 'tag') {
1463 if (!is_array($values)) {
1464 $tagIds = explode(',', $values);
1466 foreach ($tagIds as $tagId) {
1467 $values[$tagId] = 1;
1470 $result = array($id, 'IN', $values, 0, 0);
1473 $result = array($id, '=', $values, 0, $wildcard);
1479 function whereClauseSingle(&$values) {
1480 // do not process custom fields or prefixed contact ids or component params
1481 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1482 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1483 (substr($values[0], 0, 13) == 'contribution_') ||
1484 (substr($values[0], 0, 6) == 'event_') ||
1485 (substr($values[0], 0, 12) == 'participant_') ||
1486 (substr($values[0], 0, 7) == 'member_') ||
1487 (substr($values[0], 0, 6) == 'grant_') ||
1488 (substr($values[0], 0, 7) == 'pledge_') ||
1489 (substr($values[0], 0, 5) == 'case_') ||
1490 (substr($values[0], 0, 10) == 'financial_') ||
1491 (substr($values[0], 0, 11) == 'membership_')
1496 // skip for hook injected fields / params
1497 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1498 if (array_key_exists($values[0], $extFields)) {
1502 switch ($values[0]) {
1503 case 'deleted_contacts':
1504 $this->deletedContacts($values);
1507 case 'contact_type':
1508 $this->contactType($values);
1511 case 'contact_sub_type':
1512 $this->contactSubType($values);
1516 list($name, $op, $value, $grouping, $wildcard) = $values;
1517 $this->group($values);
1520 // so we resolve this into a list of groups & proceed as if they had been
1522 list($name, $op, $value, $grouping, $wildcard) = $values;
1523 $values[0] = 'group';
1525 $this->_paramLookup
['group'][0][0] ='group';
1526 $this->_paramLookup
['group'][0][1] = 'IN';
1527 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1528 $this->group($values);
1530 // case tag comes from find contacts
1533 $this->tagSearch($values);
1537 case 'contact_tags':
1538 $this->tag($values);
1543 case 'note_subject':
1544 $this->notes($values);
1548 $this->ufUser($values);
1552 case 'display_name':
1553 $this->sortName($values);
1557 $this->email($values);
1560 case 'phone_numeric':
1561 $this->phone_numeric($values);
1564 case 'phone_phone_type_id':
1565 case 'phone_location_type_id':
1566 $this->phone_option_group($values);
1569 case 'street_address':
1570 $this->street_address($values);
1573 case 'street_number':
1574 $this->street_number($values);
1577 case 'sortByCharacter':
1578 $this->sortByCharacter($values);
1581 case 'location_type':
1582 $this->locationType($values);
1586 $this->county($values);
1589 case 'state_province':
1590 $this->stateProvince($values);
1594 $this->country($values, FALSE);
1598 case 'postal_code_low':
1599 case 'postal_code_high':
1600 $this->postalCode($values);
1603 case 'activity_date':
1604 case 'activity_date_low':
1605 case 'activity_date_high':
1606 case 'activity_role':
1607 case 'activity_status':
1608 case 'activity_subject':
1609 case 'test_activities':
1610 case 'activity_type_id':
1611 case 'activity_survey_id':
1612 case 'activity_tags':
1613 case 'activity_taglist':
1614 case 'activity_test':
1615 case 'activity_contact_name':
1616 case 'activity_campaign_id':
1617 case 'activity_engagement_level':
1619 case 'source_contact':
1620 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1623 case 'birth_date_low':
1624 case 'birth_date_high':
1625 case 'deceased_date_low':
1626 case 'deceased_date_high':
1627 $this->demographics($values);
1630 case 'log_date_low':
1631 case 'log_date_high':
1632 $this->modifiedDates($values);
1636 $this->changeLog($values);
1639 case 'do_not_phone':
1640 case 'do_not_email':
1643 case 'do_not_trade':
1645 $this->privacy($values);
1648 case 'privacy_options':
1649 $this->privacyOptions($values);
1652 case 'privacy_operator':
1653 case 'privacy_toggle':
1654 // these are handled by privacy options
1657 case 'preferred_communication_method':
1658 $this->preferredCommunication($values);
1661 case 'relation_type_id':
1662 case 'relation_start_date_high':
1663 case 'relation_start_date_low':
1664 case 'relation_end_date_high':
1665 case 'relation_end_date_low':
1666 $this->relationship($values);
1667 $this->_relationshipValuesAdded
= TRUE;
1670 case 'relation_target_name':
1671 case 'relation_status':
1672 case 'relation_date_low':
1673 case 'relation_date_high':
1674 // since this case is handled with the above
1677 case 'task_status_id':
1678 $this->task($values);
1682 // since this case is handled with the above
1685 case 'prox_distance':
1686 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1689 case 'prox_street_address':
1691 case 'prox_postal_code':
1692 case 'prox_state_province_id':
1693 case 'prox_country_id':
1694 // handled by the proximity_distance clause
1698 $this->restWhere($values);
1704 * Given a list of conditions in params generate the required
1710 function whereClause() {
1711 $this->_where
[0] = array();
1712 $this->_qill
[0] = array();
1714 $config = CRM_Core_Config
::singleton();
1716 $this->includeContactIds();
1717 if (!empty($this->_params
)) {
1719 foreach (array_keys($this->_params
) as $id) {
1720 if (!CRM_Utils_Array
::value(0, $this->_params
[$id])) {
1723 // check for both id and contact_id
1724 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
1726 $this->_params
[$id][1] == 'IS NULL' ||
1727 $this->_params
[$id][1] == 'IS NOT NULL'
1729 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]}";
1731 elseif (is_array($this->_params
[$id][2])) {
1732 $idList = implode("','", $this->_params
[$id][2]);
1733 $this->_where
[0][] = "contact_a.id IN ({$idList})";
1736 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]} {$this->_params[$id][2]}";
1740 $this->whereClauseSingle($this->_params
[$id]);
1744 CRM_Core_Component
::alterQuery($this, 'where');
1746 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
1749 if ($this->_customQuery
) {
1750 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1751 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1752 if (!empty($this->_customQuery
->_where
)) {
1753 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
1756 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
1760 $andClauses = array();
1763 if (!empty($this->_where
)) {
1764 foreach ($this->_where
as $grouping => $values) {
1765 if ($grouping > 0 && !empty($values)) {
1766 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1771 if (!empty($this->_where
[0])) {
1772 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
1774 if (!empty($clauses)) {
1775 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1778 if ($validClauses > 1) {
1779 $this->_useDistinct
= TRUE;
1783 return implode(' AND ', $andClauses);
1786 function restWhere(&$values) {
1787 $name = CRM_Utils_Array
::value(0, $values);
1788 $op = CRM_Utils_Array
::value(1, $values);
1789 $value = CRM_Utils_Array
::value(2, $values);
1790 $grouping = CRM_Utils_Array
::value(3, $values);
1791 $wildcard = CRM_Utils_Array
::value(4, $values);
1793 if (isset($grouping) && !CRM_Utils_Array
::value($grouping, $this->_where
)) {
1794 $this->_where
[$grouping] = array();
1797 $multipleFields = array('url');
1799 //check if the location type exits for fields
1801 $locType = explode('-', $name);
1803 if (!in_array($locType[0], $multipleFields)) {
1804 //add phone type if exists
1805 if (isset($locType[2]) && $locType[2]) {
1806 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
1810 $field = CRM_Utils_Array
::value($name, $this->_fields
);
1813 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
1822 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
1823 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1825 if (substr($name, 0, 14) === 'state_province') {
1827 if (isset($locType[1]) && is_numeric($locType[1])) {
1828 $aName = "{$locationType[$locType[1]]}-address";
1829 $where = "`$aName`.state_province_id";
1832 $where = "civicrm_address.state_province_id";
1835 $states = CRM_Core_PseudoConstant
::stateProvince();
1836 if (is_numeric($value)) {
1837 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1838 $value = $states[(int ) $value];
1841 $intVal = CRM_Utils_Array
::key($value, $states);
1842 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1845 $this->_qill
[$grouping][] = ts('State') . " $op '$value'";
1848 $this->_qill
[$grouping][] = ts('State') . " ($lType) $op '$value'";
1851 elseif (!empty($field['pseudoconstant'])) {
1852 $this->optionValueQuery(
1853 $name, $op, $value, $grouping,
1854 CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', $field['name']),
1860 if ($name == 'gender_id') {
1861 self
::$_openedPanes[ts('Demographics')] = TRUE;
1864 elseif (substr($name, 0, 7) === 'country') {
1866 if (isset($locType[1]) && is_numeric($locType[1])) {
1867 $aName = "{$locationType[$locType[1]]}-address";
1868 $where = "`$aName`.country_id";
1871 $where = "civicrm_address.country_id";
1874 $countries = CRM_Core_PseudoConstant
::country();
1875 if (is_numeric($value)) {
1876 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1877 $value = $countries[(int ) $value];
1880 $intVal = CRM_Utils_Array
::key($value, $countries);
1881 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1884 $this->_qill
[$grouping][] = ts('Country') . " $op '$value'";
1887 $this->_qill
[$grouping][] = ts('Country') . " ($lType) $op '$value'";
1890 elseif (substr($name, 0, 6) === 'county') {
1892 if (isset($locType[1]) && is_numeric($locType[1])) {
1893 $aName = "{$locationType[$locType[1]]}-address";
1894 $where = "`$aName`.county_id";
1897 $where = "civicrm_address.county_id";
1900 $counties = CRM_Core_PseudoConstant
::county();
1901 if (is_numeric($value)) {
1902 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1903 $value = $counties[(int ) $value];
1906 $intVal = CRM_Utils_Array
::key($value, $counties);
1907 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1911 $this->_qill
[$grouping][] = ts('County') . " $op '$value'";
1914 $this->_qill
[$grouping][] = ts('County') . " ($lType) $op '$value'";
1917 elseif ($name === 'world_region') {
1918 $this->optionValueQuery(
1919 $name, $op, $value, $grouping,
1920 CRM_Core_PseudoConstant
::worldRegion(),
1925 elseif ($name === 'birth_date') {
1926 $date = CRM_Utils_Date
::processDate($value);
1927 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
1930 $date = CRM_Utils_Date
::customFormat($date);
1931 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
1934 $this->_qill
[$grouping][] = "$field[title] $op";
1936 self
::$_openedPanes[ts('Demographics')] = TRUE;
1938 elseif ($name === 'deceased_date') {
1939 $date = CRM_Utils_Date
::processDate($value);
1940 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
1942 $date = CRM_Utils_Date
::customFormat($date);
1943 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
1946 $this->_qill
[$grouping][] = "$field[title] $op";
1948 self
::$_openedPanes[ts('Demographics')] = TRUE;
1950 elseif ($name === 'is_deceased') {
1951 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
1952 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
1953 self
::$_openedPanes[ts('Demographics')] = TRUE;
1955 elseif ($name === 'contact_id') {
1956 if (is_int($value)) {
1957 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
1958 $this->_qill
[$grouping][] = "$field[title] $op $value";
1961 elseif ($name === 'name') {
1962 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
1964 $value = "%$value%";
1967 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
1968 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
1969 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
1971 elseif ($name === 'current_employer') {
1972 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
1974 $value = "%$value%";
1977 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
1978 $this->_where
[$grouping][] = self
::buildClause($wc, $op,
1979 "'$value' AND contact_a.contact_type ='Individual'"
1981 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
1983 elseif ($name === 'email_greeting') {
1984 $filterCondition = array('greeting_type' => 'email_greeting');
1985 $this->optionValueQuery(
1986 $name, $op, $value, $grouping,
1987 CRM_Core_PseudoConstant
::greeting($filterCondition),
1989 ts('Email Greeting')
1992 elseif ($name === 'postal_greeting') {
1993 $filterCondition = array('greeting_type' => 'postal_greeting');
1994 $this->optionValueQuery(
1995 $name, $op, $value, $grouping,
1996 CRM_Core_PseudoConstant
::greeting($filterCondition),
1998 ts('Postal Greeting')
2001 elseif ($name === 'addressee') {
2002 $filterCondition = array('greeting_type' => 'addressee');
2003 $this->optionValueQuery(
2004 $name, $op, $value, $grouping,
2005 CRM_Core_PseudoConstant
::greeting($filterCondition),
2010 elseif (substr($name, 0, 4) === 'url-') {
2011 $tName = 'civicrm_website';
2012 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2013 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2015 $value = "%$value%";
2019 $wc = 'civicrm_website.url';
2020 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2021 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2023 elseif ($name === 'contact_is_deleted') {
2024 $this->_where
[$grouping][] = self
::buildClause("contact_a.is_deleted", $op, $value);
2025 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2028 // sometime the value is an array, need to investigate and fix
2029 if (is_array($value)) {
2030 CRM_Core_Error
::fatal();
2033 if (!empty($field['where'])) {
2035 $value = $strtolower($value);
2038 $value = "%$value%";
2042 if (isset($locType[1]) &&
2043 is_numeric($locType[1])
2047 //get the location name
2048 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2050 $where = "`$tName`.$fldName";
2052 $this->_where
[$grouping][] = self
::buildClause("LOWER($where)", $op, $value);
2053 $this->_whereTables
[$tName] = $this->_tables
[$tName];
2054 $this->_qill
[$grouping][] = "$field[title] $op '$value'";
2057 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2058 if ($tableName == 'civicrm_contact') {
2059 $fieldName = "LOWER(contact_a.{$fieldName})";
2062 if ($op != 'IN' && !is_numeric($value)) {
2063 $fieldName = "LOWER({$field['where']})";
2066 $fieldName = "{$field['where']}";
2071 if (CRM_Utils_Array
::value('type', $field)) {
2072 $type = CRM_Utils_Type
::typeToString($field['type']);
2075 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2076 $this->_qill
[$grouping][] = "$field[title] $op $value";
2081 if ($setTables && isset($field['where'])) {
2082 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2083 if (isset($tableName)) {
2084 $this->_tables
[$tableName] = 1;
2085 $this->_whereTables
[$tableName] = 1;
2091 static function getLocationTableName(&$where, &$locType) {
2092 if (isset($locType[1]) && is_numeric($locType[1])) {
2093 list($tbName, $fldName) = explode(".", $where);
2095 //get the location name
2096 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2097 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2098 if (in_array($locType[0], $specialFields)) {
2099 //hack to fix / special handing for phone_ext
2100 if ($locType[0] == 'phone_ext') {
2101 $locType[0] = 'phone';
2103 if (isset($locType[2]) && $locType[2]) {
2104 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2107 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2110 elseif (in_array($locType[0],
2112 'address_name', 'street_address', 'supplemental_address_1', 'supplemental_address_2',
2113 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
2116 //fix for search by profile with address fields.
2117 $tName = "{$locationType[$locType[1]]}-address";
2119 elseif ($locType[0] == 'on_hold') {
2120 $tName = "{$locationType[$locType[1]]}-email";
2123 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2125 $tName = str_replace(' ', '_', $tName);
2126 return array($tName, $fldName);
2128 CRM_Core_Error
::fatal();
2132 * Given a result dao, extract the values and return that array
2134 * @param Object $dao
2136 * @return array values for this query
2138 function store($dao) {
2141 foreach ($this->_element
as $key => $dontCare) {
2142 if (property_exists($dao, $key)) {
2143 if (strpos($key, '-') !== FALSE) {
2144 $values = explode('-', $key);
2145 $lastElement = array_pop($values);
2147 $cnt = count($values);
2149 foreach ($values as $v) {
2150 if (!array_key_exists($v, $current)) {
2151 $current[$v] = array();
2153 //bad hack for im_provider
2154 if ($lastElement == 'provider_id') {
2155 if ($count < $cnt) {
2156 $current = &$current[$v];
2159 $lastElement = "{$v}_{$lastElement}";
2163 $current = &$current[$v];
2168 $current[$lastElement] = $dao->$key;
2171 $value[$key] = $dao->$key;
2179 * getter for tables array
2185 return $this->_tables
;
2188 function whereTables() {
2189 return $this->_whereTables
;
2193 * generate the where clause (used in match contacts and permissions)
2195 * @param array $params
2196 * @param array $fields
2197 * @param array $tables
2198 * @param boolean $strict
2204 static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2205 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2209 $tables = array_merge($query->tables(), $tables);
2210 $whereTables = array_merge($query->whereTables(), $whereTables);
2212 return $query->_whereClause
;
2216 * create the from clause
2218 * @param array $tables tables that need to be included in this from clause
2219 * if null, return mimimal from clause (i.e. civicrm_contact)
2220 * @param array $inner tables that should be inner-joined
2221 * @param array $right tables that should be right-joined
2223 * @return string the from clause
2227 static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2229 $from = ' FROM civicrm_contact contact_a';
2230 if (empty($tables)) {
2234 if (CRM_Utils_Array
::value('civicrm_worldregion', $tables)) {
2235 $tables = array_merge(array('civicrm_country' => 1), $tables);
2238 if ((CRM_Utils_Array
::value('civicrm_state_province', $tables) ||
2239 CRM_Utils_Array
::value('civicrm_country', $tables) ||
2240 CRM_Utils_Array
::value('civicrm_county', $tables)
2242 !CRM_Utils_Array
::value('civicrm_address', $tables)
2244 $tables = array_merge(array('civicrm_address' => 1),
2249 // add group_contact table if group table is present
2250 if (CRM_Utils_Array
::value('civicrm_group', $tables) &&
2251 !CRM_Utils_Array
::value('civicrm_group_contact', $tables)
2253 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
2256 // add group_contact and group table is subscription history is present
2257 if (CRM_Utils_Array
::value('civicrm_subscription_history', $tables)
2258 && !CRM_Utils_Array
::value('civicrm_group', $tables)
2260 $tables = array_merge(array(
2261 'civicrm_group' => 1,
2262 'civicrm_group_contact' => 1,
2268 // to handle table dependencies of components
2269 CRM_Core_Component
::tableNames($tables);
2270 // to handle table dependencies of hook injected tables
2271 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2273 //format the table list according to the weight
2274 $info = CRM_Core_TableHierarchy
::info();
2276 foreach ($tables as $key => $value) {
2278 if (strpos($key, '-') !== FALSE) {
2279 $keyArray = explode('-', $key);
2280 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2282 elseif (strpos($key, '_') !== FALSE) {
2283 $keyArray = explode('_', $key);
2284 if (is_numeric(array_pop($keyArray))) {
2285 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2288 $k = CRM_Utils_Array
::value($key, $info, 99);
2292 $k = CRM_Utils_Array
::value($key, $info, 99);
2294 $tempTable[$k . ".$key"] = $key;
2297 $newTables = array();
2298 foreach ($tempTable as $key) {
2299 $newTables[$key] = $tables[$key];
2302 $tables = $newTables;
2304 foreach ($tables as $name => $value) {
2309 if (CRM_Utils_Array
::value($name, $inner)) {
2312 elseif (CRM_Utils_Array
::value($name, $right)) {
2320 // if there is already a join statement in value, use value itself
2321 if (strpos($value, 'JOIN')) {
2322 $from .= " $value ";
2325 $from .= " $side JOIN $name ON ( $value ) ";
2330 case 'civicrm_address':
2331 if ($primaryLocation) {
2332 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2335 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2339 case 'civicrm_phone':
2340 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2343 case 'civicrm_email':
2344 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2348 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2352 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2353 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2354 $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)";
2357 case 'civicrm_openid':
2358 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2361 case 'civicrm_worldregion':
2362 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2363 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2366 case 'civicrm_location_type':
2367 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2370 case 'civicrm_group':
2371 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2374 case 'civicrm_group_contact':
2375 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2378 case 'civicrm_activity':
2379 case 'civicrm_activity_tag':
2380 case 'activity_type':
2381 case 'activity_status':
2382 case 'civicrm_activity_contact':
2383 case 'source_contact':
2384 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2387 case 'civicrm_entity_tag':
2388 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2389 civicrm_entity_tag.entity_id = contact_a.id ) ";
2392 case 'civicrm_note':
2393 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2394 contact_a.id = civicrm_note.entity_id ) ";
2397 case 'civicrm_subscription_history':
2398 $from .= " $side JOIN civicrm_subscription_history
2399 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2400 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2403 case 'civicrm_relationship':
2404 if (self
::$_relType == 'reciprocal') {
2405 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2406 $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)";
2408 elseif (self
::$_relType == 'b') {
2409 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2410 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2413 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2414 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2419 $from .= " $side JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2420 $from .= " $side JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2424 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2427 case 'civicrm_grant':
2428 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2431 case 'civicrm_website':
2432 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2436 $from .= CRM_Core_Component
::from($name, $mode, $side);
2437 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2447 * WHERE / QILL clause for deleted_contacts
2451 function deletedContacts($values) {
2452 list($_, $_, $value, $grouping, $_) = $values;
2454 // *prepend* to the relevant grouping as this is quite an important factor
2455 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2460 * where / qill clause for contact_type
2465 function contactType(&$values) {
2466 list($name, $op, $value, $grouping, $wildcard) = $values;
2468 $subTypes = array();
2471 // account for search builder mapping multiple values
2472 if (!is_array($value)) {
2473 $values = self
::parseSearchBuilderString($value, 'String');
2474 if (is_array($values)) {
2475 $value = array_flip($values);
2479 if (is_array($value)) {
2480 foreach ($value as $k => $v) {
2485 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2486 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2489 if (!empty($subType)) {
2490 $subTypes[$subType] = 1;
2492 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2497 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2498 $contactType = $contactTypeANDSubType[0];
2499 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2500 if (!empty($subType)) {
2501 $subTypes[$subType] = 1;
2503 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2507 if (!empty($clause)) {
2508 $this->_where
[$grouping][] = 'contact_a.contact_type IN (' . implode(',', $clause) . ')';
2509 $this->_qill
[$grouping][] = ts('Contact Type') . ' - ' . implode(' ' . ts('or') . ' ', $clause);
2511 if (!empty($subTypes)) {
2512 $this->includeContactSubTypes($subTypes, $grouping);
2518 * where / qill clause for contact_sub_type
2523 function contactSubType(&$values) {
2524 list($name, $op, $value, $grouping, $wildcard) = $values;
2525 $this->includeContactSubTypes($value, $grouping);
2528 function includeContactSubTypes($value, $grouping) {
2531 $alias = "contact_a.contact_sub_type";
2533 if (is_array($value)) {
2534 foreach ($value as $k => $v) {
2536 $clause[$k] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($k, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2541 $clause[$value] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2544 if (!empty($clause)) {
2545 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2546 $this->_qill
[$grouping][] = ts('Contact Subtype') . ' - ' . implode(' ' . ts('or') . ' ', array_keys($clause));
2551 * where / qill clause for groups
2556 function group(&$values) {
2557 list($name, $op, $value, $grouping, $wildcard) = $values;
2559 if (count($value) > 1) {
2560 $this->_useDistinct
= TRUE;
2563 $groupNames = CRM_Core_PseudoConstant
::group();
2564 $groupIds = implode(',', array_keys($value));
2567 foreach ($value as $id => $dontCare) {
2568 if (array_key_exists($id, $groupNames) && $dontCare) {
2569 $names[] = $groupNames[$id];
2575 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2577 is_array($gcsValues[2])
2579 foreach ($gcsValues[2] as $k => $v) {
2581 if ($k == 'Added') {
2584 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2589 $statii[] = '"Added"';
2594 if (count($value) == 1 &&
2595 count($statii) == 1 &&
2596 $statii[0] == '"Added"'
2598 // check if smart group, if so we can get rid of that one additional
2600 $groupIDs = array_keys($value);
2602 if (CRM_Utils_Array
::value(0, $groupIDs) &&
2603 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
2613 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2614 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON contact_a.id = {$gcTable}.contact_id ";
2617 $qill = ts('Contacts %1', array(1 => $op));
2618 $qill .= ' ' . implode(' ' . ts('or') . ' ', $names);
2620 $groupClause = NULL;
2623 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2624 if (!empty($statii)) {
2625 $groupClause .= " AND {$gcTable}.status IN (" . implode(', ', $statii) . ")";
2626 $qill .= " " . ts('AND') . " " . ts('Group Status') . ' - ' . implode(' ' . ts('or') . ' ', $statii);
2631 $ssClause = $this->savedSearch($values);
2634 $groupClause = "( ( $groupClause ) OR ( $ssClause ) )";
2637 $groupClause = $ssClause;
2642 $this->_where
[$grouping][] = $groupClause;
2643 $this->_qill
[$grouping][] = $qill;
2646 * Function translates selection of group type into a list of groups
2648 function getGroupsFromTypeCriteria($value){
2649 $groupIds = array();
2650 foreach ($value as $groupTypeValue) {
2651 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2652 $groupIds = ($groupIds +
$groupList);
2658 * where / qill clause for smart groups
2663 function savedSearch(&$values) {
2664 list($name, $op, $value, $grouping, $wildcard) = $values;
2665 return $this->addGroupContactCache(array_keys($value));
2668 function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
2669 $config = CRM_Core_Config
::singleton();
2671 // find all the groups that are part of a saved search
2672 $groupIDs = implode(',', $groups);
2673 if (empty($groupIDs)) {
2678 SELECT id, cache_date, saved_search_id, children
2680 WHERE id IN ( $groupIDs )
2681 AND ( saved_search_id != 0
2682 OR saved_search_id IS NOT NULL
2683 OR children IS NOT NULL )
2685 $group = CRM_Core_DAO
::executeQuery($sql);
2687 while ($group->fetch()) {
2688 if ($tableAlias == NULL) {
2689 $alias = "`civicrm_group_contact_cache_{$group->id}`";
2692 $alias = $tableAlias;
2695 $this->_useDistinct
= TRUE;
2697 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
2698 CRM_Contact_BAO_GroupContactCache
::load($group);
2701 $this->_tables
[$alias] = $this->_whereTables
[$alias] = " LEFT JOIN civicrm_group_contact_cache {$alias} ON {$joinTable}.id = {$alias}.contact_id ";
2702 $ssWhere[] = "{$alias}.group_id = {$group->id}";
2705 if (!empty($ssWhere)) {
2706 return implode(' OR ', $ssWhere);
2712 * where / qill clause for cms users
2717 function ufUser(&$values) {
2718 list($name, $op, $value, $grouping, $wildcard) = $values;
2721 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2723 $this->_qill
[$grouping][] = ts('CMS User');
2725 elseif ($value == 0) {
2726 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2728 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2729 $this->_qill
[$grouping][] = ts('Not a CMS User');
2734 * all tag search specific
2739 function tagSearch(&$values) {
2740 list($name, $op, $value, $grouping, $wildcard) = $values;
2743 $value = "%{$value}%";
2746 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2747 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2749 $etTable = "`civicrm_entity_tag-" . $value . "`";
2750 $tTable = "`civicrm_tag-" . $value . "`";
2752 if ($useAllTagTypes[2]) {
2753 $this->_tables
[$etTable] =
2754 $this->_whereTables
[$etTable] =
2755 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
2756 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
2758 // search tag in cases
2759 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2760 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
2761 $this->_tables
[$etCaseTable] =
2762 $this->_whereTables
[$etCaseTable] =
2763 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2764 LEFT JOIN civicrm_case
2765 ON (civicrm_case_contact.case_id = civicrm_case.id
2766 AND civicrm_case.is_deleted = 0 )
2767 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
2768 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
2769 // search tag in activities
2770 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2771 $tActTable = "`civicrm_act_tag-" . $value . "`";
2772 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2773 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2775 $this->_tables
[$etActTable] =
2776 $this->_whereTables
[$etActTable] =
2777 " LEFT JOIN civicrm_activity_contact
2778 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
2779 LEFT JOIN civicrm_activity
2780 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
2781 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2782 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
2783 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
2785 $this->_where
[$grouping][] = "({$tTable}.name $op '". $value . "' OR {$tCaseTable}.name $op '". $value . "' OR {$tActTable}.name $op '". $value . "')";
2786 $this->_qill
[$grouping][] = ts('Tag %1 %2 ', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
2788 $etTable = "`civicrm_entity_tag-" . $value . "`";
2789 $tTable = "`civicrm_tag-" . $value . "`";
2790 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
2791 {$etTable}.entity_table = 'civicrm_contact' )
2792 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
2794 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
2795 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
2800 * where / qill clause for tag
2805 function tag(&$values) {
2806 list($name, $op, $value, $grouping, $wildcard) = $values;
2808 $tagNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
2809 if (is_array($value)) {
2810 if (count($value) > 1) {
2811 $this->_useDistinct
= TRUE;
2813 foreach ($value as $id => $dontCare) {
2814 $names[] = CRM_Utils_Array
::value($id, $tagNames);
2816 $names = implode(' ' . ts('or') . ' ', $names);
2817 $value = implode(',', array_keys($value));
2820 $names = CRM_Utils_Array
::value($value, $tagNames);
2824 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2825 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2827 $etTable = "`civicrm_entity_tag-" . $value . "`";
2829 if ($useAllTagTypes[2]) {
2830 $this->_tables
[$etTable] =
2831 $this->_whereTables
[$etTable] =
2832 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2834 // search tag in cases
2835 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2836 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2837 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2839 $this->_tables
[$etCaseTable] =
2840 $this->_whereTables
[$etCaseTable] =
2841 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2842 LEFT JOIN civicrm_case
2843 ON (civicrm_case_contact.case_id = civicrm_case.id
2844 AND civicrm_case.is_deleted = 0 )
2845 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
2846 // search tag in activities
2847 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2848 $this->_tables
[$etActTable] =
2849 $this->_whereTables
[$etActTable] =
2850 " LEFT JOIN civicrm_activity_contact
2851 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
2852 LEFT JOIN civicrm_activity
2853 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
2854 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2855 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
2858 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
2859 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
2862 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (". $value . ") OR {$etCaseTable}.tag_id $op (". $value . ") OR {$etActTable}.tag_id $op (". $value . "))";
2864 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
2866 $this->_tables
[$etTable] =
2867 $this->_whereTables
[$etTable] =
2868 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2871 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
2872 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
2873 $op = str_replace('EMPTY', 'NULL', $op);
2874 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
2877 $this->_where
[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
2879 $this->_qill
[$grouping][] = ts('Tagged %1', array( 1 => $op)) . ' ' . $names;
2885 * where/qill clause for notes
2890 function notes(&$values) {
2891 list($name, $op, $value, $grouping, $wildcard) = $values;
2893 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
2894 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
2895 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
2897 $this->_useDistinct
= TRUE;
2899 $this->_tables
['civicrm_note'] =
2900 $this->_whereTables
['civicrm_note'] =
2901 " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
2903 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2905 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
2906 if ($wildcard ||
$op == 'LIKE') {
2907 if (strpos($value, '%') === FALSE) {
2908 $value = "%$value%";
2912 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
2918 if ( $noteOption %
2 == 0 ) {
2919 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
2920 $label = ts('Note: Body Only');
2922 if ( $noteOption %
3 == 0 ) {
2923 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
2924 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
2926 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
2927 $this->_qill
[$grouping][] = $label . " $op - '$n'";
2930 function nameNullOrEmptyOp($name, $op, $grouping) {
2934 $this->_where
[$grouping][] = "contact_a.$name $op";
2935 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
2939 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
2940 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
2943 case 'IS NOT EMPTY':
2944 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
2945 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
2954 * where / qill clause for sort_name
2959 function sortName(&$values) {
2960 list($name, $op, $value, $grouping, $wildcard) = $values;
2962 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
2963 if ( $this->nameNullOrEmptyOp( $name, $op, $grouping ) ) {
2968 $name = trim($value);
2974 $config = CRM_Core_Config
::singleton();
2978 //By default, $sub elements should be joined together with OR statements (don't change this variable).
2981 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2982 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2984 if (substr($name, 0, 1) == '"' &&
2985 substr($name, -1, 1) == '"'
2987 //If name is encased in double quotes, the value should be taken to be the string in entirety and the
2988 $value = substr($name, 1, -1);
2989 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2990 $wc = ($newName == 'sort_name') ?
'LOWER(contact_a.sort_name)' : 'LOWER(contact_a.display_name)';
2991 $sub[] = " ( $wc = '$value' ) ";
2992 if ($config->includeEmailInName
) {
2993 $sub[] = " ( civicrm_email.email = '$value' ) ";
2996 elseif (strpos($name, ',') !== FALSE) {
2997 // if we have a comma in the string, search for the entire string
2998 $value = $strtolower(CRM_Core_DAO
::escapeString($name));
3000 if ($config->includeWildCardInName
) {
3001 $value = "'%$value%'";
3004 $value = "'$value%'";
3009 $value = "'$value'";
3011 if ($newName == 'sort_name') {
3012 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3015 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3017 $sub[] = " ( $wc $op $value )";
3018 if ($config->includeNickNameInName
) {
3019 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3020 $sub[] = " ( $wc $op $value )";
3022 if ($config->includeEmailInName
) {
3023 $sub[] = " ( civicrm_email.email $op $value ) ";
3027 // the string should be treated as a series of keywords to be matched with match ANY OR
3028 // match ALL depending on Civi config settings (see CiviAdmin)
3030 // The Civi configuration setting can be overridden if the string *starts* with the case
3031 // insenstive strings 'AND:' or 'OR:'TO THINK ABOUT: what happens when someone searches
3032 // for the following "AND: 'a string in quotes'"? - probably nothing - it would make the
3033 // AND OR variable reduntant because there is only one search string?
3035 // Check to see if the $subGlue is overridden in the search text
3036 if (strtolower(substr($name, 0, 4)) == 'and:') {
3037 $name = substr($name, 4);
3040 if (strtolower(substr($name, 0, 3)) == 'or:') {
3041 $name = substr($name, 3);
3045 $firstChar = substr($name, 0, 1);
3046 $lastChar = substr($name, -1, 1);
3047 $quotes = array("'", '"');
3048 if ((strlen($name) > 2) && in_array($firstChar, $quotes) &&
3049 in_array($lastChar, $quotes)
3051 $name = substr($name, 1);
3052 $name = substr($name, 0, -1);
3053 $pieces = array($name);
3056 $pieces = explode(' ', $name);
3058 foreach ($pieces as $piece) {
3059 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($piece)));
3060 if (strlen($value)) {
3061 // Added If as a sanitization - without it, when you do an OR search, any string with
3062 // double spaces (i.e. " ") or that has a space after the keyword (e.g. "OR: ") will
3063 // return all contacts because it will include a condition similar to "OR contact
3064 // name LIKE '%'". It might be better to replace this with array_filter.
3065 $fieldsub = array();
3067 if ($config->includeWildCardInName
) {
3068 $value = "'%$value%'";
3071 $value = "'$value%'";
3076 $value = "'$value'";
3078 if ($newName == 'sort_name') {
3079 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3082 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3084 $fieldsub[] = " ( $wc $op $value )";
3085 if ($config->includeNickNameInName
) {
3086 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3087 $fieldsub[] = " ( $wc $op $value )";
3089 if ($config->includeEmailInName
) {
3090 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3092 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3093 // I seperated the glueing in two. The first stage should always be OR because we are searching for matches in *ANY* of these fields
3098 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3100 $this->_where
[$grouping][] = $sub;
3101 if ($config->includeEmailInName
) {
3102 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3103 $this->_qill
[$grouping][] = ts('Name or Email ') . "$op - '$name'";
3106 $this->_qill
[$grouping][] = ts('Name like') . " - '$name'";
3111 * where / qill clause for email
3116 function email(&$values) {
3117 list($name, $op, $value, $grouping, $wildcard) = $values;
3121 $config = CRM_Core_Config
::singleton();
3123 if (substr($n, 0, 1) == '"' &&
3124 substr($n, -1, 1) == '"'
3126 $n = substr($n, 1, -1);
3127 $value = strtolower(CRM_Core_DAO
::escapeString($n));
3128 $value = "'$value'";
3132 $value = strtolower($n);
3134 if (strpos($value, '%') === FALSE) {
3135 $value = "%{$value}%";
3140 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3141 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3144 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3145 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3148 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3152 * where / qill clause for phone number
3157 function phone_numeric(&$values) {
3158 list($name, $op, $value, $grouping, $wildcard) = $values;
3159 // Strip non-numeric characters
3160 $number = preg_replace('/[^\d]/', '', $value);
3162 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3163 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "%$number%", 'String');
3164 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3169 * where / qill clause for phone type/location
3174 function phone_option_group($values) {
3175 list($name, $op, $value, $grouping, $wildcard) = $values;
3176 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3177 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3178 $optionName = $options[$value];
3179 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3180 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3181 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3185 * where / qill clause for street_address
3190 function street_address(&$values) {
3191 list($name, $op, $value, $grouping, $wildcard) = $values;
3200 $value = strtolower($n);
3201 if (strpos($value, '%') === FALSE) {
3202 // only add wild card if not there
3203 $value = "%{$value}%";
3206 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3207 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3210 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3211 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3214 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3218 * where / qill clause for street_unit
3223 function street_number(&$values) {
3224 list($name, $op, $value, $grouping, $wildcard) = $values;
3232 if (strtolower($n) == 'odd') {
3233 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3234 $this->_qill
[$grouping][] = ts('Street Number is odd');
3236 elseif (strtolower($n) == 'even') {
3237 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3238 $this->_qill
[$grouping][] = ts('Street Number is even');
3241 $value = strtolower($n);
3243 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3244 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3247 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3251 * where / qill clause for sorting by character
3256 function sortByCharacter(&$values) {
3257 list($name, $op, $value, $grouping, $wildcard) = $values;
3259 $name = trim($value);
3260 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3261 $this->_where
[$grouping][] = $cond;
3262 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3266 * where / qill clause for including contact ids
3271 function includeContactIDs() {
3272 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3276 $contactIds = array();
3277 foreach ($this->_params
as $id => $values) {
3278 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3279 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3282 if (!empty($contactIds)) {
3283 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3288 * where / qill clause for postal code
3293 function postalCode(&$values) {
3294 // skip if the fields dont have anything to do with postal_code
3295 if (!CRM_Utils_Array
::value('postal_code', $this->_fields
)) {
3299 list($name, $op, $value, $grouping, $wildcard) = $values;
3301 // Handle numeric postal code range searches properly by casting the column as numeric
3302 if (is_numeric($value)) {
3303 $field = 'ROUND(civicrm_address.postal_code)';
3304 $val = CRM_Utils_Type
::escape($value, 'Integer');
3307 $field = 'civicrm_address.postal_code';
3308 $val = CRM_Utils_Type
::escape($value, 'String');
3311 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3313 if ($name == 'postal_code') {
3314 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3315 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3317 elseif ($name == 'postal_code_low') {
3318 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3319 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3321 elseif ($name == 'postal_code_high') {
3322 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3323 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3328 * where / qill clause for location type
3333 function locationType(&$values, $status = NULL) {
3334 list($name, $op, $value, $grouping, $wildcard) = $values;
3336 if (is_array($value)) {
3337 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', array_keys($value)) . ')';
3338 $this->_tables
['civicrm_address'] = 1;
3339 $this->_whereTables
['civicrm_address'] = 1;
3341 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3343 foreach (array_keys($value) as $id) {
3344 $names[] = $locationType[$id];
3347 $this->_primaryLocation
= FALSE;
3350 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3353 return implode(' ' . ts('or') . ' ', $names);
3358 function country(&$values, $fromStateProvince = TRUE) {
3359 list($name, $op, $value, $grouping, $wildcard) = $values;
3361 if (!$fromStateProvince) {
3362 $stateValues = $this->getWhereValues('state_province', $grouping);
3363 if (!empty($stateValues)) {
3364 // return back to caller if there are state province values
3365 // since that handles this case
3370 $countryClause = $countryQill = NULL;
3376 $this->_tables
['civicrm_address'] = 1;
3377 $this->_whereTables
['civicrm_address'] = 1;
3379 $countries = CRM_Core_PseudoConstant
::country();
3380 if (is_numeric($value)) {
3381 $countryClause = self
::buildClause(
3382 'civicrm_address.country_id',
3387 $countryName = $countries[(int ) $value];
3391 $intValues = self
::parseSearchBuilderString($value);
3392 if ($intValues && ($op == 'IN' ||
$op == 'NOT IN')) {
3393 $countryClause = self
::buildClause(
3394 'civicrm_address.country_id',
3399 $countryNames = array();
3400 foreach ($intValues as $v) {
3401 $countryNames[] = $countries[$v];
3403 $countryName = implode(',', $countryNames);
3406 $countries = CRM_Core_PseudoConstant
::country();
3407 $intVal = CRM_Utils_Array
::key($value, $countries);
3408 $countryClause = self
::buildClause(
3409 'civicrm_address.country_id',
3414 $countryName = $value;
3417 $countryQill = ts('Country') . " {$op} '$countryName'";
3419 if (!$fromStateProvince) {
3420 $this->_where
[$grouping][] = $countryClause;
3421 $this->_qill
[$grouping][] = $countryQill;
3425 if ($fromStateProvince) {
3426 if (!empty($countryClause)) {
3429 " ...AND... " . $countryQill,
3433 return array(NULL, NULL);
3439 * where / qill clause for county (if present)
3444 function county(&$values, $status = null) {
3445 list($name, $op, $value, $grouping, $wildcard) = $values;
3447 if (! is_array($value)) {
3448 // force the county to be an array
3449 $value = array($value);
3452 // check if the values are ids OR names of the counties
3453 $inputFormat = 'id';
3454 foreach ($value as $v) {
3455 if (!is_numeric($v)) {
3456 $inputFormat = 'name';
3464 else if ($op == '!=') {
3468 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3469 $op = str_replace('EMPTY', 'NULL', $op);
3472 if (in_array( $op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3473 $clause = "civicrm_address.county_id $op";
3475 elseif ($inputFormat == 'id') {
3476 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3478 $county = CRM_Core_PseudoConstant
::county();
3479 foreach ($value as $id) {
3480 $names[] = CRM_Utils_Array
::value($id, $county);
3484 $inputClause = array();
3485 $county = CRM_Core_PseudoConstant
::county();
3486 foreach ($value as $name) {
3487 $name = trim($name);
3488 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3490 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3493 $this->_tables
['civicrm_address'] = 1;
3494 $this->_whereTables
['civicrm_address'] = 1;
3496 $this->_where
[$grouping][] = $clause;
3498 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3500 return implode(' ' . ts('or') . ' ', $names);
3505 * where / qill clause for state/province AND country (if present)
3510 function stateProvince(&$values, $status = NULL) {
3511 list($name, $op, $value, $grouping, $wildcard) = $values;
3513 // quick escape for IS NULL
3514 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3517 else if (!is_array($value)) {
3518 // force the state to be an array
3519 // check if its in the mapper format!
3520 $values = self
::parseSearchBuilderString($value);
3521 if (is_array($values)) {
3525 $value = array($value);
3529 // check if the values are ids OR names of the states
3530 $inputFormat = 'id';
3532 foreach ($value as $v) {
3533 if (!is_numeric($v)) {
3534 $inputFormat = 'name';
3544 else if ($op == '!=') {
3548 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3549 $op = str_replace('EMPTY', 'NULL', $op);
3551 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3552 $stateClause = "civicrm_address.state_province_id $op";
3554 else if ($inputFormat == 'id') {
3555 if ($op != 'NOT IN') {
3558 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
3560 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3561 foreach ($value as $id) {
3562 $names[] = CRM_Utils_Array
::value($id, $stateProvince);
3566 $inputClause = array();
3567 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3568 foreach ($value as $name) {
3569 $name = trim($name);
3570 $inputClause[] = CRM_Utils_Array
::key($name, $stateProvince);
3572 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
3575 $this->_tables
['civicrm_address'] = 1;
3576 $this->_whereTables
['civicrm_address'] = 1;
3578 $countryValues = $this->getWhereValues('country', $grouping);
3579 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3581 if ($countryClause) {
3582 $clause = "( $stateClause AND $countryClause )";
3585 $clause = $stateClause;
3588 $this->_where
[$grouping][] = $clause;
3590 $this->_qill
[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3593 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
3598 * where / qill clause for change log
3603 function changeLog(&$values) {
3604 list($name, $op, $value, $grouping, $wildcard) = $values;
3606 $targetName = $this->getWhereValues('changed_by', $grouping);
3611 $name = trim($targetName[2]);
3612 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3613 $name = $targetName[4] ?
"%$name%" : $name;
3614 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3615 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3616 $this->_qill
[$grouping][] = ts('Changed by') . ": $name";
3619 function modifiedDates($values) {
3620 $this->_useDistinct
= TRUE;
3622 // CRM-11281, default to added date if not set
3623 $fieldTitle = ts('Added Date');
3625 foreach (array_keys($this->_params
) as $id) {
3626 if ($this->_params
[$id][0] == 'log_date') {
3627 if ($this->_params
[$id][2] == 2) {
3628 $fieldTitle = ts('Modified Date');
3633 $this->dateQueryBuilder($values,
3634 'civicrm_log', 'log_date', 'modified_date', $fieldTitle
3638 function demographics(&$values) {
3639 list($name, $op, $value, $grouping, $wildcard) = $values;
3641 if (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3643 $this->dateQueryBuilder($values,
3644 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3647 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3649 $this->dateQueryBuilder($values,
3650 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3654 self
::$_openedPanes[ts('Demographics')] = TRUE;
3657 function privacy(&$values) {
3658 list($name, $op, $value, $grouping, $wildcard) = $values;
3659 //fixed for profile search listing CRM-4633
3660 if (strpbrk($value, "[")) {
3661 $value = "'{$value}'";
3663 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3666 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3668 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3669 $title = $field ?
$field['title'] : $name;
3670 $this->_qill
[$grouping][] = "$title $op $value";
3673 function privacyOptions($values) {
3674 list($name, $op, $value, $grouping, $wildcard) = $values;
3676 if (empty($value) ||
!is_array($value)) {
3680 // get the operator and toggle values
3681 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3684 strtolower($opValues[2] == 'AND')
3689 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3691 if ($toggleValues &&
3692 $toggleValues[2] == 2
3699 foreach ($value as $dontCare => $pOption) {
3700 $clauses[] = " ( contact_a.{$pOption} $compareOP 1 ) ";
3701 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3702 $title = $field ?
$field['title'] : $pOption;
3703 $qill[] = " $title $compareOP 1 ";
3706 $this->_where
[$grouping][] = '( ' . implode($operator, $clauses) . ' )';
3707 $this->_qill
[$grouping][] = implode($operator, $qill);
3710 function preferredCommunication(&$values) {
3711 list($name, $op, $value, $grouping, $wildcard) = $values;
3714 if (!is_array($value)) {
3716 $value = trim($value, ' ()');
3717 if (strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
3718 $v = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
3721 $v = explode(",", $value);
3724 foreach ($v as $item) {
3731 foreach ($value as $key => $checked) {
3738 $commPref = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
3740 $sqlValue = array();
3741 $sql = "contact_a.preferred_communication_method";
3742 foreach ($pref as $val) {
3743 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $val . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' ) ";
3744 $showValue[] = $commPref[$val];
3746 $this->_where
[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
3747 $this->_qill
[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
3751 * where / qill clause for relationship
3756 function relationship(&$values) {
3757 list($name, $op, $value, $grouping, $wildcard) = $values;
3758 if($this->_relationshipValuesAdded
){
3761 // also get values array for relation_target_name
3762 // for relatinship search we always do wildcard
3763 $targetName = $this->getWhereValues('relation_target_name', $grouping);
3764 $relStatus = $this->getWhereValues('relation_status', $grouping);
3765 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
3767 $nameClause = $name = NULL;
3769 $name = trim($targetName[2]);
3770 if (substr($name, 0, 1) == '"' &&
3771 substr($name, -1, 1) == '"'
3773 $name = substr($name, 1, -1);
3774 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3775 $nameClause = "= '$name'";
3778 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3779 $nameClause = "LIKE '%{$name}%'";
3783 $rel = explode('_', $value);
3785 self
::$_relType = $rel[1];
3786 $params = array('id' => $rel[0]);
3787 $rTypeValues = array();
3788 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
3789 if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
3790 self
::$_relType = 'reciprocal';
3794 $this->_where
[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
3797 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
3798 $relTypeOrg = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
3799 $relTypeHou = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Household');
3800 $allRelationshipType = array();
3801 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
3802 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
3804 if ($nameClause ||
!$targetGroup) {
3805 $this->_qill
[$grouping][] = "$allRelationshipType[$value] $name";
3809 //check to see if the target contact is in specified group
3811 //add contacts from static groups
3812 $this->_tables
['civicrm_relationship_group_contact'] =
3813 $this->_whereTables
['civicrm_relationship_group_contact'] =
3814 " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = contact_b.id";
3815 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" . implode(",", $targetGroup[2]) . ") )";
3817 //add contacts from saved searches
3818 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
3820 //set the group where clause
3822 $groupWhere[] = "( " . $ssWhere . " )";
3824 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
3826 //Get the names of the target groups for the qill
3827 $groupNames = &CRM_Core_PseudoConstant
::group();
3828 $qillNames = array();
3829 foreach ($targetGroup[2] as $groupId) {
3830 if (array_key_exists($groupId, $groupNames)) {
3831 $qillNames[] = $groupNames[$groupId];
3834 $this->_qill
[$grouping][] = "$allRelationshipType[$value] ( " . implode(", ", $qillNames) . " )";
3837 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
3838 $today = date('Ymd');
3839 //check for active, inactive and all relation status
3840 if ($relStatus[2] == 0) {
3841 $this->_where
[$grouping][] = "(
3842 civicrm_relationship.is_active = 1 AND
3843 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
3844 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
3846 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
3848 elseif ($relStatus[2] == 1) {
3849 $this->_where
[$grouping][] = "(
3850 civicrm_relationship.is_active = 0 OR
3851 civicrm_relationship.end_date < {$today} OR
3852 civicrm_relationship.start_date > {$today}
3854 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
3857 $this->addRelationshipDateClauses($grouping);
3858 if(!empty($rType) && isset($rType->id
)){
3859 $this->_where
[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
3861 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
3862 $this->_useDistinct
= TRUE;
3863 $this->_relationshipValuesAdded
= TRUE;
3866 * Add start & end date criteria in
3867 * @param string $grouping
3869 function addRelationshipDateClauses($grouping){
3870 $dateValues = array();
3876 foreach ($dateTypes as $dateField){
3877 $dateValueLow = $this->getWhereValues('relation_'. $dateField .'_low', $grouping);
3878 $dateValueHigh= $this->getWhereValues('relation_'. $dateField .'_high', $grouping);
3879 if(!empty($dateValueLow)){
3880 $date = date('Ymd', strtotime($dateValueLow[2]));
3881 $this->_where
[$grouping][] = "civicrm_relationship.$dateField >= $date";
3882 $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);
3884 if(!empty($dateValueHigh)){
3885 $date = date('Ymd', strtotime($dateValueHigh[2]));
3886 $this->_where
[$grouping][] = "civicrm_relationship.$dateField <= $date";
3887 $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);
3892 * default set of return properties
3897 static function &defaultReturnProperties($mode = 1) {
3898 if (!isset(self
::$_defaultReturnProperties)) {
3899 self
::$_defaultReturnProperties = array();
3902 if (!isset(self
::$_defaultReturnProperties[$mode])) {
3903 // add activity return properties
3904 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
3905 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
3908 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
3911 if (empty(self
::$_defaultReturnProperties[$mode])) {
3912 self
::$_defaultReturnProperties[$mode] = array(
3915 'legal_identifier' => 1,
3916 'external_identifier' => 1,
3917 'contact_type' => 1,
3918 'contact_sub_type' => 1,
3920 'display_name' => 1,
3921 'preferred_mail_format' => 1,
3926 'individual_prefix' => 1,
3927 'individual_suffix' => 1,
3930 'street_address' => 1,
3931 'supplemental_address_1' => 1,
3932 'supplemental_address_2' => 1,
3935 'postal_code_suffix' => 1,
3936 'state_province' => 1,
3938 'world_region' => 1,
3945 'household_name' => 1,
3946 'organization_name' => 1,
3947 'deceased_date' => 1,
3952 'current_employer' => 1,
3953 // FIXME: should we use defaultHierReturnProperties() for the below?
3954 'do_not_email' => 1,
3957 'do_not_phone' => 1,
3958 'do_not_trade' => 1,
3960 'contact_is_deleted' => 1,
3964 return self
::$_defaultReturnProperties[$mode];
3968 * get primary condition for a sql clause
3975 static function getPrimaryCondition($value) {
3976 if (is_numeric($value)) {
3977 $value = (int ) $value;
3978 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
3984 * wrapper for a simple search query
3986 * @param array $params
3987 * @param array $returnProperties
3988 * @param bolean $count
3993 static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
3994 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
3995 list($select, $from, $where, $having) = $query->query();
3997 return "$select $from $where $having";
4001 * These are stub comments as this function needs more explanation - particularly in terms of how it
4002 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4004 * This function was originally written as a wrapper for the api query but is called from multiple places
4005 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4006 * but it is unclear as to whehter that is historical or there is a reason
4007 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4009 * @param array $params
4010 * @param array $returnProperties
4011 * @param string $sort
4012 * @param int $offset
4013 * @param int $row_count
4014 * @params bool $smartGroupCache ?? update smart group cache?
4015 * @param bool $count return count obnly
4016 * @param bool $skipPermissions Should permissions be ignored or should the logged in user's permissions be applied
4021 static function apiQuery(
4023 $returnProperties = NULL,
4028 $smartGroupCache = TRUE,
4030 $skipPermissions = TRUE
4033 $query = new CRM_Contact_BAO_Query(
4034 $params, $returnProperties,
4035 NULL, TRUE, FALSE, 1,
4037 TRUE, $smartGroupCache
4040 //this should add a check for view deleted if permissions are enabled
4041 if ($skipPermissions){
4042 $query->_skipDeleteClause
= TRUE;
4044 $query->generatePermissionClause(FALSE, $count);
4046 // note : this modifies _fromClause and _simpleFromClause
4047 $query->includePseudoFieldsJoin($sort);
4049 list($select, $from, $where, $having) = $query->query($count);
4051 $options = $query->_options
;
4052 if(!empty($query->_permissionWhereClause
)){
4053 if (empty($where)) {
4054 $where = "WHERE $query->_permissionWhereClause";
4057 $where = "$where AND $query->_permissionWhereClause";
4061 $sql = "$select $from $where $having";
4064 if ($query->_useGroupBy
) {
4065 $sql .= ' GROUP BY contact_a.id';
4067 if (!empty($sort)) {
4068 $sql .= " ORDER BY $sort ";
4070 if ($row_count > 0 && $offset >= 0) {
4071 $sql .= " LIMIT $offset, $row_count ";
4074 $dao = CRM_Core_DAO
::executeQuery($sql);
4077 while ($dao->fetch()) {
4079 $noRows = $dao->rowCount
;
4081 return array($noRows,NULL);
4083 $val = $query->store($dao);
4084 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4086 if (!empty($convertedVals)) {
4087 $val = array_merge_recursive($val, $convertedVals);
4089 $values[$dao->contact_id
] = $val;
4092 return array($values, $options);
4096 * create and query the db for an contact search
4098 * @param int $offset the offset for the query
4099 * @param int $rowCount the number of rows to return
4100 * @param string $sort the order by string
4101 * @param boolean $count is this a count only query ?
4102 * @param boolean $includeContactIds should we include contact ids?
4103 * @param boolean $sortByChar if true returns the distinct array of first characters for search results
4104 * @param boolean $groupContacts if true, return only the contact ids
4105 * @param boolean $returnQuery should we return the query as a string
4106 * @param string $additionalWhereClause if the caller wants to further restrict the search (used for components)
4107 * @param string $additionalFromClause should be clause with proper joins, effective to reduce where clause load.
4109 * @return CRM_Contact_DAO_Contact
4112 function searchQuery(
4113 $offset = 0, $rowCount = 0, $sort = NULL,
4114 $count = FALSE, $includeContactIds = FALSE,
4115 $sortByChar = FALSE, $groupContacts = FALSE,
4116 $returnQuery = FALSE,
4117 $additionalWhereClause = NULL, $sortOrder = NULL,
4118 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4121 if ($includeContactIds) {
4122 $this->_includeContactIds
= TRUE;
4123 $this->_whereClause
= $this->whereClause();
4126 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4128 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4129 // and that contact happens to be deleted, set $onlyDeleted to true
4130 foreach ($this->_params
as $values) {
4131 $name = CRM_Utils_Array
::value(0, $values);
4132 $op = CRM_Utils_Array
::value(1, $values);
4133 $value = CRM_Utils_Array
::value(2, $values);
4134 if ($name == 'contact_id' and $op == '=') {
4135 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4136 $onlyDeleted = TRUE;
4141 $this->generatePermissionClause($onlyDeleted, $count);
4143 if (empty($where)) {
4144 $where = "WHERE $this->_permissionWhereClause";
4147 $where = "$where AND $this->_permissionWhereClause";
4150 if ($additionalWhereClause) {
4151 $where = $where . ' AND ' . $additionalWhereClause;
4154 // building the query string
4157 if (isset($this->_groupByComponentClause
)) {
4158 $groupBy = $this->_groupByComponentClause
;
4160 elseif ($this->_useGroupBy
) {
4161 $groupBy = ' GROUP BY contact_a.id';
4164 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4165 $groupBy = 'GROUP BY civicrm_activity.id ';
4168 $order = $orderBy = $limit = '';
4170 $config = CRM_Core_Config
::singleton();
4171 if ($config->includeOrderByClause ||
4172 isset($this->_distinctComponentClause
)
4175 if (is_string($sort)) {
4179 $orderBy = trim($sort->orderBy());
4181 if (!empty($orderBy)) {
4182 // this is special case while searching for
4183 // changelog CRM-1718
4184 if (preg_match('/sort_name/i', $orderBy)) {
4185 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4188 $order = " ORDER BY $orderBy";
4191 $order .= " $sortOrder";
4194 // always add contact_a.id to the ORDER clause
4195 // so the order is deterministic
4196 if (strpos('contact_a.id', $order) === FALSE) {
4197 $order .= ", contact_a.id";
4201 elseif ($sortByChar) {
4202 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4205 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4209 // hack for order clause
4211 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4212 $fieldOrder = explode(' ', $fieldStr);
4213 $field = $fieldOrder[0];
4219 case 'contact_a.sort_name':
4220 case 'contact_a.id':
4225 $this->_whereTables
["civicrm_address"] = 1;
4226 $order = str_replace($field, "civicrm_address.{$field}", $order);
4230 case 'state_province':
4231 $this->_whereTables
["civicrm_{$field}"] = 1;
4232 $order = str_replace($field, "civicrm_{$field}.name", $order);
4236 $this->_whereTables
["civicrm_email"] = 1;
4237 $order = str_replace($field, "civicrm_email.{$field}", $order);
4240 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4241 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4245 if ($rowCount > 0 && $offset >= 0) {
4246 $limit = " LIMIT $offset, $rowCount ";
4250 // note : this modifies _fromClause and _simpleFromClaus
4251 $this->includePseudoFieldsJoin($sort);
4253 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts);
4255 //additional from clause should be w/ proper joins.
4256 if ($additionalFromClause) {
4257 $from .= "\n" . $additionalFromClause;
4260 // if we are doing a transform, do it here
4261 // use the $from, $where and $having to get the contact ID
4262 if ($this->_displayRelationshipType
) {
4263 $this->filterRelatedContacts($from, $where, $having);
4266 if ($skipOrderAndLimit) {
4267 $query = "$select $from $where $having $groupBy";
4270 $query = "$select $from $where $having $groupBy $order $limit";
4278 return CRM_Core_DAO
::singleValueQuery($query);
4281 $dao = CRM_Core_DAO
::executeQuery($query);
4282 if ($groupContacts) {
4284 while ($dao->fetch()) {
4287 return implode(',', $ids);
4294 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4296 * @param string $cacheKey
4297 * @param int $offset
4298 * @param int $rowCount
4299 * @param bool $includeContactIds
4300 * @return CRM_Core_DAO
4302 function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4303 $this->_includeContactIds
= $includeContactIds;
4304 list($select, $from) = $this->query();
4305 $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);
4306 $order = " ORDER BY pnc.id";
4307 $groupBy = " GROUP BY contact_a.id";
4308 $limit = " LIMIT $offset, $rowCount";
4309 $query = "$select $from $groupBy $order $limit";
4310 return CRM_Core_DAO
::executeQuery($query);
4314 * Populate $this->_permissionWhereClause with permission related clause and update other
4315 * query related properties.
4317 * Function calls ACL permission class and hooks to filter the query appropriately
4319 * Note that these 2 params were in the code when extracted from another function
4320 * and a second round extraction would be to make them properties of the class
4322 * @param bool $onlyDeleted Only get deleted contacts
4323 * @param bool $count Return Count only
4327 function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4328 if (!$this->_skipPermission
) {
4329 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4330 CRM_Core_Permission
::VIEW
,
4332 $this->_whereTables
,
4335 $this->_skipDeleteClause
4338 // regenerate fromClause since permission might have added tables
4339 if ($this->_permissionWhereClause
) {
4340 //fix for row count in qill (in contribute/membership find)
4342 $this->_useDistinct
= TRUE;
4344 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4345 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4349 // add delete clause if needed even if we are skipping permission
4351 if (!$this->_skipDeleteClause
) {
4352 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4353 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4357 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4363 function setSkipPermission($val) {
4364 $this->_skipPermission
= $val;
4367 function &summaryContribution($context = NULL) {
4368 list($select, $from, $where, $having) = $this->query(TRUE);
4372 SELECT COUNT( civicrm_contribution.total_amount ) as total_count,
4373 SUM( civicrm_contribution.total_amount ) as total_amount,
4374 AVG( civicrm_contribution.total_amount ) as total_avg,
4375 civicrm_contribution.currency as currency";
4377 // make sure contribution is completed - CRM-4989
4378 $where .= " AND civicrm_contribution.contribution_status_id = 1 ";
4379 if ($context == 'search') {
4380 $where .= " AND contact_a.is_deleted = 0 ";
4384 $summary['total'] = array();
4385 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4387 $query = "$select $from $where GROUP BY currency";
4390 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4392 $summary['total']['count'] = 0;
4393 $summary['total']['amount'] = $summary['total']['avg'] = array();
4394 while ($dao->fetch()) {
4395 $summary['total']['count'] +
= $dao->total_count
;
4396 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4397 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4399 if (!empty($summary['total']['amount'])) {
4400 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4401 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4404 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4409 SELECT COUNT( civicrm_contribution.total_amount ) as cancel_count,
4410 SUM( civicrm_contribution.total_amount ) as cancel_amount,
4411 AVG( civicrm_contribution.total_amount ) as cancel_avg,
4412 civicrm_contribution.currency as currency";
4414 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4415 if ($context == 'search') {
4416 $where .= " AND contact_a.is_deleted = 0 ";
4419 $query = "$select $from $where GROUP BY currency";
4420 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4423 if ($dao->fetch()) {
4424 $summary['cancel']['count'] = $dao->cancel_count
;
4425 $summary['cancel']['amount'] = $dao->cancel_amount
;
4426 $summary['cancel']['avg'] = $dao->cancel_avg
;
4430 $summary['cancel']['count'] = 0;
4431 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4432 while ($dao->fetch()) {
4433 $summary['cancel']['count'] +
= $dao->cancel_count
;
4434 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4435 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4437 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4438 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
4445 * getter for the qill object
4451 return $this->_qill
;
4455 * default set of return default hier return properties
4460 static function &defaultHierReturnProperties() {
4461 if (!isset(self
::$_defaultHierReturnProperties)) {
4462 self
::$_defaultHierReturnProperties = array(
4465 'legal_identifier' => 1,
4466 'external_identifier' => 1,
4467 'contact_type' => 1,
4468 'contact_sub_type' => 1,
4470 'display_name' => 1,
4475 'individual_prefix' => 1,
4476 'individual_suffix' => 1,
4477 'email_greeting' => 1,
4478 'postal_greeting' => 1,
4482 'preferred_communication_method' => 1,
4483 'do_not_phone' => 1,
4484 'do_not_email' => 1,
4487 'do_not_trade' => 1,
4490 '1' => array('location_type' => 1,
4491 'street_address' => 1,
4493 'state_province' => 1,
4495 'postal_code_suffix' => 1,
4498 'phone-Mobile' => 1,
4511 'location_type' => 1,
4512 'street_address' => 1,
4514 'state_province' => 1,
4516 'postal_code_suffix' => 1,
4519 'phone-Mobile' => 1,
4533 return self
::$_defaultHierReturnProperties;
4536 function dateQueryBuilder(
4537 &$values, $tableName, $fieldName,
4538 $dbFieldName, $fieldTitle,
4539 $appendTimeStamp = TRUE
4541 list($name, $op, $value, $grouping, $wildcard) = $values;
4547 if ($name == "{$fieldName}_low" ||
4548 $name == "{$fieldName}_high"
4550 if (isset($this->_rangeCache
[$fieldName])) {
4553 $this->_rangeCache
[$fieldName] = 1;
4555 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4557 if ($name == $fieldName . '_low') {
4559 $firstPhrase = ts('greater than or equal to');
4560 $firstDate = CRM_Utils_Date
::processDate($value);
4562 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4563 if (!empty($secondValues) && $secondValues[2]) {
4565 $secondPhrase = ts('less than or equal to');
4566 $secondValue = $secondValues[2];
4568 if ($appendTimeStamp && strlen($secondValue) == 10) {
4569 $secondValue .= ' 23:59:59';
4571 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4574 elseif ($name == $fieldName . '_high') {
4576 $firstPhrase = ts('less than or equal to');
4578 if ($appendTimeStamp && strlen($value) == 10) {
4579 $value .= ' 23:59:59';
4581 $firstDate = CRM_Utils_Date
::processDate($value);
4583 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4584 if (!empty($secondValues) && $secondValues[2]) {
4586 $secondPhrase = ts('greater than or equal to');
4587 $secondValue = $secondValues[2];
4588 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4592 if (!$appendTimeStamp) {
4593 $firstDate = substr($firstDate, 0, 8);
4595 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
4598 if (!$appendTimeStamp) {
4599 $secondDate = substr($secondDate, 0, 8);
4601 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
4604 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4606 $this->_where
[$grouping][] = "
4607 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
4608 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
4610 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
4613 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
4614 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
4618 if ($name == $fieldName) {
4622 $date = CRM_Utils_Date
::processDate($value);
4624 if (!$appendTimeStamp) {
4625 $date = substr($date, 0, 8);
4628 $format = CRM_Utils_Date
::customFormat($date);
4631 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'";
4634 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op";
4636 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4637 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$format\"";
4641 $tableName == 'civicrm_log' &&
4642 $fieldTitle == ts('Added Date')
4644 //CRM-6903 --hack to check modified date of first record.
4645 //as added date means first modified date of object.
4646 $addedDateQuery = 'select id from civicrm_log group by entity_id order by id';
4647 $this->_where
[$grouping][] = "civicrm_log.id IN ( {$addedDateQuery} )";
4651 function numberRangeBuilder(&$values,
4652 $tableName, $fieldName,
4653 $dbFieldName, $fieldTitle,
4656 list($name, $op, $value, $grouping, $wildcard) = $values;
4658 if ($name == "{$fieldName}_low" ||
4659 $name == "{$fieldName}_high"
4661 if (isset($this->_rangeCache
[$fieldName])) {
4664 $this->_rangeCache
[$fieldName] = 1;
4666 $secondOP = $secondPhrase = $secondValue = NULL;
4668 if ($name == "{$fieldName}_low") {
4670 $firstPhrase = ts('greater than');
4672 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4673 if (!empty($secondValues)) {
4675 $secondPhrase = ts('less than');
4676 $secondValue = $secondValues[2];
4681 $firstPhrase = ts('less than');
4683 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4684 if (!empty($secondValues)) {
4686 $secondPhrase = ts('greater than');
4687 $secondValue = $secondValues[2];
4692 $this->_where
[$grouping][] = "
4693 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
4694 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
4696 $displayValue = $options ?
$options[$value] : $value;
4697 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
4699 $this->_qill
[$grouping][] =
4700 "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
4703 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
4704 $displayValue = $options ?
$options[$value] : $value;
4705 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
4707 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4712 if ($name == $fieldName) {
4716 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
4718 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4719 $displayValue = $options ?
$options[$value] : $value;
4720 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
4727 * Given the field name, operator, value & its data type
4728 * builds the where Clause for the query
4729 * used for handling 'IS NULL'/'IS NOT NULL' operators
4731 * @param string $field fieldname
4732 * @param string $op operator
4733 * @param string $value value
4734 * @param string $dataType data type of the field
4736 * @return where clause for the query
4739 static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
4741 $clause = "$field $op";
4749 $clause = " ( $field IS NULL OR $field = '' ) ";
4752 case 'IS NOT EMPTY':
4753 $clause = " ( $field IS NOT NULL AND $field <> '' ) ";
4758 if (isset($dataType)) {
4759 if (is_array($value)) {
4763 $value = CRM_Utils_Type
::escape($value, "String");
4764 $values = explode(',', CRM_Utils_Array
::value(0, explode(')', CRM_Utils_Array
::value(1, explode('(', $value)))));
4766 // supporting multiple values in IN clause
4768 foreach ($values as $v) {
4770 $val[] = "'" . CRM_Utils_Type
::escape($v, $dataType) . "'";
4772 $value = "(" . implode($val, ",") . ")";
4774 return "$clause $value";
4777 if (empty($dataType)) {
4778 $dataType = 'String';
4781 $value = CRM_Utils_Type
::escape($value, $dataType);
4783 // if we dont have a dataType we should assume
4784 if ($dataType == 'String' ||
$dataType == 'Text') {
4785 $value = "'" . strtolower($value) . "'";
4787 return "$clause $value";
4791 function openedSearchPanes($reset = FALSE) {
4792 if (!$reset ||
empty($this->_whereTables
)) {
4793 return self
::$_openedPanes;
4796 // pane name to table mapper
4797 $panesMapper = array(
4798 ts('Contributions') => 'civicrm_contribution',
4799 ts('Memberships') => 'civicrm_membership',
4800 ts('Events') => 'civicrm_participant',
4801 ts('Relationships') => 'civicrm_relationship',
4802 ts('Activities') => 'civicrm_activity',
4803 ts('Pledges') => 'civicrm_pledge',
4804 ts('Cases') => 'civicrm_case',
4805 ts('Grants') => 'civicrm_grant',
4806 ts('Address Fields') => 'civicrm_address',
4807 ts('Notes') => 'civicrm_note',
4808 ts('Change Log') => 'civicrm_log',
4809 ts('Mailings') => 'civicrm_mailing_event_queue',
4812 foreach (array_keys($this->_whereTables
) as $table) {
4813 if ($panName = array_search($table, $panesMapper)) {
4814 self
::$_openedPanes[$panName] = TRUE;
4818 return self
::$_openedPanes;
4821 function setOperator($operator) {
4822 $validOperators = array('AND', 'OR');
4823 if (!in_array($operator, $validOperators)) {
4826 $this->_operator
= $operator;
4829 function getOperator() {
4830 return $this->_operator
;
4833 function filterRelatedContacts(&$from, &$where, &$having) {
4834 static $_rTypeProcessed = NULL;
4835 static $_rTypeFrom = NULL;
4836 static $_rTypeWhere = NULL;
4838 if (!$_rTypeProcessed) {
4839 $_rTypeProcessed = TRUE;
4841 // create temp table with contact ids
4842 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
4843 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
4844 CRM_Core_DAO
::executeQuery($sql);
4847 REPLACE INTO $tableName ( contact_id )
4853 CRM_Core_DAO
::executeQuery($sql);
4855 $qillMessage = ts('Contacts with a Relationship Type of: ');
4856 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
4858 if (is_numeric($this->_displayRelationshipType
)) {
4859 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
4861 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
4862 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
4865 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
4866 AND displayRelType.is_active = 1
4870 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
4871 if ($dirOne == 'a') {
4872 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
4874 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
4875 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
4879 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
4881 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
4882 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
4886 WHERE displayRelType.relationship_type_id = $relType
4887 AND displayRelType.is_active = 1
4890 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
4893 if (strpos($from, $_rTypeFrom) === FALSE) {
4894 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
4895 // this happens when we have an event_type in the quert (CRM-7969)
4896 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
4897 $from .= $_rTypeFrom;
4898 $where = $_rTypeWhere;
4904 static function caseImportant( $op ) {
4906 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
4909 static function componentPresent( &$returnProperties, $prefix ) {
4910 foreach ($returnProperties as $name => $dontCare ) {
4911 if (substr($name, 0, strlen($prefix)) == $prefix) {
4919 * Builds the necessary structures for all fields that are similar to option value lookups
4921 * @param $name string the name of the field
4922 * @param $op string the sql operator, this function should handle ALL SQL operators
4923 * @param $value any string / integer / array depends on the operator and whos calling the query builder
4924 * @param $grouping int the index where to place the where clause
4925 * @param $selectValue array the key value pairs for this element. This allows us to use this function for things besides option-value pairs
4926 * @param $field array an array that contains various properties of the field identified by $name
4927 * @param $label string The label for this field element
4928 * @param $dataType string The data type for this element
4930 * @return void adds the where clause and qill to the query object
4932 function optionValueQuery(
4940 $dataType = 'String',
4944 $pseudoFields = array('email_greeting', 'postal_greeting', 'addressee', 'gender_id', 'prefix_id', 'suffix_id');
4946 if (is_numeric($value)) {
4947 $qill = $selectValues[(int ) $value];
4949 elseif ($op == 'IN' ||
$op == 'NOT IN') {
4950 $values = self
::parseSearchBuilderString($value);
4951 if (is_array($values)) {
4953 $newValues = array();
4954 foreach ($values as $v) {
4955 $intVals[] = (int) $v;
4956 $newValues[] = $selectValues[(int ) $v];
4959 $value = (in_array($name, $pseudoFields)) ?
$intVals : $newValues;
4960 $qill = implode(', ', $newValues);
4964 // its a string, lets get the int value
4965 $value = array_search($value, $selectValues);
4968 list($tableName, $fieldName) = explode('.', $field['where'], 2);
4969 if ($tableName == 'civicrm_contact') {
4970 $wc = "contact_a.$fieldName";
4974 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
4977 if (in_array($name, $pseudoFields)) {
4978 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id'))) {
4979 $wc = "contact_a.{$name}_id";
4981 $dataType = 'Positive';
4982 $value = (!$value) ?
0 : $value;
4985 $this->_qill
[$grouping][] = $label . " $op '$qill'";
4986 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' ||
$op == 'RLIKE')) ?
'=' : $op;
4987 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
4991 * function to check and explode a user defined numeric string into an array
4992 * this was the protocol used by search builder in the old old days before we had
4993 * super nice js widgets to do the hard work
4995 * @param string the string to check
4996 * @param string the dataType we should check for the values, default integer
4998 * @return FALSE if string does not match the patter
4999 * array of numeric values if string does match the pattern
5002 static function parseSearchBuilderString($string, $dataType = 'Integer') {
5003 $string = trim($string);
5004 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5008 $string = substr($string, 1, -1);
5009 $values = explode(',', $string);
5010 if (empty($values)) {
5014 $returnValues = array();
5015 foreach ($values as $v) {
5016 if ($dataType == 'Integer' && ! is_numeric($v)) {
5019 else if ($dataType == 'String' && ! is_string($v)) {
5022 $returnValues[] = trim($v);
5025 if (empty($returnValues)) {
5029 return $returnValues;
5033 * convert the pseudo constants id's to their names
5034 * @param reference parameter $dao
5036 function convertToPseudoNames(&$dao, $return = FALSE) {
5037 if (empty($this->_pseudoConstantsSelect
)) {
5041 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5042 if (CRM_Utils_Array
::value('sorting', $this->_pseudoConstantsSelect
[$key])) {
5046 if (property_exists($dao, $value['idCol'])) {
5047 $val = $dao->$value['idCol'];
5049 if (CRM_Utils_System
::isNull($val)) {
5052 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5053 $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5055 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5056 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5059 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5060 $dao->$key = $labels[$val];
5063 // return converted values in array format
5065 if (strpos($key, '-') !== FALSE) {
5066 $keyVal = explode('-', $key);
5067 $current = &$values;
5068 $lastElement = array_pop($keyVal);
5069 foreach ($keyVal as $v) {
5070 if (!array_key_exists($v, $current)) {
5071 $current[$v] = array();
5073 $current = &$current[$v];
5075 $current[$lastElement] = $dao->$key;
5078 $values[$key] = $dao->$key;
5087 * include pseudo fields LEFT JOIN
5088 * @param $sort can be a object or string
5091 function includePseudoFieldsJoin($sort) {
5092 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5095 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5098 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5099 if (CRM_Utils_Array
::value('table', $value)) {
5100 $regex = "/({$value['table']}\.|{$name})/";
5101 if (preg_match($regex, $sort)) {
5102 $this->_elemnt
[$value['element']] = 1;
5103 $this->_select
[$value['element']] = $value['select'];
5104 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5105 $present[$value['table']] = $value['join'];
5109 $presentSimpleFrom = $present;
5111 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5112 array_key_exists('civicrm_country', $presentSimpleFrom)) {
5113 unset($presentSimpleFrom['civicrm_country']);
5115 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5116 array_key_exists('civicrm_country', $present)) {
5117 unset($present['civicrm_country']);
5120 $presentClause = $presentSimpleFromClause = NULL;
5121 if (!empty($present)) {
5122 $presentClause = implode(' ', $present);
5124 if (!empty($presentSimpleFrom)) {
5125 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5128 $this->_fromClause
= $this->_fromClause
. $presentClause;
5129 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5131 return array($presentClause, $presentSimpleFromClause);