3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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;
326 public $_rowCountClause;
329 * use groupBy component clause for component searches
333 public $_groupByComponentClause;
336 * Track open panes, useful in advance search
341 public static $_openedPanes = array();
344 * For search builder - which custom fields are location-dependent
347 public $_locationSpecificCustomFields = array();
350 * The tables which have a dependency on location and/or address
355 static $_dependencies = array(
356 'civicrm_state_province' => 1,
357 'civicrm_country' => 1,
358 'civicrm_county' => 1,
359 'civicrm_address' => 1,
360 'civicrm_location_type' => 1,
364 * List of location specific fields
366 static $_locationSpecificFields = array(
371 'supplemental_address_1',
372 'supplemental_address_2',
375 'postal_code_suffix',
388 * Remember if we handle either end of a number or date range
389 * so we can skip the other
391 protected $_rangeCache = array();
393 * Set to true when $this->relationship is run to avoid adding twice
396 protected $_relationshipValuesAdded = FALSE;
399 * Set to the name of the temp table if one has been created
402 static $_relationshipTempTable = NULL;
404 public $_pseudoConstantsSelect = array();
407 * class constructor which also does all the work
409 * @param array $params
410 * @param array $returnProperties
411 * @param array $fields
412 * @param boolean $includeContactIds
413 * @param boolean $strict
414 * @param bool|int $mode - mode the search is operating on
416 * @param bool $skipPermission
417 * @param bool $searchDescendentGroups
418 * @param bool $smartGroupCache
419 * @param null $displayRelationshipType
420 * @param string $operator
422 * @return \CRM_Contact_BAO_Query
425 function __construct(
426 $params = NULL, $returnProperties = NULL, $fields = NULL,
427 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
428 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
429 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
432 $this->_params
= &$params;
433 if ($this->_params
== NULL) {
434 $this->_params
= array();
437 if (empty($returnProperties)) {
438 $this->_returnProperties
= self
::defaultReturnProperties($mode);
441 $this->_returnProperties
= &$returnProperties;
444 $this->_includeContactIds
= $includeContactIds;
445 $this->_strict
= $strict;
446 $this->_mode
= $mode;
447 $this->_skipPermission
= $skipPermission;
448 $this->_smartGroupCache
= $smartGroupCache;
449 $this->_displayRelationshipType
= $displayRelationshipType;
450 $this->setOperator($operator);
453 $this->_fields
= &$fields;
454 $this->_search
= FALSE;
455 $this->_skipPermission
= TRUE;
458 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE);
460 $fields = CRM_Core_Component
::getQueryFields();
461 unset($fields['note']);
462 $this->_fields
= array_merge($this->_fields
, $fields);
464 // add activity fields
465 $fields = CRM_Activity_BAO_Activity
::exportableFields();
466 $this->_fields
= array_merge($this->_fields
, $fields);
468 // add any fields provided by hook implementers
469 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
470 $this->_fields
= array_merge($this->_fields
, $extFields);
473 // basically do all the work once, and then reuse it
478 * function which actually does all the work for the constructor
483 function initialize() {
484 $this->_select
= array();
485 $this->_element
= array();
486 $this->_tables
= array();
487 $this->_whereTables
= array();
488 $this->_where
= array();
489 $this->_qill
= array();
490 $this->_options
= array();
491 $this->_cfIDs
= array();
492 $this->_paramLookup
= array();
493 $this->_having
= array();
495 $this->_customQuery
= NULL;
497 // reset cached static variables - CRM-5803
498 self
::$_activityRole = NULL;
499 self
::$_considerCompActivities = NULL;
500 self
::$_withContactActivitiesOnly = NULL;
502 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
503 $this->_element
['contact_id'] = 1;
504 $this->_tables
['civicrm_contact'] = 1;
506 if (!empty($this->_params
)) {
507 $this->buildParamsLookup();
510 $this->_whereTables
= $this->_tables
;
512 $this->selectClause();
513 $this->_whereClause
= $this->whereClause();
515 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
516 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
518 $this->openedSearchPanes(TRUE);
521 function buildParamsLookup() {
522 // first fix and handle contact deletion nicely
523 // this code is primarily for search builder use case
524 // where different clauses can specify if they want deleted
527 $trashParamExists = FALSE;
528 $paramByGroup = array();
529 foreach ( $this->_params
as $k => $param ) {
530 if (!empty($param[0]) && $param[0] == 'contact_is_deleted' ) {
531 $trashParamExists = TRUE;
533 if (!empty($param[3])) {
534 $paramByGroup[$param[3]][$k] = $param;
538 if ( $trashParamExists ) {
539 $this->_skipDeleteClause
= TRUE;
541 //cycle through group sets and explicitly add trash param if not set
542 foreach ( $paramByGroup as $setID => $set ) {
544 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params
) &&
545 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params
) ) {
546 $this->_params
[] = array(
547 'contact_is_deleted',
557 foreach ($this->_params
as $value) {
558 if (empty($value[0])) {
561 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
563 if (!array_key_exists($cfID, $this->_cfIDs
)) {
564 $this->_cfIDs
[$cfID] = array();
566 $this->_cfIDs
[$cfID][] = $value;
569 if (!array_key_exists($value[0], $this->_paramLookup
)) {
570 $this->_paramLookup
[$value[0]] = array();
572 $this->_paramLookup
[$value[0]][] = $value;
577 * Some composite fields do not appear in the fields array
578 * hack to make them part of the query
583 function addSpecialFields() {
584 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
585 foreach ($special as $name) {
586 if (!empty($this->_returnProperties
[$name])) {
587 $this->_select
[$name] = "contact_a.{$name} as $name";
588 $this->_element
[$name] = 1;
594 * Given a list of conditions in params and a list of desired
595 * return Properties generate the required select and from
596 * clauses. Note that since the where clause introduces new
597 * tables, the initial attempt also retrieves all variables used
603 function selectClause() {
605 $this->addSpecialFields();
607 foreach ($this->_fields
as $name => $field) {
608 // skip component fields
609 // there are done by the alter query below
610 // and need not be done on every field
612 (substr($name, 0, 12) == 'participant_') ||
613 (substr($name, 0, 7) == 'pledge_') ||
614 (substr($name, 0, 5) == 'case_')
619 // redirect to activity select clause
621 (substr($name, 0, 9) == 'activity_') ||
622 ($name == 'parent_id')
624 CRM_Activity_BAO_Query
::select($this);
628 // if this is a hierarchical name, we ignore it
629 $names = explode('-', $name);
630 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
634 // make an exception for special cases, to add the field in select clause
635 $makeException = FALSE;
637 //special handling for groups/tags
638 if (in_array($name, array('groups', 'tags', 'notes'))
639 && isset($this->_returnProperties
[substr($name, 0, -1)])
641 $makeException = TRUE;
644 // since note has 3 different options we need special handling
645 // note / note_subject / note_body
646 if ($name == 'notes') {
647 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
648 if (isset($this->_returnProperties
[$noteField])) {
649 $makeException = TRUE;
655 if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id'))) {
656 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
657 $makeException = TRUE;
661 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
662 if (!empty($this->_paramLookup
[$name]) ||
!empty($this->_returnProperties
[$name]) ||
666 // add to cfIDs array if not present
667 if (!array_key_exists($cfID, $this->_cfIDs
)) {
668 $this->_cfIDs
[$cfID] = array();
671 elseif (isset($field['where'])) {
672 list($tableName, $fieldName) = explode('.', $field['where'], 2);
673 if (isset($tableName)) {
674 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
675 $this->_tables
['civicrm_address'] = 1;
676 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
677 $this->_element
['address_id'] = 1;
680 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
681 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
683 if ($tableName == 'im_provider') {
684 CRM_Core_OptionValue
::select($this);
687 if (in_array($tableName,
688 array('email_greeting', 'postal_greeting', 'addressee'))) {
689 $this->_element
["{$name}_id"] = 1;
690 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
691 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
692 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
693 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
695 if ($tableName == 'email_greeting') {
696 $this->_pseudoConstantsSelect
[$name]['join'] =
697 " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
698 $this->_pseudoConstantsSelect
[$name]['join'] .=
699 " 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 ) ";
701 elseif ($tableName == 'postal_greeting') {
702 $this->_pseudoConstantsSelect
[$name]['join'] =
703 " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
704 $this->_pseudoConstantsSelect
[$name]['join'] .=
705 " 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 ) ";
707 elseif ($tableName == 'addressee') {
708 $this->_pseudoConstantsSelect
[$name]['join'] =
709 " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
710 $this->_pseudoConstantsSelect
[$name]['join'] .=
711 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
713 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
716 $greetField = "{$name}_display";
717 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
718 $this->_element
[$greetField] = 1;
720 $greetField = "{$name}_custom";
721 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
722 $this->_element
[$greetField] = 1;
726 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
727 $this->_tables
[$tableName] = 1;
730 // also get the id of the tableName
731 $tName = substr($tableName, 8);
732 if (in_array($tName, array('country', 'state_province', 'county'))) {
733 if ($tName == 'state_province') {
734 $this->_pseudoConstantsSelect
['state_province_name'] =
735 array('pseudoField' => "{$tName}", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address',
736 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
738 $this->_pseudoConstantsSelect
[$tName] =
739 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id",
740 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
743 $this->_pseudoConstantsSelect
[$name] =
744 array('pseudoField' => "{$tName}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address',
745 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
748 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
749 $this->_element
["{$tName}_id"] = 1;
751 elseif ($tName != 'contact') {
752 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
753 $this->_element
["{$tName}_id"] = 1;
756 //special case for phone
757 if ($name == 'phone') {
758 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
759 $this->_element
['phone_type_id'] = 1;
762 // if IM then select provider_id also
763 // to get "IM Service Provider" in a file to be exported, CRM-3140
765 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
766 $this->_element
['provider_id'] = 1;
769 if ($tName == 'contact') {
770 // special case, when current employer is set for Individual contact
771 if ($fieldName == 'organization_name') {
772 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
774 elseif ($fieldName != 'id') {
775 if ($fieldName == 'prefix_id') {
776 $this->_pseudoConstantsSelect
['individual_prefix'] = array('pseudoField' => 'prefix_id', 'idCol' => "prefix_id", 'bao' => 'CRM_Contact_BAO_Contact');
778 if ($fieldName == 'suffix_id') {
779 $this->_pseudoConstantsSelect
['individual_suffix'] = array('pseudoField' => 'suffix_id', 'idCol' => "suffix_id", 'bao' => 'CRM_Contact_BAO_Contact');
781 if ($fieldName == 'gender_id') {
782 $this->_pseudoConstantsSelect
['gender'] = array('pseudoField' => 'gender_id', 'idCol' => "gender_id", 'bao' => 'CRM_Contact_BAO_Contact');
784 if ($name == 'communication_style_id') {
785 $this->_pseudoConstantsSelect
['communication_style'] = array('pseudoField' => 'communication_style_id', 'idCol' => "communication_style_id", 'bao' => 'CRM_Contact_BAO_Contact');
787 $this->_select
[$name] = "contact_a.{$fieldName} as `$name`";
790 elseif (in_array($tName, array('country', 'county'))) {
791 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
792 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
794 elseif ($tName == 'state_province') {
795 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
796 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
799 $this->_select
[$name] = "{$field['where']} as `$name`";
801 if (!in_array($tName, array('state_province', 'country', 'county'))) {
802 $this->_element
[$name] = 1;
807 elseif ($name === 'tags') {
808 $this->_useGroupBy
= TRUE;
809 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
810 $this->_element
[$name] = 1;
811 $this->_tables
['civicrm_tag'] = 1;
812 $this->_tables
['civicrm_entity_tag'] = 1;
814 elseif ($name === 'groups') {
815 $this->_useGroupBy
= TRUE;
816 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
817 $this->_element
[$name] = 1;
818 $this->_tables
['civicrm_group'] = 1;
820 elseif ($name === 'notes') {
821 // if note field is subject then return subject else body of the note
822 $noteColumn = 'note';
823 if (isset($noteField) && $noteField == 'note_subject') {
824 $noteColumn = 'subject';
827 $this->_useGroupBy
= TRUE;
828 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
829 $this->_element
[$name] = 1;
830 $this->_tables
['civicrm_note'] = 1;
832 elseif ($name === 'current_employer') {
833 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
834 $this->_element
[$name] = 1;
838 if ($cfID && !empty($field['is_search_range'])) {
839 // this is a custom field with range search enabled, so we better check for two/from values
840 if (!empty($this->_paramLookup
[$name . '_from'])) {
841 if (!array_key_exists($cfID, $this->_cfIDs
)) {
842 $this->_cfIDs
[$cfID] = array();
844 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
845 // search in the cdID array for the same grouping
847 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
848 if ($c[3] == $p[3]) {
849 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
854 $p[2] = array('from' => $p[2]);
855 $this->_cfIDs
[$cfID][] = $p;
859 if (!empty($this->_paramLookup
[$name . '_to'])) {
860 if (!array_key_exists($cfID, $this->_cfIDs
)) {
861 $this->_cfIDs
[$cfID] = array();
863 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
864 // search in the cdID array for the same grouping
866 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
867 if ($c[4] == $p[4]) {
868 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
873 $p[2] = array('to' => $p[2]);
874 $this->_cfIDs
[$cfID][] = $p;
881 // add location as hierarchical elements
882 $this->addHierarchicalElements();
884 // add multiple field like website
885 $this->addMultipleElements();
888 CRM_Core_Component
::alterQuery($this, 'select');
890 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
892 if (!empty($this->_cfIDs
)) {
893 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
894 $this->_customQuery
->query();
895 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
896 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
897 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
898 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
899 $this->_options
= $this->_customQuery
->_options
;
904 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
910 function addHierarchicalElements() {
911 if (empty($this->_returnProperties
['location'])) {
914 if (!is_array($this->_returnProperties
['location'])) {
918 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
919 $processed = array();
922 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
923 $addressCustomFieldIds = array();
925 foreach ($this->_returnProperties
['location'] as $name => $elements) {
926 $lCond = self
::getPrimaryCondition($name);
929 $locationTypeId = array_search($name, $locationTypes);
930 if ($locationTypeId === FALSE) {
933 $lCond = "location_type_id = $locationTypeId";
934 $this->_useDistinct
= TRUE;
936 //commented for CRM-3256
937 $this->_useGroupBy
= TRUE;
940 $name = str_replace(' ', '_', $name);
942 $tName = "$name-location_type";
943 $ltName = "`$name-location_type`";
944 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
945 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
946 $this->_element
["{$tName}_id"] = 1;
947 $this->_element
["{$tName}"] = 1;
949 $locationTypeName = $tName;
950 $locationTypeJoin = array();
954 foreach ($elements as $elementFullName => $dontCare) {
956 $elementName = $elementCmpName = $elementFullName;
958 if (substr($elementCmpName, 0, 5) == 'phone') {
959 $elementCmpName = 'phone';
962 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
963 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
964 $addressCustomFieldIds[$cfID][$name] = 1;
967 //add address table only once
968 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
970 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
972 $tName = "$name-address";
973 $aName = "`$name-address`";
974 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
975 $this->_element
["{$tName}_id"] = 1;
976 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
977 $this->_tables
[$tName] = $addressJoin;
978 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
979 $processed[$aName] = 1;
983 $cond = $elementType = '';
984 if (strpos($elementName, '-') !== FALSE) {
985 // this is either phone, email or IM
986 list($elementName, $elementType) = explode('-', $elementName);
989 if (($elementName != 'phone') && ($elementName != 'im')) {
990 $cond = self
::getPrimaryCondition($elementType);
992 // CRM-13011 : If location type is primary, do not restrict search to the phone
993 // type id - we want the primary phone, regardless of what type it is.
994 // Otherwise, restrict to the specified phone type for the given field.
995 if ((!$cond) && ($elementName == 'phone') && $elements['location_type'] != 'Primary') {
996 $cond = "phone_type_id = '$elementType'";
998 elseif ((!$cond) && ($elementName == 'im')) {
999 // IM service provider id, CRM-3140
1000 $cond = "provider_id = '$elementType'";
1002 $elementType = '-' . $elementType;
1005 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
1007 // hack for profile, add location id
1010 // fix for CRM-882( to handle phone types )
1011 !is_numeric($elementType)
1013 if (is_numeric($name)) {
1014 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1017 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1020 elseif (is_numeric($name)) {
1021 //this for phone type to work
1022 if (in_array($elementName, array('phone', 'phone_ext'))) {
1023 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1026 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1030 //this is for phone type to work for profile edit
1031 if (in_array($elementName, array('phone', 'phone_ext'))) {
1032 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1035 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1040 // Check if there is a value, if so also add to where Clause
1042 if ($this->_params
) {
1044 if (isset($locationTypeId)) {
1045 $nm .= "-$locationTypeId";
1047 if (!is_numeric($elementType)) {
1048 $nm .= "$elementType";
1051 foreach ($this->_params
as $id => $values) {
1052 if ((is_array($values) && $values[0] == $nm) ||
1053 (in_array($elementName, array('phone', 'im'))
1054 && (strpos($values[0], $nm) !== FALSE)
1064 if ($field && isset($field['where'])) {
1065 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1066 $pf = substr($tableName, 8);
1067 $tName = $name . '-' . $pf . $elementType;
1068 if (isset($tableName)) {
1069 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1070 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1073 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1076 $this->_element
["{$tName}_id"] = 1;
1077 if (substr($tName, -15) == '-state_province') {
1078 // FIXME: hack to fix CRM-1900
1079 $a = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1083 if (substr_count($a, 'state_province_name') > 0) {
1084 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1085 array('pseudoField' => "{$pf}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1086 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1089 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1090 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id");
1091 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1095 if (substr($elementFullName, 0, 2) == 'im') {
1096 $provider = "{$name}-{$elementFullName}-provider_id";
1097 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1098 $this->_element
[$provider] = 1;
1100 if ($pf == 'country' ||
$pf == 'county') {
1101 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array('pseudoField' => "{$pf}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1102 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1105 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1109 if (in_array($pf, array('state_province', 'country', 'county'))) {
1110 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1113 $this->_element
["{$name}-{$elementFullName}"] = 1;
1116 if (empty($processed["`$tName`"])) {
1117 $processed["`$tName`"] = 1;
1118 $newName = $tableName . '_' . $index;
1119 switch ($tableName) {
1120 case 'civicrm_phone':
1121 case 'civicrm_email':
1123 case 'civicrm_openid':
1125 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id AND `$tName`.$lCond";
1126 // this special case to add phone type
1128 $phoneTypeCondition = " AND `$tName`.$cond ";
1129 //gross hack to pickup corrupted data also, CRM-7603
1130 if (strpos($cond, 'phone_type_id') !== FALSE) {
1131 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1133 $this->_tables
[$tName] .= $phoneTypeCondition;
1136 //build locationType join
1137 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1140 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1144 case 'civicrm_state_province':
1145 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1146 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1147 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1149 $this->_whereTables
["{$name}-address"] = $addressJoin;
1153 case 'civicrm_country':
1154 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1155 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1156 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1158 $this->_whereTables
["{$name}-address"] = $addressJoin;
1162 case 'civicrm_county':
1163 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1164 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1165 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1167 $this->_whereTables
["{$name}-address"] = $addressJoin;
1173 $this->_whereTables
["{$name}-address"] = $addressJoin;
1182 // add location type join
1183 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1184 $this->_tables
[$locationTypeName] = $ltypeJoin;
1186 // table should be present in $this->_whereTables,
1187 // to add its condition in location type join, CRM-3939.
1188 if ($addWhereCount) {
1189 $locClause = array();
1190 foreach ($this->_whereTables
as $tableName => $clause) {
1191 if (!empty($locationTypeJoin[$tableName])) {
1192 $locClause[] = $locationTypeJoin[$tableName];
1196 if (!empty($locClause)) {
1197 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1202 if (!empty($addressCustomFieldIds)) {
1203 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1204 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1205 foreach ($locTypeName as $name => $dnc) {
1206 $this->_locationSpecificCustomFields
[$cfID] = array($name, array_search($name, $locationTypes));
1207 $fieldName = "$name-custom_{$cfID}";
1208 $tName = "$name-address-custom-{$cfID}";
1209 $aName = "`$name-address-custom-{$cfID}`";
1210 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1211 $this->_element
["{$tName}_id"] = 1;
1212 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1213 $this->_element
[$fieldName] = 1;
1214 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1221 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
1227 function addMultipleElements() {
1228 if (empty($this->_returnProperties
['website'])) {
1231 if (!is_array($this->_returnProperties
['website'])) {
1235 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1236 foreach ($elements as $elementFullName => $dontCare) {
1237 $tName = "website-{$key}-{$elementFullName}";
1238 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1239 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1240 $this->_element
["{$tName}_id"] = 1;
1241 $this->_element
["{$tName}"] = 1;
1243 $type = "website-{$key}-website_type_id";
1244 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1245 $this->_element
[$type] = 1;
1246 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1252 * generate the query based on what type of query we need
1254 * @param boolean $count
1255 * @param boolean $sortByChar
1256 * @param boolean $groupContacts
1257 * @param boolean $onlyDeleted
1259 * @return array sql query parts as an array
1262 function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1263 // build permission clause
1264 $this->generatePermissionClause($onlyDeleted, $count);
1267 if (isset($this->_rowCountClause
)) {
1268 $select = "SELECT {$this->_rowCountClause}";
1269 } else if (isset($this->_distinctComponentClause
)) {
1270 // we add distinct to get the right count for components
1271 // for the more complex result set, we use GROUP BY the same id
1273 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1276 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1278 $from = $this->_simpleFromClause
;
1279 if ($this->_useDistinct
) {
1280 $this->_useGroupBy
= TRUE;
1283 elseif ($sortByChar) {
1284 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1285 $from = $this->_simpleFromClause
;
1287 elseif ($groupContacts) {
1288 $select = 'SELECT contact_a.id as id';
1289 if ($this->_useDistinct
) {
1290 $this->_useGroupBy
= TRUE;
1292 $from = $this->_simpleFromClause
;
1295 if (!empty($this->_paramLookup
['group'])) {
1296 // make sure there is only one element
1297 // this is used when we are running under smog and need to know
1298 // how the contact was added (CRM-1203)
1299 if ((count($this->_paramLookup
['group']) == 1) &&
1300 (count($this->_paramLookup
['group'][0][2]) == 1)
1302 $groups = array_keys($this->_paramLookup
['group'][0][2]);
1303 $groupId = $groups[0];
1305 //check if group is saved search
1306 $group = new CRM_Contact_BAO_Group();
1307 $group->id
= $groupId;
1310 if (!isset($group->saved_search_id
)) {
1311 $tbName = "`civicrm_group_contact-{$groupId}`";
1312 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1313 $this->_element
['group_contact_id'] = 1;
1314 $this->_select
['status'] = "$tbName.status as status";
1315 $this->_element
['status'] = 1;
1318 $this->_useGroupBy
= TRUE;
1320 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1321 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1323 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1324 $this->_useDistinct
= FALSE;
1325 $this->_useGroupBy
= TRUE;
1329 $select = "SELECT ";
1330 if (isset($this->_distinctComponentClause
)) {
1331 $select .= "{$this->_distinctComponentClause}, ";
1333 $select .= implode(', ', $this->_select
);
1334 $from = $this->_fromClause
;
1338 if (!empty($this->_whereClause
)) {
1339 $where = "WHERE {$this->_whereClause}";
1342 if (!empty($this->_permissionWhereClause
)) {
1343 if (empty($where)) {
1344 $where = "WHERE $this->_permissionWhereClause";
1347 $where = "$where AND $this->_permissionWhereClause";
1352 if (!empty($this->_having
)) {
1353 foreach ($this->_having
as $havingSets) {
1354 foreach ($havingSets as $havingSet) {
1355 $havingValue[] = $havingSet;
1358 $having = ' HAVING ' . implode(' AND ', $havingValue);
1361 // if we are doing a transform, do it here
1362 // use the $from, $where and $having to get the contact ID
1363 if ($this->_displayRelationshipType
) {
1364 $this->filterRelatedContacts($from, $where, $having);
1367 return array($select, $from, $where, $having);
1376 function &getWhereValues($name, $grouping) {
1378 foreach ($this->_params
as $values) {
1379 if ($values[0] == $name && $values[3] == $grouping) {
1392 static function fixDateValues($relative, &$from, &$to) {
1394 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1399 * @param $formValues
1400 * @param int $wildcard
1401 * @param bool $useEquals
1405 static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE) {
1407 if (empty($formValues)) {
1411 foreach ($formValues as $id => $values) {
1412 if ($id == 'privacy') {
1413 if (is_array($formValues['privacy'])) {
1414 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1415 foreach ($formValues['privacy'] as $key => $value) {
1417 $params[] = array($key, $op, $value, 0, 0);
1422 elseif ($id == 'email_on_hold') {
1423 if ($formValues['email_on_hold']['on_hold']) {
1424 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1427 elseif (preg_match('/_date_relative$/', $id) ||
1428 $id == 'event_relative' ||
1429 $id == 'case_from_relative' ||
1430 $id == 'case_to_relative'
1432 if ($id == 'event_relative') {
1433 $fromRange = 'event_start_date_low';
1434 $toRange = 'event_end_date_high';
1436 else if ($id == 'case_from_relative') {
1437 $fromRange = 'case_from_start_date_low';
1438 $toRange = 'case_from_start_date_high';
1440 else if ($id == 'case_to_relative') {
1441 $fromRange = 'case_to_end_date_low';
1442 $toRange = 'case_to_end_date_high';
1445 $dateComponent = explode('_date_relative', $id);
1446 $fromRange = "{$dateComponent[0]}_date_low";
1447 $toRange = "{$dateComponent[0]}_date_high";
1450 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1451 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1456 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals);
1461 $params[] = $values;
1470 * @param int $wildcard
1471 * @param bool $useEquals
1473 * @return array|null
1475 static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE) {
1476 // skip a few search variables
1477 static $skipWhere = NULL;
1478 static $likeNames = NULL;
1481 if (CRM_Utils_System
::isNull($values)) {
1487 'task', 'radio_ts', 'uf_group_id',
1488 'component_mode', 'qfKey', 'operator',
1489 'display_relationship_type',
1493 if (in_array($id, $skipWhere) ||
1494 substr($id, 0, 4) == '_qf_' ||
1495 substr($id, 0, 7) == 'hidden_'
1501 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1504 // email comes in via advanced search
1505 // so use wildcard always
1506 if ($id == 'email') {
1510 if (!$useEquals && in_array($id, $likeNames)) {
1511 $result = array($id, 'LIKE', $values, 0, 1);
1513 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1514 $result = array($id, 'LIKE', $values, 0, 0);
1516 elseif ($id == 'group') {
1517 if (is_array($values)) {
1518 foreach ($values as $groupIds => $val) {
1520 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1521 if (strlen($matches[1]) > 0) {
1522 $values[$matches[1]] = 1;
1523 unset($values[$groupIds]);
1529 $groupIds = explode(',', $values);
1531 foreach ($groupIds as $groupId) {
1532 $values[$groupId] = 1;
1536 $result = array($id, 'IN', $values, 0, 0);
1538 elseif ($id == 'contact_tags' ||
$id == 'tag') {
1539 if (!is_array($values)) {
1540 $tagIds = explode(',', $values);
1542 foreach ($tagIds as $tagId) {
1543 $values[$tagId] = 1;
1546 $result = array($id, 'IN', $values, 0, 0);
1548 elseif ($id == 'contact_type') {
1549 $result = array($id, 'IN', $values, 0, $wildcard);
1552 $result = array($id, '=', $values, 0, $wildcard);
1561 function whereClauseSingle(&$values) {
1562 // do not process custom fields or prefixed contact ids or component params
1563 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1564 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1565 (substr($values[0], 0, 13) == 'contribution_') ||
1566 (substr($values[0], 0, 6) == 'event_') ||
1567 (substr($values[0], 0, 12) == 'participant_') ||
1568 (substr($values[0], 0, 7) == 'member_') ||
1569 (substr($values[0], 0, 6) == 'grant_') ||
1570 (substr($values[0], 0, 7) == 'pledge_') ||
1571 (substr($values[0], 0, 5) == 'case_') ||
1572 (substr($values[0], 0, 10) == 'financial_') ||
1573 (substr($values[0], 0, 11) == 'membership_')
1578 // skip for hook injected fields / params
1579 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1580 if (array_key_exists($values[0], $extFields)) {
1584 switch ($values[0]) {
1585 case 'deleted_contacts':
1586 $this->deletedContacts($values);
1589 case 'contact_type':
1590 $this->contactType($values);
1593 case 'contact_sub_type':
1594 $this->contactSubType($values);
1598 $this->group($values);
1602 // so we resolve this into a list of groups & proceed as if they had been
1604 list($name, $op, $value, $grouping, $wildcard) = $values;
1605 $values[0] = 'group';
1607 $this->_paramLookup
['group'][0][0] ='group';
1608 $this->_paramLookup
['group'][0][1] = 'IN';
1609 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1610 $this->group($values);
1613 // case tag comes from find contacts
1615 $this->tagSearch($values);
1619 case 'contact_tags':
1620 $this->tag($values);
1625 case 'note_subject':
1626 $this->notes($values);
1630 $this->ufUser($values);
1634 case 'display_name':
1635 $this->sortName($values);
1639 $this->email($values);
1642 case 'phone_numeric':
1643 $this->phone_numeric($values);
1646 case 'phone_phone_type_id':
1647 case 'phone_location_type_id':
1648 $this->phone_option_group($values);
1651 case 'street_address':
1652 $this->street_address($values);
1655 case 'street_number':
1656 $this->street_number($values);
1659 case 'sortByCharacter':
1660 $this->sortByCharacter($values);
1663 case 'location_type':
1664 $this->locationType($values);
1668 $this->county($values);
1671 case 'state_province':
1672 $this->stateProvince($values);
1676 $this->country($values, FALSE);
1680 case 'postal_code_low':
1681 case 'postal_code_high':
1682 $this->postalCode($values);
1685 case 'activity_date':
1686 case 'activity_date_low':
1687 case 'activity_date_high':
1688 case 'activity_role':
1689 case 'activity_status':
1690 case 'followup_parent_id':
1692 case 'activity_subject':
1693 case 'test_activities':
1694 case 'activity_type_id':
1695 case 'activity_type':
1696 case 'activity_survey_id':
1697 case 'activity_tags':
1698 case 'activity_taglist':
1699 case 'activity_test':
1700 case 'activity_campaign_id':
1701 case 'activity_engagement_level':
1703 case 'activity_result':
1704 case 'source_contact':
1705 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1708 case 'birth_date_low':
1709 case 'birth_date_high':
1710 case 'deceased_date_low':
1711 case 'deceased_date_high':
1712 $this->demographics($values);
1715 case 'log_date_low':
1716 case 'log_date_high':
1717 $this->modifiedDates($values);
1721 $this->changeLog($values);
1724 case 'do_not_phone':
1725 case 'do_not_email':
1728 case 'do_not_trade':
1730 $this->privacy($values);
1733 case 'privacy_options':
1734 $this->privacyOptions($values);
1737 case 'privacy_operator':
1738 case 'privacy_toggle':
1739 // these are handled by privacy options
1742 case 'preferred_communication_method':
1743 $this->preferredCommunication($values);
1746 case 'relation_type_id':
1747 case 'relation_start_date_high':
1748 case 'relation_start_date_low':
1749 case 'relation_end_date_high':
1750 case 'relation_end_date_low':
1751 case 'relation_target_name':
1752 case 'relation_status':
1753 case 'relation_date_low':
1754 case 'relation_date_high':
1755 $this->relationship($values);
1756 $this->_relationshipValuesAdded
= TRUE;
1759 case 'task_status_id':
1760 $this->task($values);
1764 // since this case is handled with the above
1767 case 'prox_distance':
1768 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1771 case 'prox_street_address':
1773 case 'prox_postal_code':
1774 case 'prox_state_province_id':
1775 case 'prox_country_id':
1776 // handled by the proximity_distance clause
1780 $this->restWhere($values);
1786 * Given a list of conditions in params generate the required
1792 function whereClause() {
1793 $this->_where
[0] = array();
1794 $this->_qill
[0] = array();
1796 $this->includeContactIds();
1797 if (!empty($this->_params
)) {
1798 foreach (array_keys($this->_params
) as $id) {
1799 if (empty($this->_params
[$id][0])) {
1802 // check for both id and contact_id
1803 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
1805 $this->_params
[$id][1] == 'IS NULL' ||
1806 $this->_params
[$id][1] == 'IS NOT NULL'
1808 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]}";
1810 elseif (is_array($this->_params
[$id][2])) {
1811 $idList = implode("','", $this->_params
[$id][2]);
1812 //why on earth do they put ' in the middle & not on the outside? We have to assume it's
1813 //to support 'something' so lets add them conditionally to support the api (which is a tested flow
1814 // so if you are looking to alter this check api test results
1815 if(strpos(trim($idList), "'") > 0) {
1816 $idList = "'" . $idList . "'";
1819 $this->_where
[0][] = "contact_a.id IN ({$idList})";
1822 $this->_where
[0][] = self
::buildClause("contact_a.id", "{$this->_params[$id][1]}", "{$this->_params[$id][2]}");
1826 $this->whereClauseSingle($this->_params
[$id]);
1830 CRM_Core_Component
::alterQuery($this, 'where');
1832 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
1835 if ($this->_customQuery
) {
1836 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1837 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1838 if (!empty($this->_customQuery
->_where
)) {
1839 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
1842 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
1846 $andClauses = array();
1849 if (!empty($this->_where
)) {
1850 foreach ($this->_where
as $grouping => $values) {
1851 if ($grouping > 0 && !empty($values)) {
1852 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1857 if (!empty($this->_where
[0])) {
1858 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
1860 if (!empty($clauses)) {
1861 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1864 if ($validClauses > 1) {
1865 $this->_useDistinct
= TRUE;
1869 return implode(' AND ', $andClauses);
1877 function restWhere(&$values) {
1878 $name = CRM_Utils_Array
::value(0, $values);
1879 $op = CRM_Utils_Array
::value(1, $values);
1880 $value = CRM_Utils_Array
::value(2, $values);
1881 $grouping = CRM_Utils_Array
::value(3, $values);
1882 $wildcard = CRM_Utils_Array
::value(4, $values);
1884 if (isset($grouping) && empty($this->_where
[$grouping])) {
1885 $this->_where
[$grouping] = array();
1888 $multipleFields = array('url');
1890 //check if the location type exits for fields
1892 $locType = explode('-', $name);
1894 if (!in_array($locType[0], $multipleFields)) {
1895 //add phone type if exists
1896 if (isset($locType[2]) && $locType[2]) {
1897 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
1901 $field = CRM_Utils_Array
::value($name, $this->_fields
);
1904 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
1913 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
1914 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1916 if (substr($name, 0, 14) === 'state_province') {
1917 if (isset($locType[1]) && is_numeric($locType[1])) {
1919 $aName = "{$locationType[$locType[1]]}-address";
1920 $where = "`$aName`.state_province_id";
1923 $where = "civicrm_address.state_province_id";
1926 $states = CRM_Core_PseudoConstant
::stateProvince();
1927 if (is_numeric($value)) {
1928 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1929 $value = $states[(int ) $value];
1932 $intVal = CRM_Utils_Array
::key($value, $states);
1933 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1936 $this->_qill
[$grouping][] = ts('State') . " $op '$value'";
1939 $this->_qill
[$grouping][] = ts('State') . " ($lType) $op '$value'";
1942 elseif (!empty($field['pseudoconstant'])) {
1943 $this->optionValueQuery(
1944 $name, $op, $value, $grouping,
1945 CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', $field['name']),
1951 if ($name == 'gender_id') {
1952 self
::$_openedPanes[ts('Demographics')] = TRUE;
1955 elseif (substr($name, 0, 7) === 'country') {
1956 if (isset($locType[1]) && is_numeric($locType[1])) {
1958 $aName = "{$locationType[$locType[1]]}-address";
1959 $where = "`$aName`.country_id";
1962 $where = "civicrm_address.country_id";
1965 $countries = CRM_Core_PseudoConstant
::country();
1966 if (is_numeric($value)) {
1967 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1968 $value = $countries[(int ) $value];
1971 $intVal = CRM_Utils_Array
::key($value, $countries);
1972 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1976 $this->_qill
[$grouping][] = ts('Country') . " $op '$value'";
1979 $this->_qill
[$grouping][] = ts('Country') . " ($lType) $op '$value'";
1982 elseif (substr($name, 0, 6) === 'county') {
1983 if (isset($locType[1]) && is_numeric($locType[1])) {
1985 $aName = "{$locationType[$locType[1]]}-address";
1986 $where = "`$aName`.county_id";
1989 $where = "civicrm_address.county_id";
1992 $counties = CRM_Core_PseudoConstant
::county();
1993 if (is_numeric($value)) {
1994 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1995 $value = $counties[(int ) $value];
1998 $intVal = CRM_Utils_Array
::key($value, $counties);
1999 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
2003 $this->_qill
[$grouping][] = ts('County') . " $op '$value'";
2006 $this->_qill
[$grouping][] = ts('County') . " ($lType) $op '$value'";
2009 elseif ($name === 'world_region') {
2010 $field['where'] = 'civicrm_worldregion.id';
2011 $this->optionValueQuery(
2012 $name, $op, $value, $grouping,
2013 CRM_Core_PseudoConstant
::worldRegion(),
2018 elseif ($name === 'birth_date') {
2019 $date = CRM_Utils_Date
::processDate($value);
2020 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
2023 $date = CRM_Utils_Date
::customFormat($date);
2024 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
2027 $this->_qill
[$grouping][] = "$field[title] $op";
2029 self
::$_openedPanes[ts('Demographics')] = TRUE;
2031 elseif ($name === 'deceased_date') {
2032 $date = CRM_Utils_Date
::processDate($value);
2033 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
2035 $date = CRM_Utils_Date
::customFormat($date);
2036 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
2039 $this->_qill
[$grouping][] = "$field[title] $op";
2041 self
::$_openedPanes[ts('Demographics')] = TRUE;
2043 elseif ($name === 'is_deceased') {
2044 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
2045 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2046 self
::$_openedPanes[ts('Demographics')] = TRUE;
2048 elseif ($name === 'contact_id') {
2049 if (is_int($value)) {
2050 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2051 $this->_qill
[$grouping][] = "$field[title] $op $value";
2054 elseif ($name === 'name') {
2055 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2057 $value = "%$value%";
2060 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2061 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2062 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2064 elseif ($name === 'current_employer') {
2065 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2067 $value = "%$value%";
2070 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
2071 $ceWhereClause = self
::buildClause($wc, $op,
2074 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2075 $this->_where
[$grouping][] = $ceWhereClause;
2076 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2078 elseif ($name === 'email_greeting') {
2079 $filterCondition = array('greeting_type' => 'email_greeting');
2080 $this->optionValueQuery(
2081 $name, $op, $value, $grouping,
2082 CRM_Core_PseudoConstant
::greeting($filterCondition),
2084 ts('Email Greeting')
2087 elseif ($name === 'postal_greeting') {
2088 $filterCondition = array('greeting_type' => 'postal_greeting');
2089 $this->optionValueQuery(
2090 $name, $op, $value, $grouping,
2091 CRM_Core_PseudoConstant
::greeting($filterCondition),
2093 ts('Postal Greeting')
2096 elseif ($name === 'addressee') {
2097 $filterCondition = array('greeting_type' => 'addressee');
2098 $this->optionValueQuery(
2099 $name, $op, $value, $grouping,
2100 CRM_Core_PseudoConstant
::greeting($filterCondition),
2105 elseif (substr($name, 0, 4) === 'url-') {
2106 $tName = 'civicrm_website';
2107 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2108 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2110 $value = "%$value%";
2114 $wc = 'civicrm_website.url';
2115 $this->_where
[$grouping][] = $d = self
::buildClause($wc, $op, $value);
2116 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2118 elseif ($name === 'contact_is_deleted') {
2119 $this->_where
[$grouping][] = self
::buildClause("contact_a.is_deleted", $op, $value);
2120 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2123 if (is_array($value)) {
2124 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2125 // for api style operators for functions that hit this point without worrying about regression
2126 // (the previous comments indicated the condition for hitting this point were unknown
2127 // per CRM-14743 we are adding modified_date & created_date operator support
2128 $operations = array_keys($value);
2129 foreach ($operations as $operator) {
2130 if(!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2131 // we don't know when this might happen
2132 CRM_Core_Error
::fatal();
2135 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($name, $value, NULL);
2136 //since this is not currently being called by the form layer we can skip worrying about the 'qill' for now
2140 if (!empty($field['where'])) {
2142 $value = $strtolower($value);
2145 $value = "%$value%";
2149 if (isset($locType[1]) &&
2150 is_numeric($locType[1])
2154 //get the location name
2155 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2157 $where = "`$tName`.$fldName";
2159 $this->_where
[$grouping][] = self
::buildClause("LOWER($where)", $op, $value);
2160 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2161 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2162 $this->_qill
[$grouping][] = "$field[title] $op '$value'";
2165 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2166 if ($tableName == 'civicrm_contact') {
2167 $fieldName = "LOWER(contact_a.{$fieldName})";
2170 if ($op != 'IN' && !is_numeric($value)) {
2171 $fieldName = "LOWER({$field['where']})";
2174 $fieldName = "{$field['where']}";
2179 if (!empty($field['type'])) {
2180 $type = CRM_Utils_Type
::typeToString($field['type']);
2183 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2184 $this->_qill
[$grouping][] = "$field[title] $op $value";
2189 if ($setTables && isset($field['where'])) {
2190 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2191 if (isset($tableName)) {
2192 $this->_tables
[$tableName] = 1;
2193 $this->_whereTables
[$tableName] = 1;
2206 static function getLocationTableName(&$where, &$locType) {
2207 if (isset($locType[1]) && is_numeric($locType[1])) {
2208 list($tbName, $fldName) = explode(".", $where);
2210 //get the location name
2211 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2212 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2213 if (in_array($locType[0], $specialFields)) {
2214 //hack to fix / special handing for phone_ext
2215 if ($locType[0] == 'phone_ext') {
2216 $locType[0] = 'phone';
2218 if (isset($locType[2]) && $locType[2]) {
2219 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2222 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2225 elseif (in_array($locType[0],
2227 'address_name', 'street_address', 'supplemental_address_1', 'supplemental_address_2',
2228 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
2231 //fix for search by profile with address fields.
2232 $tName = "{$locationType[$locType[1]]}-address";
2234 elseif ($locType[0] == 'on_hold') {
2235 $tName = "{$locationType[$locType[1]]}-email";
2238 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2240 $tName = str_replace(' ', '_', $tName);
2241 return array($tName, $fldName);
2243 CRM_Core_Error
::fatal();
2247 * Given a result dao, extract the values and return that array
2249 * @param Object $dao
2251 * @return array values for this query
2253 function store($dao) {
2256 foreach ($this->_element
as $key => $dontCare) {
2257 if (property_exists($dao, $key)) {
2258 if (strpos($key, '-') !== FALSE) {
2259 $values = explode('-', $key);
2260 $lastElement = array_pop($values);
2262 $cnt = count($values);
2264 foreach ($values as $v) {
2265 if (!array_key_exists($v, $current)) {
2266 $current[$v] = array();
2268 //bad hack for im_provider
2269 if ($lastElement == 'provider_id') {
2270 if ($count < $cnt) {
2271 $current = &$current[$v];
2274 $lastElement = "{$v}_{$lastElement}";
2278 $current = &$current[$v];
2283 $current[$lastElement] = $dao->$key;
2286 $value[$key] = $dao->$key;
2294 * getter for tables array
2300 return $this->_tables
;
2304 * Where tables is sometimes used to create the from clause, but, not reliably, set this AND set tables
2305 * It's unclear the intent - there is a 'simpleFrom' clause which takes whereTables into account & a fromClause which doesn't
2306 * logic may have eroded
2309 function whereTables() {
2310 return $this->_whereTables
;
2314 * generate the where clause (used in match contacts and permissions)
2316 * @param array $params
2317 * @param array $fields
2318 * @param array $tables
2319 * @param $whereTables
2320 * @param boolean $strict
2326 static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2327 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2331 $tables = array_merge($query->tables(), $tables);
2332 $whereTables = array_merge($query->whereTables(), $whereTables);
2334 return $query->_whereClause
;
2338 * create the from clause
2340 * @param array $tables tables that need to be included in this from clause
2341 * if null, return mimimal from clause (i.e. civicrm_contact)
2342 * @param array $inner tables that should be inner-joined
2343 * @param array $right tables that should be right-joined
2345 * @param bool $primaryLocation
2348 * @return string the from clause
2352 static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2354 $from = ' FROM civicrm_contact contact_a';
2355 if (empty($tables)) {
2359 if (!empty($tables['civicrm_worldregion'])) {
2360 $tables = array_merge(array('civicrm_country' => 1), $tables);
2363 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2364 CRM_Utils_Array
::value('civicrm_county', $tables)
2365 ) && empty($tables['civicrm_address'])) {
2366 $tables = array_merge(array('civicrm_address' => 1),
2371 // add group_contact table if group table is present
2372 if (!empty($tables['civicrm_group']) && empty($tables['civicrm_group_contact'])) {
2373 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
2376 // add group_contact and group table is subscription history is present
2377 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2378 $tables = array_merge(array(
2379 'civicrm_group' => 1,
2380 'civicrm_group_contact' => 1,
2386 // to handle table dependencies of components
2387 CRM_Core_Component
::tableNames($tables);
2388 // to handle table dependencies of hook injected tables
2389 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2391 //format the table list according to the weight
2392 $info = CRM_Core_TableHierarchy
::info();
2394 foreach ($tables as $key => $value) {
2396 if (strpos($key, '-') !== FALSE) {
2397 $keyArray = explode('-', $key);
2398 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2400 elseif (strpos($key, '_') !== FALSE) {
2401 $keyArray = explode('_', $key);
2402 if (is_numeric(array_pop($keyArray))) {
2403 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2406 $k = CRM_Utils_Array
::value($key, $info, 99);
2410 $k = CRM_Utils_Array
::value($key, $info, 99);
2412 $tempTable[$k . ".$key"] = $key;
2415 $newTables = array();
2416 foreach ($tempTable as $key) {
2417 $newTables[$key] = $tables[$key];
2420 $tables = $newTables;
2422 foreach ($tables as $name => $value) {
2427 if (!empty($inner[$name])) {
2430 elseif (!empty($right[$name])) {
2438 // if there is already a join statement in value, use value itself
2439 if (strpos($value, 'JOIN')) {
2440 $from .= " $value ";
2443 $from .= " $side JOIN $name ON ( $value ) ";
2448 case 'civicrm_address':
2449 if ($primaryLocation) {
2450 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2453 //CRM-14263 further handling of address joins further down...
2454 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2458 case 'civicrm_phone':
2459 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2462 case 'civicrm_email':
2463 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2467 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2471 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2472 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2473 $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)";
2476 case 'civicrm_openid':
2477 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2480 case 'civicrm_worldregion':
2481 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2482 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2485 case 'civicrm_location_type':
2486 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2489 case 'civicrm_group':
2490 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2493 case 'civicrm_group_contact':
2494 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2497 case 'civicrm_activity':
2498 case 'civicrm_activity_tag':
2499 case 'activity_type':
2500 case 'activity_status':
2502 case 'civicrm_activity_contact':
2503 case 'source_contact':
2504 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2507 case 'civicrm_entity_tag':
2508 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2509 civicrm_entity_tag.entity_id = contact_a.id ) ";
2512 case 'civicrm_note':
2513 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2514 contact_a.id = civicrm_note.entity_id ) ";
2517 case 'civicrm_subscription_history':
2518 $from .= " $side JOIN civicrm_subscription_history
2519 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2520 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2523 case 'civicrm_relationship':
2524 if (self
::$_relType == 'reciprocal') {
2525 if(self
::$_relationshipTempTable) {
2526 // we have a temptable to join on
2527 $tbl = self
::$_relationshipTempTable;
2528 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2531 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2532 $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)";
2535 elseif (self
::$_relType == 'b') {
2536 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2537 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2540 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2541 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2546 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2547 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2551 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2554 case 'civicrm_grant':
2555 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2558 case 'civicrm_website':
2559 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2563 $locationTypeName = '';
2564 if (strpos($name, '-address') != 0) {
2565 $locationTypeName = 'address';
2567 elseif (strpos($name, '-phone') != 0) {
2568 $locationTypeName = 'phone';
2570 elseif (strpos($name, '-email') != 0) {
2571 $locationTypeName = 'email';
2573 if($locationTypeName) {
2574 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2575 $parts = explode('-', $name);
2576 $locationID = array_search($parts[0], CRM_Core_BAO_Address
::buildOptions('location_type_id', 'get', array('name' => $parts[0])));
2577 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2580 $from .= CRM_Core_Component
::from($name, $mode, $side);
2582 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2591 * WHERE / QILL clause for deleted_contacts
2597 function deletedContacts($values) {
2598 list($_, $_, $value, $grouping, $_) = $values;
2600 // *prepend* to the relevant grouping as this is quite an important factor
2601 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2606 * where / qill clause for contact_type
2613 function contactType(&$values) {
2614 list($name, $op, $value, $grouping, $wildcard) = $values;
2616 $subTypes = array();
2619 // account for search builder mapping multiple values
2620 if (!is_array($value)) {
2621 $values = self
::parseSearchBuilderString($value, 'String');
2622 if (is_array($values)) {
2623 $value = array_flip($values);
2627 if (is_array($value)) {
2628 foreach ($value as $k => $v) {
2633 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2634 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2637 if (!empty($subType)) {
2638 $subTypes[$subType] = 1;
2640 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2645 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2646 $contactType = $contactTypeANDSubType[0];
2647 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2648 if (!empty($subType)) {
2649 $subTypes[$subType] = 1;
2651 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2655 if (!empty($clause)) {
2657 if ($op == 'IN' ||
$op == 'NOT IN') {
2658 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2661 $type = array_pop($clause);
2662 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2665 $this->_qill
[$grouping][] = ts('Contact Type') . ' - ' . implode(' ' . ts('or') . ' ', $quill);
2667 if (!empty($subTypes)) {
2668 $this->includeContactSubTypes($subTypes, $grouping);
2674 * where / qill clause for contact_sub_type
2681 function contactSubType(&$values) {
2682 list($name, $op, $value, $grouping, $wildcard) = $values;
2683 $this->includeContactSubTypes($value, $grouping);
2690 function includeContactSubTypes($value, $grouping) {
2693 $alias = "contact_a.contact_sub_type";
2695 if (is_array($value)) {
2696 foreach ($value as $k => $v) {
2698 $clause[$k] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($k, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2703 $clause[$value] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2706 if (!empty($clause)) {
2707 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2708 $this->_qill
[$grouping][] = ts('Contact Subtype') . ' - ' . implode(' ' . ts('or') . ' ', array_keys($clause));
2713 * where / qill clause for groups
2720 function group(&$values) {
2721 list($name, $op, $value, $grouping, $wildcard) = $values;
2723 if (count($value) > 1) {
2724 $this->_useDistinct
= TRUE;
2727 $groupNames = CRM_Core_PseudoConstant
::group();
2728 $groupIds = implode(',', array_keys($value));
2731 foreach ($value as $id => $dontCare) {
2732 if (array_key_exists($id, $groupNames) && $dontCare) {
2733 $names[] = $groupNames[$id];
2739 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2741 is_array($gcsValues[2])
2743 foreach ($gcsValues[2] as $k => $v) {
2745 if ($k == 'Added') {
2748 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2753 $statii[] = '"Added"';
2758 if (count($value) == 1 &&
2759 count($statii) == 1 &&
2760 $statii[0] == '"Added"'
2762 // check if smart group, if so we can get rid of that one additional
2764 $groupIDs = array_keys($value);
2766 if (!empty($groupIDs[0]) &&
2767 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
2777 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2778 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON ( contact_a.id = {$gcTable}.contact_id AND {$gcTable}.group_id $op ( $groupIds ) )";
2781 $qill = ts('Contacts %1', array(1 => $op));
2782 $qill .= ' ' . implode(' ' . ts('or') . ' ', $names);
2784 $groupClause = NULL;
2787 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2788 if (!empty($statii)) {
2789 $groupClause .= " AND {$gcTable}.status IN (" . implode(', ', $statii) . ")";
2790 $qill .= " " . ts('AND') . " " . ts('Group Status') . ' - ' . implode(' ' . ts('or') . ' ', $statii);
2795 $ssClause = $this->savedSearch($values);
2798 $groupClause = "( ( $groupClause ) OR ( $ssClause ) )";
2801 $groupClause = $ssClause;
2806 $this->_where
[$grouping][] = $groupClause;
2807 $this->_qill
[$grouping][] = $qill;
2810 * Function translates selection of group type into a list of groups
2817 function getGroupsFromTypeCriteria($value){
2818 $groupIds = array();
2819 foreach ($value as $groupTypeValue) {
2820 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2821 $groupIds = ($groupIds +
$groupList);
2827 * where / qill clause for smart groups
2831 * @return string|NULL
2834 function savedSearch(&$values) {
2835 list($name, $op, $value, $grouping, $wildcard) = $values;
2836 return $this->addGroupContactCache(array_keys($value));
2840 * @param array $groups
2841 * @param string $tableAlias
2842 * @param string $joinTable
2844 * @return null|string
2846 function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
2847 $config = CRM_Core_Config
::singleton();
2849 // Find all the groups that are part of a saved search.
2850 $groupIDs = implode(',', $groups);
2851 if (empty($groupIDs)) {
2856 SELECT id, cache_date, saved_search_id, children
2858 WHERE id IN ( $groupIDs )
2859 AND ( saved_search_id != 0
2860 OR saved_search_id IS NOT NULL
2861 OR children IS NOT NULL )
2864 $group = CRM_Core_DAO
::executeQuery($sql);
2865 $groupsFiltered = array();
2867 while ($group->fetch()) {
2868 $groupsFiltered[] = $group->id
;
2870 $this->_useDistinct
= TRUE;
2872 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
2873 CRM_Contact_BAO_GroupContactCache
::load($group);
2877 if (count($groupsFiltered)) {
2878 $groupIDsFiltered = implode(',', $groupsFiltered);
2880 if ($tableAlias == NULL) {
2881 $tableAlias = "civicrm_group_contact_cache_{$groupIDsFiltered}";
2884 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache `{$tableAlias}` ON {$joinTable}.id = `{$tableAlias}`.contact_id ";
2886 return "`{$tableAlias}`.group_id IN (" . $groupIDsFiltered . ")";
2893 * where / qill clause for cms users
2900 function ufUser(&$values) {
2901 list($name, $op, $value, $grouping, $wildcard) = $values;
2904 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2906 $this->_qill
[$grouping][] = ts('CMS User');
2908 elseif ($value == 0) {
2909 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2911 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2912 $this->_qill
[$grouping][] = ts('Not a CMS User');
2917 * all tag search specific
2924 function tagSearch(&$values) {
2925 list($name, $op, $value, $grouping, $wildcard) = $values;
2928 $value = "%{$value}%";
2931 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2932 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2934 $etTable = "`civicrm_entity_tag-" . $value . "`";
2935 $tTable = "`civicrm_tag-" . $value . "`";
2937 if ($useAllTagTypes[2]) {
2938 $this->_tables
[$etTable] =
2939 $this->_whereTables
[$etTable] =
2940 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
2941 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
2943 // search tag in cases
2944 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2945 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
2946 $this->_tables
[$etCaseTable] =
2947 $this->_whereTables
[$etCaseTable] =
2948 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2949 LEFT JOIN civicrm_case
2950 ON (civicrm_case_contact.case_id = civicrm_case.id
2951 AND civicrm_case.is_deleted = 0 )
2952 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
2953 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
2954 // search tag in activities
2955 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2956 $tActTable = "`civicrm_act_tag-" . $value . "`";
2957 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2958 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2960 $this->_tables
[$etActTable] =
2961 $this->_whereTables
[$etActTable] =
2962 " LEFT JOIN civicrm_activity_contact
2963 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
2964 LEFT JOIN civicrm_activity
2965 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
2966 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2967 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
2968 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
2970 $this->_where
[$grouping][] = "({$tTable}.name $op '". $value . "' OR {$tCaseTable}.name $op '". $value . "' OR {$tActTable}.name $op '". $value . "')";
2971 $this->_qill
[$grouping][] = ts('Tag %1 %2 ', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
2973 $etTable = "`civicrm_entity_tag-" . $value . "`";
2974 $tTable = "`civicrm_tag-" . $value . "`";
2975 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
2976 {$etTable}.entity_table = 'civicrm_contact' )
2977 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
2979 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
2980 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
2985 * where / qill clause for tag
2992 function tag(&$values) {
2993 list($name, $op, $value, $grouping, $wildcard) = $values;
2995 $tagNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
2996 if (is_array($value)) {
2997 if (count($value) > 1) {
2998 $this->_useDistinct
= TRUE;
3000 foreach ($value as $id => $dontCare) {
3001 $names[] = CRM_Utils_Array
::value($id, $tagNames);
3003 $names = implode(' ' . ts('or') . ' ', $names);
3004 $value = implode(',', array_keys($value));
3007 $names = CRM_Utils_Array
::value($value, $tagNames);
3011 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3012 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3014 $etTable = "`civicrm_entity_tag-" . $value . "`";
3016 if ($useAllTagTypes[2]) {
3017 $this->_tables
[$etTable] =
3018 $this->_whereTables
[$etTable] =
3019 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3021 // search tag in cases
3022 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3023 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3024 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3026 $this->_tables
[$etCaseTable] =
3027 $this->_whereTables
[$etCaseTable] =
3028 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3029 LEFT JOIN civicrm_case
3030 ON (civicrm_case_contact.case_id = civicrm_case.id
3031 AND civicrm_case.is_deleted = 0 )
3032 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3033 // search tag in activities
3034 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3035 $this->_tables
[$etActTable] =
3036 $this->_whereTables
[$etActTable] =
3037 " LEFT JOIN civicrm_activity_contact
3038 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3039 LEFT JOIN civicrm_activity
3040 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3041 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3042 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3045 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3046 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3049 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (". $value . ") OR {$etCaseTable}.tag_id $op (". $value . ") OR {$etActTable}.tag_id $op (". $value . "))";
3051 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
3053 $this->_tables
[$etTable] =
3054 $this->_whereTables
[$etTable] =
3055 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3058 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3059 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3060 $op = str_replace('EMPTY', 'NULL', $op);
3061 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3064 $this->_where
[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
3066 $this->_qill
[$grouping][] = ts('Tagged %1', array( 1 => $op)) . ' ' . $names;
3072 * where/qill clause for notes
3079 function notes(&$values) {
3080 list($name, $op, $value, $grouping, $wildcard) = $values;
3082 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3083 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3084 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3086 $this->_useDistinct
= TRUE;
3088 $this->_tables
['civicrm_note'] =
3089 $this->_whereTables
['civicrm_note'] =
3090 " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3092 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3094 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3095 if ($wildcard ||
$op == 'LIKE') {
3096 if (strpos($value, '%') === FALSE) {
3097 $value = "%$value%";
3101 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3107 if ( $noteOption %
2 == 0 ) {
3108 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3109 $label = ts('Note: Body Only');
3111 if ( $noteOption %
3 == 0 ) {
3112 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3113 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3115 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3116 $this->_qill
[$grouping][] = $label . " $op - '$n'";
3126 function nameNullOrEmptyOp($name, $op, $grouping) {
3130 $this->_where
[$grouping][] = "contact_a.$name $op";
3131 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3135 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3136 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3139 case 'IS NOT EMPTY':
3140 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3141 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3150 * where / qill clause for sort_name
3157 function sortName(&$values) {
3158 list($name, $op, $value, $grouping, $wildcard) = $values;
3160 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3161 if ( $this->nameNullOrEmptyOp( $name, $op, $grouping ) ) {
3166 $name = trim($value);
3172 $config = CRM_Core_Config
::singleton();
3176 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3179 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3180 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3182 if (substr($name, 0, 1) == '"' &&
3183 substr($name, -1, 1) == '"'
3185 //If name is encased in double quotes, the value should be taken to be the string in entirety and the
3186 $value = substr($name, 1, -1);
3187 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
3188 $wc = ($newName == 'sort_name') ?
'LOWER(contact_a.sort_name)' : 'LOWER(contact_a.display_name)';
3189 $sub[] = " ( $wc = '$value' ) ";
3190 if ($config->includeEmailInName
) {
3191 $sub[] = " ( civicrm_email.email = '$value' ) ";
3194 elseif (strpos($name, ',') !== FALSE) {
3195 // if we have a comma in the string, search for the entire string
3196 $value = $strtolower(CRM_Core_DAO
::escapeString($name));
3198 if ($config->includeWildCardInName
) {
3199 $value = "'%$value%'";
3202 $value = "'$value%'";
3207 $value = "'$value'";
3209 if ($newName == 'sort_name') {
3210 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3213 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3215 $sub[] = " ( $wc $op $value )";
3216 if ($config->includeNickNameInName
) {
3217 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3218 $sub[] = " ( $wc $op $value )";
3220 if ($config->includeEmailInName
) {
3221 $sub[] = " ( civicrm_email.email $op $value ) ";
3225 // the string should be treated as a series of keywords to be matched with match ANY OR
3226 // match ALL depending on Civi config settings (see CiviAdmin)
3228 // The Civi configuration setting can be overridden if the string *starts* with the case
3229 // insenstive strings 'AND:' or 'OR:'TO THINK ABOUT: what happens when someone searches
3230 // for the following "AND: 'a string in quotes'"? - probably nothing - it would make the
3231 // AND OR variable reduntant because there is only one search string?
3233 // Check to see if the $subGlue is overridden in the search text
3234 if (strtolower(substr($name, 0, 4)) == 'and:') {
3235 $name = substr($name, 4);
3238 if (strtolower(substr($name, 0, 3)) == 'or:') {
3239 $name = substr($name, 3);
3243 $firstChar = substr($name, 0, 1);
3244 $lastChar = substr($name, -1, 1);
3245 $quotes = array("'", '"');
3246 if ((strlen($name) > 2) && in_array($firstChar, $quotes) &&
3247 in_array($lastChar, $quotes)
3249 $name = substr($name, 1);
3250 $name = substr($name, 0, -1);
3251 $pieces = array($name);
3254 $pieces = explode(' ', $name);
3256 foreach ($pieces as $piece) {
3257 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($piece)));
3258 if (strlen($value)) {
3259 // Added If as a sanitization - without it, when you do an OR search, any string with
3260 // double spaces (i.e. " ") or that has a space after the keyword (e.g. "OR: ") will
3261 // return all contacts because it will include a condition similar to "OR contact
3262 // name LIKE '%'". It might be better to replace this with array_filter.
3263 $fieldsub = array();
3265 if ($config->includeWildCardInName
) {
3266 $value = "'%$value%'";
3269 $value = "'$value%'";
3274 $value = "'$value'";
3276 if ($newName == 'sort_name') {
3277 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3280 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3282 $fieldsub[] = " ( $wc $op $value )";
3283 if ($config->includeNickNameInName
) {
3284 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3285 $fieldsub[] = " ( $wc $op $value )";
3287 if ($config->includeEmailInName
) {
3288 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3290 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3291 // I seperated the glueing in two. The first stage should always be OR because we are searching for matches in *ANY* of these fields
3296 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3298 $this->_where
[$grouping][] = $sub;
3299 if ($config->includeEmailInName
) {
3300 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3301 $this->_qill
[$grouping][] = ts('Name or Email ') . "$op - '$name'";
3304 $this->_qill
[$grouping][] = ts('Name like') . " - '$name'";
3309 * where / qill clause for email
3316 function email(&$values) {
3317 list($name, $op, $value, $grouping, $wildcard) = $values;
3321 $config = CRM_Core_Config
::singleton();
3323 if (substr($n, 0, 1) == '"' &&
3324 substr($n, -1, 1) == '"'
3326 $n = substr($n, 1, -1);
3327 $value = strtolower(CRM_Core_DAO
::escapeString($n));
3328 $value = "'$value'";
3332 $value = strtolower($n);
3334 if (strpos($value, '%') === FALSE) {
3335 $value = "%{$value}%";
3340 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3341 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3344 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3345 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3348 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3352 * where / qill clause for phone number
3359 function phone_numeric(&$values) {
3360 list($name, $op, $value, $grouping, $wildcard) = $values;
3361 // Strip non-numeric characters; allow wildcards
3362 $number = preg_replace('/[^\d%]/', '', $value);
3364 if ( strpos($number, '%') === FALSE ) {
3365 $number = "%$number%";
3368 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3369 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3370 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3375 * where / qill clause for phone type/location
3382 function phone_option_group($values) {
3383 list($name, $op, $value, $grouping, $wildcard) = $values;
3384 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3385 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3386 $optionName = $options[$value];
3387 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3388 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3389 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3393 * where / qill clause for street_address
3400 function street_address(&$values) {
3401 list($name, $op, $value, $grouping, $wildcard) = $values;
3410 $value = strtolower($n);
3411 if (strpos($value, '%') === FALSE) {
3412 // only add wild card if not there
3413 $value = "%{$value}%";
3416 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3417 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3420 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3421 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3424 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3428 * where / qill clause for street_unit
3435 function street_number(&$values) {
3436 list($name, $op, $value, $grouping, $wildcard) = $values;
3444 if (strtolower($n) == 'odd') {
3445 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3446 $this->_qill
[$grouping][] = ts('Street Number is odd');
3448 elseif (strtolower($n) == 'even') {
3449 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3450 $this->_qill
[$grouping][] = ts('Street Number is even');
3453 $value = strtolower($n);
3455 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3456 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3459 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3463 * where / qill clause for sorting by character
3470 function sortByCharacter(&$values) {
3471 list($name, $op, $value, $grouping, $wildcard) = $values;
3473 $name = trim($value);
3474 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3475 $this->_where
[$grouping][] = $cond;
3476 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3480 * where / qill clause for including contact ids
3485 function includeContactIDs() {
3486 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3490 $contactIds = array();
3491 foreach ($this->_params
as $id => $values) {
3492 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3493 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3496 if (!empty($contactIds)) {
3497 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3502 * where / qill clause for postal code
3509 function postalCode(&$values) {
3510 // skip if the fields dont have anything to do with postal_code
3511 if (empty($this->_fields
['postal_code'])) {
3515 list($name, $op, $value, $grouping, $wildcard) = $values;
3517 // Handle numeric postal code range searches properly by casting the column as numeric
3518 if (is_numeric($value)) {
3519 $field = 'ROUND(civicrm_address.postal_code)';
3520 $val = CRM_Utils_Type
::escape($value, 'Integer');
3523 $field = 'civicrm_address.postal_code';
3524 $val = CRM_Utils_Type
::escape($value, 'String');
3527 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3529 if ($name == 'postal_code') {
3530 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3531 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3533 elseif ($name == 'postal_code_low') {
3534 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3535 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3537 elseif ($name == 'postal_code_high') {
3538 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3539 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3544 * where / qill clause for location type
3547 * @param null $status
3552 function locationType(&$values, $status = NULL) {
3553 list($name, $op, $value, $grouping, $wildcard) = $values;
3555 if (is_array($value)) {
3556 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', array_keys($value)) . ')';
3557 $this->_tables
['civicrm_address'] = 1;
3558 $this->_whereTables
['civicrm_address'] = 1;
3560 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3562 foreach (array_keys($value) as $id) {
3563 $names[] = $locationType[$id];
3566 $this->_primaryLocation
= FALSE;
3569 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3572 return implode(' ' . ts('or') . ' ', $names);
3579 * @param bool $fromStateProvince
3583 function country(&$values, $fromStateProvince = TRUE) {
3584 list($name, $op, $value, $grouping, $wildcard) = $values;
3586 if (!$fromStateProvince) {
3587 $stateValues = $this->getWhereValues('state_province', $grouping);
3588 if (!empty($stateValues)) {
3589 // return back to caller if there are state province values
3590 // since that handles this case
3595 $countryClause = $countryQill = NULL;
3601 $this->_tables
['civicrm_address'] = 1;
3602 $this->_whereTables
['civicrm_address'] = 1;
3604 $countries = CRM_Core_PseudoConstant
::country();
3605 if (is_numeric($value)) {
3606 $countryClause = self
::buildClause(
3607 'civicrm_address.country_id',
3612 $countryName = $countries[(int ) $value];
3616 $intValues = self
::parseSearchBuilderString($value);
3617 if ($intValues && ($op == 'IN' ||
$op == 'NOT IN')) {
3618 $countryClause = self
::buildClause(
3619 'civicrm_address.country_id',
3624 $countryNames = array();
3625 foreach ($intValues as $v) {
3626 $countryNames[] = $countries[$v];
3628 $countryName = implode(',', $countryNames);
3631 $countries = CRM_Core_PseudoConstant
::country();
3632 $intVal = CRM_Utils_Array
::key($value, $countries);
3633 $countryClause = self
::buildClause(
3634 'civicrm_address.country_id',
3639 $countryName = $value;
3642 $countryQill = ts('Country') . " {$op} '$countryName'";
3644 if (!$fromStateProvince) {
3645 $this->_where
[$grouping][] = $countryClause;
3646 $this->_qill
[$grouping][] = $countryQill;
3650 if ($fromStateProvince) {
3651 if (!empty($countryClause)) {
3654 " ...AND... " . $countryQill,
3658 return array(NULL, NULL);
3664 * where / qill clause for county (if present)
3667 * @param null $status
3672 function county(&$values, $status = null) {
3673 list($name, $op, $value, $grouping, $wildcard) = $values;
3675 if (! is_array($value)) {
3676 // force the county to be an array
3677 $value = array($value);
3680 // check if the values are ids OR names of the counties
3681 $inputFormat = 'id';
3682 foreach ($value as $v) {
3683 if (!is_numeric($v)) {
3684 $inputFormat = 'name';
3692 else if ($op == '!=') {
3696 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3697 $op = str_replace('EMPTY', 'NULL', $op);
3700 if (in_array( $op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3701 $clause = "civicrm_address.county_id $op";
3703 elseif ($inputFormat == 'id') {
3704 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3706 $county = CRM_Core_PseudoConstant
::county();
3707 foreach ($value as $id) {
3708 $names[] = CRM_Utils_Array
::value($id, $county);
3712 $inputClause = array();
3713 $county = CRM_Core_PseudoConstant
::county();
3714 foreach ($value as $name) {
3715 $name = trim($name);
3716 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3718 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3721 $this->_tables
['civicrm_address'] = 1;
3722 $this->_whereTables
['civicrm_address'] = 1;
3724 $this->_where
[$grouping][] = $clause;
3726 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3728 return implode(' ' . ts('or') . ' ', $names);
3733 * where / qill clause for state/province AND country (if present)
3736 * @param null $status
3741 function stateProvince(&$values, $status = NULL) {
3742 list($name, $op, $value, $grouping, $wildcard) = $values;
3744 // quick escape for IS NULL
3745 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3748 else if (!is_array($value)) {
3749 // force the state to be an array
3750 // check if its in the mapper format!
3751 $values = self
::parseSearchBuilderString($value);
3752 if (is_array($values)) {
3756 $value = array($value);
3760 // check if the values are ids OR names of the states
3761 $inputFormat = 'id';
3763 foreach ($value as $v) {
3764 if (!is_numeric($v)) {
3765 $inputFormat = 'name';
3775 else if ($op == '!=') {
3779 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3780 $op = str_replace('EMPTY', 'NULL', $op);
3782 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3783 $stateClause = "civicrm_address.state_province_id $op";
3785 else if ($inputFormat == 'id') {
3786 if ($op != 'NOT IN') {
3789 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
3791 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3792 foreach ($value as $id) {
3793 $names[] = CRM_Utils_Array
::value($id, $stateProvince);
3797 $inputClause = array();
3798 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3799 foreach ($value as $name) {
3800 $name = trim($name);
3801 $inputClause[] = CRM_Utils_Array
::key($name, $stateProvince);
3803 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
3806 $this->_tables
['civicrm_address'] = 1;
3807 $this->_whereTables
['civicrm_address'] = 1;
3809 $countryValues = $this->getWhereValues('country', $grouping);
3810 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3812 if ($countryClause) {
3813 $clause = "( $stateClause AND $countryClause )";
3816 $clause = $stateClause;
3819 $this->_where
[$grouping][] = $clause;
3821 $this->_qill
[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3824 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
3829 * where / qill clause for change log
3836 function changeLog(&$values) {
3837 list($name, $op, $value, $grouping, $wildcard) = $values;
3839 $targetName = $this->getWhereValues('changed_by', $grouping);
3844 $name = trim($targetName[2]);
3845 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3846 $name = $targetName[4] ?
"%$name%" : $name;
3847 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3848 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3849 $this->_qill
[$grouping][] = ts('Modified by') . ": $name";
3855 function modifiedDates($values) {
3856 $this->_useDistinct
= TRUE;
3858 // CRM-11281, default to added date if not set
3859 $fieldTitle = ts('Added Date');
3860 $fieldName = 'created_date';
3861 foreach (array_keys($this->_params
) as $id) {
3862 if ($this->_params
[$id][0] == 'log_date') {
3863 if ($this->_params
[$id][2] == 2) {
3864 $fieldTitle = ts('Modified Date');
3865 $fieldName = 'modified_date';
3871 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3873 self
::$_openedPanes[ts('Change Log')] = TRUE;
3879 function demographics(&$values) {
3880 list($name, $op, $value, $grouping, $wildcard) = $values;
3882 if (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3884 $this->dateQueryBuilder($values,
3885 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3888 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3890 $this->dateQueryBuilder($values,
3891 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3895 self
::$_openedPanes[ts('Demographics')] = TRUE;
3901 function privacy(&$values) {
3902 list($name, $op, $value, $grouping, $wildcard) = $values;
3903 //fixed for profile search listing CRM-4633
3904 if (strpbrk($value, "[")) {
3905 $value = "'{$value}'";
3907 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3910 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3912 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3913 $title = $field ?
$field['title'] : $name;
3914 $this->_qill
[$grouping][] = "$title $op $value";
3920 function privacyOptions($values) {
3921 list($name, $op, $value, $grouping, $wildcard) = $values;
3923 if (empty($value) ||
!is_array($value)) {
3927 // get the operator and toggle values
3928 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3931 strtolower($opValues[2] == 'AND')
3936 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3938 if ($toggleValues &&
3939 $toggleValues[2] == 2
3946 foreach ($value as $dontCare => $pOption) {
3947 $clauses[] = " ( contact_a.{$pOption} $compareOP 1 ) ";
3948 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3949 $title = $field ?
$field['title'] : $pOption;
3950 $qill[] = " $title $compareOP 1 ";
3953 $this->_where
[$grouping][] = '( ' . implode($operator, $clauses) . ' )';
3954 $this->_qill
[$grouping][] = implode($operator, $qill);
3960 function preferredCommunication(&$values) {
3961 list($name, $op, $value, $grouping, $wildcard) = $values;
3964 if (in_array($op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3967 elseif (!is_array($value)) {
3969 $value = trim($value, ' ()');
3970 if (strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
3971 $v = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
3974 $v = explode(",", $value);
3977 foreach ($v as $item) {
3984 foreach ($value as $key => $checked) {
3991 $commPref = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
3993 $sqlValue = array();
3994 $showValue = array();
3995 $sql = "contact_a.preferred_communication_method";
3996 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3997 $sqlValue[] = "{$sql} {$op}";
4000 foreach ($pref as $val) {
4001 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $val . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' ) ";
4002 $showValue[] = $commPref[$val];
4005 $this->_where
[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
4006 $this->_qill
[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
4010 * where / qill clause for relationship
4017 function relationship(&$values) {
4018 list($name, $op, $value, $grouping, $wildcard) = $values;
4019 if($this->_relationshipValuesAdded
){
4022 // also get values array for relation_target_name
4023 // for relatinship search we always do wildcard
4024 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4025 $relStatus = $this->getWhereValues('relation_status', $grouping);
4026 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4027 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4029 $nameClause = $name = NULL;
4031 $name = trim($targetName[2]);
4032 if (substr($name, 0, 1) == '"' &&
4033 substr($name, -1, 1) == '"'
4035 $name = substr($name, 1, -1);
4036 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4037 $nameClause = "= '$name'";
4040 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4041 $nameClause = "LIKE '%{$name}%'";
4045 $rel = explode('_', $value);
4047 self
::$_relType = $rel[1];
4048 $params = array('id' => $rel[0]);
4049 $rTypeValues = array();
4050 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
4051 if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
4052 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4053 //@todo unless we are dealing with a target group
4054 self
::$_relType = 'reciprocal';
4056 // if we are creating a temp table we build our own where for the relationship table
4057 $relationshipTempTable = NULL;
4058 if(self
::$_relType == 'reciprocal' && empty($targetGroup)) {
4060 self
::$_relationshipTempTable =
4061 $relationshipTempTable =
4062 CRM_Core_DAO
::createTempTableName( 'civicrm_rel');
4064 $where[$grouping][] = " sort_name $nameClause ";
4068 $where = &$this->_where
;
4070 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4075 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
4076 $relTypeOrg = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
4077 $relTypeHou = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Household');
4078 $allRelationshipType = array();
4079 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
4080 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
4082 if ($nameClause ||
!$targetGroup) {
4083 $this->_qill
[$grouping][] = "$allRelationshipType[$value] $name";
4087 //check to see if the target contact is in specified group
4089 //add contacts from static groups
4090 $this->_tables
['civicrm_relationship_group_contact'] =
4091 $this->_whereTables
['civicrm_relationship_group_contact'] =
4092 " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = contact_b.id AND civicrm_relationship_group_contact.status = 'Added'";
4094 "( civicrm_relationship_group_contact.group_id IN (" .
4095 implode(",", $targetGroup[2]) . ") ) ";
4097 //add contacts from saved searches
4098 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
4100 //set the group where clause
4102 $groupWhere[] = "( " . $ssWhere . " )";
4104 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4106 //Get the names of the target groups for the qill
4107 $groupNames = CRM_Core_PseudoConstant
::group();
4108 $qillNames = array();
4109 foreach ($targetGroup[2] as $groupId) {
4110 if (array_key_exists($groupId, $groupNames)) {
4111 $qillNames[] = $groupNames[$groupId];
4114 $this->_qill
[$grouping][] = "$allRelationshipType[$value] ( " . implode(", ", $qillNames) . " )";
4117 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4118 $today = date('Ymd');
4119 //check for active, inactive and all relation status
4120 if ($relStatus[2] == 0) {
4121 $where[$grouping][] = "(
4122 civicrm_relationship.is_active = 1 AND
4123 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4124 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4126 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4128 elseif ($relStatus[2] == 1) {
4129 $where[$grouping][] = "(
4130 civicrm_relationship.is_active = 0 OR
4131 civicrm_relationship.end_date < {$today} OR
4132 civicrm_relationship.start_date > {$today}
4134 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4137 //check for permissioned, non-permissioned and all permissioned relations
4138 if ($relPermission[2] == 1) {
4139 $this->_where
[$grouping][] = "(
4140 civicrm_relationship.is_permission_a_b = 1
4142 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4143 } elseif ($relPermission[2] == 2) {
4144 //non-allowed permission relationship.
4145 $this->_where
[$grouping][] = "(
4146 civicrm_relationship.is_permission_a_b = 0
4148 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4151 $this->addRelationshipDateClauses($grouping, $where);
4152 if(!empty($rType) && isset($rType->id
)){
4153 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
4155 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4156 $this->_useDistinct
= TRUE;
4157 $this->_relationshipValuesAdded
= TRUE;
4158 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4160 // @todo creating a temp table could be expanded to group filter
4161 // as even creating a temp table of all relationships is much much more efficient than
4162 // an OR in the join
4163 if($relationshipTempTable) {
4164 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4166 CREATE TEMPORARY TABLE {$relationshipTempTable}
4167 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4168 FROM civicrm_relationship
4169 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4172 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4173 FROM civicrm_relationship
4174 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4177 CRM_Core_DAO
::executeQuery($sql);
4182 * Add start & end date criteria in
4183 * @param string $grouping
4184 * @param array $where = array to add where clauses to, in case you are generating a temp table
4185 * not the main query.
4187 function addRelationshipDateClauses($grouping, &$where){
4188 $dateValues = array();
4194 foreach ($dateTypes as $dateField){
4195 $dateValueLow = $this->getWhereValues('relation_'. $dateField .'_low', $grouping);
4196 $dateValueHigh= $this->getWhereValues('relation_'. $dateField .'_high', $grouping);
4197 if(!empty($dateValueLow)){
4198 $date = date('Ymd', strtotime($dateValueLow[2]));
4199 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4200 $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);
4202 if(!empty($dateValueHigh)){
4203 $date = date('Ymd', strtotime($dateValueHigh[2]));
4204 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4205 $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);
4211 * default set of return properties
4215 * @return array derault return properties
4218 static function &defaultReturnProperties($mode = 1) {
4219 if (!isset(self
::$_defaultReturnProperties)) {
4220 self
::$_defaultReturnProperties = array();
4223 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4224 // add activity return properties
4225 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4226 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4229 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4232 if (empty(self
::$_defaultReturnProperties[$mode])) {
4233 self
::$_defaultReturnProperties[$mode] = array(
4236 'legal_identifier' => 1,
4237 'external_identifier' => 1,
4238 'contact_type' => 1,
4239 'contact_sub_type' => 1,
4241 'display_name' => 1,
4242 'preferred_mail_format' => 1,
4249 'formal_title' => 1,
4250 'communication_style_id' => 1,
4253 'street_address' => 1,
4254 'supplemental_address_1' => 1,
4255 'supplemental_address_2' => 1,
4258 'postal_code_suffix' => 1,
4259 'state_province' => 1,
4261 'world_region' => 1,
4268 'household_name' => 1,
4269 'organization_name' => 1,
4270 'deceased_date' => 1,
4275 'current_employer' => 1,
4276 // FIXME: should we use defaultHierReturnProperties() for the below?
4277 'do_not_email' => 1,
4280 'do_not_phone' => 1,
4281 'do_not_trade' => 1,
4283 'contact_is_deleted' => 1,
4284 'preferred_communication_method' => 1,
4285 'preferred_language' => 1,
4289 return self
::$_defaultReturnProperties[$mode];
4293 * get primary condition for a sql clause
4297 * @return string|NULL
4300 static function getPrimaryCondition($value) {
4301 if (is_numeric($value)) {
4302 $value = (int ) $value;
4303 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4309 * wrapper for a simple search query
4311 * @param array $params
4312 * @param array $returnProperties
4313 * @param bool $count
4318 static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4319 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4320 list($select, $from, $where, $having) = $query->query();
4322 return "$select $from $where $having";
4326 * These are stub comments as this function needs more explanation - particularly in terms of how it
4327 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4329 * This function was originally written as a wrapper for the api query but is called from multiple places
4330 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4331 * but it is unclear as to whehter that is historical or there is a reason
4332 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4334 * @param array $params
4335 * @param array $returnProperties
4336 * @param null $fields
4337 * @param string $sort
4338 * @param int $offset
4339 * @param int $row_count
4340 * @param bool $smartGroupCache
4341 * @param bool $count return count obnly
4342 * @param bool $skipPermissions Should permissions be ignored or should the logged in user's permissions be applied
4344 * @params bool $smartGroupCache ?? update smart group cache?
4349 static function apiQuery(
4351 $returnProperties = NULL,
4356 $smartGroupCache = TRUE,
4358 $skipPermissions = TRUE
4361 $query = new CRM_Contact_BAO_Query(
4362 $params, $returnProperties,
4363 NULL, TRUE, FALSE, 1,
4365 TRUE, $smartGroupCache
4368 //this should add a check for view deleted if permissions are enabled
4369 if ($skipPermissions){
4370 $query->_skipDeleteClause
= TRUE;
4372 $query->generatePermissionClause(FALSE, $count);
4374 // note : this modifies _fromClause and _simpleFromClause
4375 $query->includePseudoFieldsJoin($sort);
4377 list($select, $from, $where, $having) = $query->query($count);
4379 $options = $query->_options
;
4380 if(!empty($query->_permissionWhereClause
)){
4381 if (empty($where)) {
4382 $where = "WHERE $query->_permissionWhereClause";
4385 $where = "$where AND $query->_permissionWhereClause";
4389 $sql = "$select $from $where $having";
4392 if ($query->_useGroupBy
) {
4393 $sql .= ' GROUP BY contact_a.id';
4395 if (!empty($sort)) {
4396 $sort = CRM_Utils_Type
::escape($sort, 'String');
4397 $sql .= " ORDER BY $sort ";
4399 if ($row_count > 0 && $offset >= 0) {
4400 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4401 $rowCount = CRM_Utils_Type
::escape($row_count, 'Int');
4402 $sql .= " LIMIT $offset, $row_count ";
4405 $dao = CRM_Core_DAO
::executeQuery($sql);
4408 while ($dao->fetch()) {
4410 $noRows = $dao->rowCount
;
4412 return array($noRows,NULL);
4414 $val = $query->store($dao);
4415 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4417 if (!empty($convertedVals)) {
4418 $val = array_replace_recursive($val, $convertedVals);
4420 $values[$dao->contact_id
] = $val;
4423 return array($values, $options);
4427 * create and query the db for an contact search
4429 * @param int $offset the offset for the query
4430 * @param int $rowCount the number of rows to return
4431 * @param string $sort the order by string
4432 * @param boolean $count is this a count only query ?
4433 * @param boolean $includeContactIds should we include contact ids?
4434 * @param boolean $sortByChar if true returns the distinct array of first characters for search results
4435 * @param boolean $groupContacts if true, return only the contact ids
4436 * @param boolean $returnQuery should we return the query as a string
4437 * @param string $additionalWhereClause if the caller wants to further restrict the search (used for components)
4438 * @param null $sortOrder
4439 * @param string $additionalFromClause should be clause with proper joins, effective to reduce where clause load.
4441 * @param bool $skipOrderAndLimit
4443 * @return CRM_Core_DAO
4446 function searchQuery(
4447 $offset = 0, $rowCount = 0, $sort = NULL,
4448 $count = FALSE, $includeContactIds = FALSE,
4449 $sortByChar = FALSE, $groupContacts = FALSE,
4450 $returnQuery = FALSE,
4451 $additionalWhereClause = NULL, $sortOrder = NULL,
4452 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4455 if ($includeContactIds) {
4456 $this->_includeContactIds
= TRUE;
4457 $this->_whereClause
= $this->whereClause();
4460 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4462 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4463 // and that contact happens to be deleted, set $onlyDeleted to true
4464 foreach ($this->_params
as $values) {
4465 $name = CRM_Utils_Array
::value(0, $values);
4466 $op = CRM_Utils_Array
::value(1, $values);
4467 $value = CRM_Utils_Array
::value(2, $values);
4468 if ($name == 'contact_id' and $op == '=') {
4469 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4470 $onlyDeleted = TRUE;
4476 // building the query string
4479 if (isset($this->_groupByComponentClause
)) {
4480 $groupBy = $this->_groupByComponentClause
;
4482 elseif ($this->_useGroupBy
) {
4483 $groupBy = ' GROUP BY contact_a.id';
4486 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4487 $groupBy = 'GROUP BY civicrm_activity.id ';
4490 $order = $orderBy = $limit = '';
4492 $config = CRM_Core_Config
::singleton();
4493 if ($config->includeOrderByClause ||
4494 isset($this->_distinctComponentClause
)
4497 if (is_string($sort)) {
4501 $orderBy = trim($sort->orderBy());
4503 if (!empty($orderBy)) {
4504 // this is special case while searching for
4505 // change log CRM-1718
4506 if (preg_match('/sort_name/i', $orderBy)) {
4507 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4510 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
4511 $order = " ORDER BY $orderBy";
4514 $sortOrder = CRM_Utils_Type
::escape($sortOrder, 'String');
4515 $order .= " $sortOrder";
4518 // always add contact_a.id to the ORDER clause
4519 // so the order is deterministic
4520 if (strpos('contact_a.id', $order) === FALSE) {
4521 $order .= ", contact_a.id";
4525 elseif ($sortByChar) {
4526 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4529 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4533 // hack for order clause
4535 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4536 $fieldOrder = explode(' ', $fieldStr);
4537 $field = $fieldOrder[0];
4543 $this->_whereTables
["civicrm_address"] = 1;
4544 $order = str_replace($field, "civicrm_address.{$field}", $order);
4548 case 'state_province':
4549 $this->_whereTables
["civicrm_{$field}"] = 1;
4550 $order = str_replace($field, "civicrm_{$field}.name", $order);
4554 $this->_whereTables
["civicrm_email"] = 1;
4555 $order = str_replace($field, "civicrm_email.{$field}", $order);
4559 //CRM-12565 add "`" around $field if it is a pseudo constant
4560 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
4561 if (!empty($value['element']) && $value['element'] == $field) {
4562 $order = str_replace($field, "`{$field}`", $order);
4566 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4567 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4571 if ($rowCount > 0 && $offset >= 0) {
4572 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4573 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4574 $limit = " LIMIT $offset, $rowCount ";
4578 // note : this modifies _fromClause and _simpleFromClause
4579 $this->includePseudoFieldsJoin($sort);
4581 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4583 if ($additionalWhereClause) {
4584 $where = $where . ' AND ' . $additionalWhereClause;
4587 //additional from clause should be w/ proper joins.
4588 if ($additionalFromClause) {
4589 $from .= "\n" . $additionalFromClause;
4592 // if we are doing a transform, do it here
4593 // use the $from, $where and $having to get the contact ID
4594 if ($this->_displayRelationshipType
) {
4595 $this->filterRelatedContacts($from, $where, $having);
4598 if ($skipOrderAndLimit) {
4599 $query = "$select $from $where $having $groupBy";
4602 $query = "$select $from $where $having $groupBy $order $limit";
4609 return CRM_Core_DAO
::singleValueQuery($query);
4612 $dao = CRM_Core_DAO
::executeQuery($query);
4613 if ($groupContacts) {
4615 while ($dao->fetch()) {
4618 return implode(',', $ids);
4625 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4627 * @param string $cacheKey
4628 * @param int $offset
4629 * @param int $rowCount
4630 * @param bool $includeContactIds
4631 * @return CRM_Core_DAO
4633 function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4634 $this->_includeContactIds
= $includeContactIds;
4635 list($select, $from, $where) = $this->query();
4636 $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);
4637 $order = " ORDER BY pnc.id";
4638 $groupBy = " GROUP BY contact_a.id";
4639 $limit = " LIMIT $offset, $rowCount";
4640 $query = "$select $from $where $groupBy $order $limit";
4642 return CRM_Core_DAO
::executeQuery($query);
4646 * Populate $this->_permissionWhereClause with permission related clause and update other
4647 * query related properties.
4649 * Function calls ACL permission class and hooks to filter the query appropriately
4651 * Note that these 2 params were in the code when extracted from another function
4652 * and a second round extraction would be to make them properties of the class
4654 * @param bool $onlyDeleted Only get deleted contacts
4655 * @param bool $count Return Count only
4659 function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4660 if (!$this->_skipPermission
) {
4661 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4662 CRM_Core_Permission
::VIEW
,
4664 $this->_whereTables
,
4667 $this->_skipDeleteClause
4670 // regenerate fromClause since permission might have added tables
4671 if ($this->_permissionWhereClause
) {
4672 //fix for row count in qill (in contribute/membership find)
4674 $this->_useDistinct
= TRUE;
4677 if (empty($this->_fromClause
)) {
4678 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4681 if (empty($this->_simpleFromClause
)) {
4682 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4687 // add delete clause if needed even if we are skipping permission
4689 if (!$this->_skipDeleteClause
) {
4690 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4691 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4695 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4704 function setSkipPermission($val) {
4705 $this->_skipPermission
= $val;
4709 * @param null $context
4713 function &summaryContribution($context = NULL) {
4714 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4718 SELECT COUNT( conts.total_amount ) as total_count,
4719 SUM( conts.total_amount ) as total_amount,
4720 AVG( conts.total_amount ) as total_avg,
4721 conts.currency as currency";
4722 if($this->_permissionWhereClause
) {
4723 $where .= " AND " . $this->_permissionWhereClause
;
4725 if ($context == 'search') {
4726 $where .= " AND contact_a.is_deleted = 0 ";
4729 // make sure contribution is completed - CRM-4989
4730 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4734 $summary['total'] = array();
4735 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4737 $query = "$select FROM (
4738 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $completedWhere
4739 GROUP BY civicrm_contribution.id
4743 $dao = CRM_Core_DAO
::executeQuery($query);
4745 $summary['total']['count'] = 0;
4746 $summary['total']['amount'] = $summary['total']['avg'] = array();
4747 while ($dao->fetch()) {
4748 $summary['total']['count'] +
= $dao->total_count
;
4749 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4750 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4752 if (!empty($summary['total']['amount'])) {
4753 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4754 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4757 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4760 // soft credit summary
4761 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
4762 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
4765 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
4766 GROUP BY civicrm_contribution_soft.id
4769 $dao = CRM_Core_DAO
::executeQuery($query);
4770 $summary['soft_credit']['count'] = 0;
4771 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
4772 while ($dao->fetch()) {
4773 $summary['soft_credit']['count'] +
= $dao->total_count
;
4774 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4775 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4777 if (!empty($summary['soft_credit']['amount'])) {
4778 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
4779 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
4782 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
4787 //@todo - this could be one query using the IF in mysql - eg
4788 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
4789 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
4790 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
4791 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
4792 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
4793 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
4794 // FROM civicrm_contact contact_a
4795 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
4796 // WHERE ( ... where clause....
4797 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
4801 SELECT COUNT( conts.total_amount ) as cancel_count,
4802 SUM( conts.total_amount ) as cancel_amount,
4803 AVG( conts.total_amount ) as cancel_avg,
4804 conts.currency as currency";
4806 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4807 if ($context == 'search') {
4808 $where .= " AND contact_a.is_deleted = 0 ";
4811 $query = "$select FROM (
4812 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
4813 GROUP BY civicrm_contribution.id
4817 $dao = CRM_Core_DAO
::executeQuery($query);
4820 if ($dao->fetch()) {
4821 $summary['cancel']['count'] = $dao->cancel_count
;
4822 $summary['cancel']['amount'] = $dao->cancel_amount
;
4823 $summary['cancel']['avg'] = $dao->cancel_avg
;
4827 $summary['cancel']['count'] = 0;
4828 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4829 while ($dao->fetch()) {
4830 $summary['cancel']['count'] +
= $dao->cancel_count
;
4831 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4832 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4834 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4835 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
4842 * getter for the qill object
4848 return $this->_qill
;
4852 * default set of return default hier return properties
4857 static function &defaultHierReturnProperties() {
4858 if (!isset(self
::$_defaultHierReturnProperties)) {
4859 self
::$_defaultHierReturnProperties = array(
4862 'legal_identifier' => 1,
4863 'external_identifier' => 1,
4864 'contact_type' => 1,
4865 'contact_sub_type' => 1,
4867 'display_name' => 1,
4874 'formal_title' => 1,
4875 'communication_style_id' => 1,
4876 'email_greeting' => 1,
4877 'postal_greeting' => 1,
4881 'preferred_communication_method' => 1,
4882 'do_not_phone' => 1,
4883 'do_not_email' => 1,
4886 'do_not_trade' => 1,
4889 '1' => array('location_type' => 1,
4890 'street_address' => 1,
4892 'state_province' => 1,
4894 'postal_code_suffix' => 1,
4897 'phone-Mobile' => 1,
4910 'location_type' => 1,
4911 'street_address' => 1,
4913 'state_province' => 1,
4915 'postal_code_suffix' => 1,
4918 'phone-Mobile' => 1,
4932 return self
::$_defaultHierReturnProperties;
4939 * @param $dbFieldName
4940 * @param $fieldTitle
4941 * @param bool $appendTimeStamp
4943 function dateQueryBuilder(
4944 &$values, $tableName, $fieldName,
4945 $dbFieldName, $fieldTitle,
4946 $appendTimeStamp = TRUE
4948 list($name, $op, $value, $grouping, $wildcard) = $values;
4954 if ($name == "{$fieldName}_low" ||
4955 $name == "{$fieldName}_high"
4957 if (isset($this->_rangeCache
[$fieldName])) {
4960 $this->_rangeCache
[$fieldName] = 1;
4962 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4964 if ($name == $fieldName . '_low') {
4966 $firstPhrase = ts('greater than or equal to');
4967 $firstDate = CRM_Utils_Date
::processDate($value);
4969 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4970 if (!empty($secondValues) && $secondValues[2]) {
4972 $secondPhrase = ts('less than or equal to');
4973 $secondValue = $secondValues[2];
4975 if ($appendTimeStamp && strlen($secondValue) == 10) {
4976 $secondValue .= ' 23:59:59';
4978 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4981 elseif ($name == $fieldName . '_high') {
4983 $firstPhrase = ts('less than or equal to');
4985 if ($appendTimeStamp && strlen($value) == 10) {
4986 $value .= ' 23:59:59';
4988 $firstDate = CRM_Utils_Date
::processDate($value);
4990 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4991 if (!empty($secondValues) && $secondValues[2]) {
4993 $secondPhrase = ts('greater than or equal to');
4994 $secondValue = $secondValues[2];
4995 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4999 if (!$appendTimeStamp) {
5000 $firstDate = substr($firstDate, 0, 8);
5002 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5005 if (!$appendTimeStamp) {
5006 $secondDate = substr($secondDate, 0, 8);
5008 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5011 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5013 $this->_where
[$grouping][] = "
5014 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5015 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5017 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5020 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5021 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5025 if ($name == $fieldName) {
5029 $date = CRM_Utils_Date
::processDate($value);
5031 if (!$appendTimeStamp) {
5032 $date = substr($date, 0, 8);
5035 $format = CRM_Utils_Date
::customFormat($date);
5038 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'";
5041 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op";
5043 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5044 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$format\"";
5052 * @param $dbFieldName
5053 * @param $fieldTitle
5054 * @param null $options
5056 function numberRangeBuilder(&$values,
5057 $tableName, $fieldName,
5058 $dbFieldName, $fieldTitle,
5061 list($name, $op, $value, $grouping, $wildcard) = $values;
5063 if ($name == "{$fieldName}_low" ||
5064 $name == "{$fieldName}_high"
5066 if (isset($this->_rangeCache
[$fieldName])) {
5069 $this->_rangeCache
[$fieldName] = 1;
5071 $secondOP = $secondPhrase = $secondValue = NULL;
5073 if ($name == "{$fieldName}_low") {
5075 $firstPhrase = ts('greater than');
5077 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5078 if (!empty($secondValues)) {
5080 $secondPhrase = ts('less than');
5081 $secondValue = $secondValues[2];
5086 $firstPhrase = ts('less than');
5088 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5089 if (!empty($secondValues)) {
5091 $secondPhrase = ts('greater than');
5092 $secondValue = $secondValues[2];
5097 $this->_where
[$grouping][] = "
5098 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5099 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5101 $displayValue = $options ?
$options[$value] : $value;
5102 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5104 $this->_qill
[$grouping][] =
5105 "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5108 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5109 $displayValue = $options ?
$options[$value] : $value;
5110 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5112 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5117 if ($name == $fieldName) {
5121 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5123 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5124 $displayValue = $options ?
$options[$value] : $value;
5125 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5132 * Given the field name, operator, value & its data type
5133 * builds the where Clause for the query
5134 * used for handling 'IS NULL'/'IS NOT NULL' operators
5136 * @param string $field fieldname
5137 * @param string $op operator
5138 * @param string $value value
5139 * @param string $dataType data type of the field
5141 * @return string where clause for the query
5144 static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5146 $clause = "$field $op";
5154 $clause = " (NULLIF($field, '') IS NULL) ";
5157 case 'IS NOT EMPTY':
5158 $clause = " (NULLIF($field, '') IS NOT NULL) ";
5163 if (isset($dataType)) {
5164 if (is_array($value)) {
5168 $value = CRM_Utils_Type
::escape($value, "String");
5169 $values = explode(',', CRM_Utils_Array
::value(0, explode(')', CRM_Utils_Array
::value(1, explode('(', $value)))));
5171 // supporting multiple values in IN clause
5173 foreach ($values as $v) {
5175 $val[] = "'" . CRM_Utils_Type
::escape($v, $dataType) . "'";
5177 $value = "(" . implode($val, ",") . ")";
5179 return "$clause $value";
5182 if (empty($dataType)) {
5183 $dataType = 'String';
5186 $value = CRM_Utils_Type
::escape($value, $dataType);
5187 // if we don't have a dataType we should assume
5188 if ($dataType == 'String' ||
$dataType == 'Text') {
5189 $value = "'" . strtolower($value) . "'";
5191 return "$clause $value";
5196 * @param bool $reset
5200 function openedSearchPanes($reset = FALSE) {
5201 if (!$reset ||
empty($this->_whereTables
)) {
5202 return self
::$_openedPanes;
5205 // pane name to table mapper
5206 $panesMapper = array(
5207 ts('Contributions') => 'civicrm_contribution',
5208 ts('Memberships') => 'civicrm_membership',
5209 ts('Events') => 'civicrm_participant',
5210 ts('Relationships') => 'civicrm_relationship',
5211 ts('Activities') => 'civicrm_activity',
5212 ts('Pledges') => 'civicrm_pledge',
5213 ts('Cases') => 'civicrm_case',
5214 ts('Grants') => 'civicrm_grant',
5215 ts('Address Fields') => 'civicrm_address',
5216 ts('Notes') => 'civicrm_note',
5217 ts('Change Log') => 'civicrm_log',
5218 ts('Mailings') => 'civicrm_mailing_event_queue',
5220 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5222 foreach (array_keys($this->_whereTables
) as $table) {
5223 if ($panName = array_search($table, $panesMapper)) {
5224 self
::$_openedPanes[$panName] = TRUE;
5228 return self
::$_openedPanes;
5234 function setOperator($operator) {
5235 $validOperators = array('AND', 'OR');
5236 if (!in_array($operator, $validOperators)) {
5239 $this->_operator
= $operator;
5245 function getOperator() {
5246 return $this->_operator
;
5254 function filterRelatedContacts(&$from, &$where, &$having) {
5255 static $_rTypeProcessed = NULL;
5256 static $_rTypeFrom = NULL;
5257 static $_rTypeWhere = NULL;
5259 if (!$_rTypeProcessed) {
5260 $_rTypeProcessed = TRUE;
5262 // create temp table with contact ids
5263 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5264 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5265 CRM_Core_DAO
::executeQuery($sql);
5268 REPLACE INTO $tableName ( contact_id )
5274 CRM_Core_DAO
::executeQuery($sql);
5276 $qillMessage = ts('Contacts with a Relationship Type of: ');
5277 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5279 if (is_numeric($this->_displayRelationshipType
)) {
5280 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5282 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5283 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5286 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5287 AND displayRelType.is_active = 1
5291 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5292 if ($dirOne == 'a') {
5293 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5295 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5296 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5300 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5302 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5303 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5307 WHERE displayRelType.relationship_type_id = $relType
5308 AND displayRelType.is_active = 1
5311 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5314 if (strpos($from, $_rTypeFrom) === FALSE) {
5315 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5316 // this happens when we have an event_type in the quert (CRM-7969)
5317 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5318 $from .= $_rTypeFrom;
5319 $where = $_rTypeWhere;
5330 static function caseImportant( $op ) {
5332 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5336 * @param $returnProperties
5341 static function componentPresent( &$returnProperties, $prefix ) {
5342 foreach ($returnProperties as $name => $dontCare ) {
5343 if (substr($name, 0, strlen($prefix)) == $prefix) {
5351 * Builds the necessary structures for all fields that are similar to option value lookups
5353 * @param $name string the name of the field
5354 * @param $op string the sql operator, this function should handle ALL SQL operators
5355 * @param $value string|integer|array depends on the operator and who's calling the query builder
5356 * @param $grouping int the index where to place the where clause
5357 * @param $selectValues
5358 * @param $field array an array that contains various properties of the field identified by $name
5359 * @param $label string The label for this field element
5360 * @param $dataType string The data type for this element
5362 * @param bool $useIDsOnly
5364 * @internal param array $selectValue the key value pairs for this element. This allows us to use this function for things besides option-value pairs
5365 * @return void adds the where clause and qill to the query object
5367 function optionValueQuery(
5375 $dataType = 'String',
5379 if (!empty($selectValues) && !is_array($value) && !empty($selectValues[$value])) {
5380 $qill = $selectValues[$value];
5386 $pseudoFields = array('email_greeting', 'postal_greeting', 'addressee', 'gender_id', 'prefix_id', 'suffix_id', 'communication_style_id');
5388 if (is_numeric($value)) {
5389 $qill = $selectValues[(int ) $value];
5391 elseif ($op == 'IN' ||
$op == 'NOT IN') {
5392 if (is_array($value)) {
5394 $newValues = array();
5395 foreach ($value as $k => $v) {
5396 $intVals[$k] = (int) $k;
5397 $newValues[] = $selectValues[(int) $k];
5400 $value = (in_array($name, $pseudoFields)) ?
$intVals : $newValues;
5401 $qill = implode(', ', $newValues);
5404 elseif (!array_key_exists($value, $selectValues)) {
5405 // its a string, lets get the int value
5406 $value = array_search($value, $selectValues);
5409 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5410 if ($tableName == 'civicrm_contact') {
5411 $wc = "contact_a.$fieldName";
5415 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5418 if (in_array($name, $pseudoFields)) {
5419 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5420 $wc = "contact_a.{$name}_id";
5422 $dataType = 'Positive';
5423 $value = (!$value) ?
0 : $value;
5426 $this->_qill
[$grouping][] = $label . " $op '$qill'";
5427 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' ||
$op == 'RLIKE')) ?
'=' : $op;
5428 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5432 * function to check and explode a user defined numeric string into an array
5433 * this was the protocol used by search builder in the old old days before we had
5434 * super nice js widgets to do the hard work
5436 * @param string $string
5437 * @param string $dataType the dataType we should check for the values, default integer
5439 * @return bool|array if string does not match the patter
5440 * array of numeric values if string does match the pattern
5443 static function parseSearchBuilderString($string, $dataType = 'Integer') {
5444 $string = trim($string);
5445 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5449 $string = substr($string, 1, -1);
5450 $values = explode(',', $string);
5451 if (empty($values)) {
5455 $returnValues = array();
5456 foreach ($values as $v) {
5457 if ($dataType == 'Integer' && ! is_numeric($v)) {
5460 else if ($dataType == 'String' && ! is_string($v)) {
5463 $returnValues[] = trim($v);
5466 if (empty($returnValues)) {
5470 return $returnValues;
5474 * convert the pseudo constants id's to their names
5476 * @param CRM_Core_DAO dao
5477 * @param bool $return
5481 function convertToPseudoNames(&$dao, $return = FALSE) {
5482 if (empty($this->_pseudoConstantsSelect
)) {
5486 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5487 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5491 if (property_exists($dao, $value['idCol'])) {
5492 $val = $dao->$value['idCol'];
5494 if (CRM_Utils_System
::isNull($val)) {
5497 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5499 $idColumn = "{$key}_id";
5500 $dao->$idColumn = $val;
5502 if ($key == 'state_province_name') {
5503 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5506 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5509 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5510 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5512 // FIX ME: we should potentially move this to component Query and write a wrapper function that
5513 // handles pseudoconstant fixes for all component
5514 elseif ($value['pseudoField'] == 'participant_role') {
5515 $viewRoles = array();
5516 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val) as $k => $v) {
5517 $viewRoles[] = CRM_Event_PseudoConstant
::participantRole($v);
5519 $dao->$key = implode(', ', $viewRoles);
5522 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5523 $dao->$key = $labels[$val];
5526 // return converted values in array format
5528 if (strpos($key, '-') !== FALSE) {
5529 $keyVal = explode('-', $key);
5530 $current = &$values;
5531 $lastElement = array_pop($keyVal);
5532 foreach ($keyVal as $v) {
5533 if (!array_key_exists($v, $current)) {
5534 $current[$v] = array();
5536 $current = &$current[$v];
5538 $current[$lastElement] = $dao->$key;
5541 $values[$key] = $dao->$key;
5550 * include pseudo fields LEFT JOIN
5551 * @param string|array $sort can be a object or string
5555 function includePseudoFieldsJoin($sort) {
5556 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5559 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5562 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5563 if (!empty($value['table'])) {
5564 $regex = "/({$value['table']}\.|{$name})/";
5565 if (preg_match($regex, $sort)) {
5566 $this->_elemnt
[$value['element']] = 1;
5567 $this->_select
[$value['element']] = $value['select'];
5568 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5569 $present[$value['table']] = $value['join'];
5573 $presentSimpleFrom = $present;
5575 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5576 array_key_exists('civicrm_country', $presentSimpleFrom)) {
5577 unset($presentSimpleFrom['civicrm_country']);
5579 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5580 array_key_exists('civicrm_country', $present)) {
5581 unset($present['civicrm_country']);
5584 $presentClause = $presentSimpleFromClause = NULL;
5585 if (!empty($present)) {
5586 $presentClause = implode(' ', $present);
5588 if (!empty($presentSimpleFrom)) {
5589 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5592 $this->_fromClause
= $this->_fromClause
. $presentClause;
5593 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5595 return array($presentClause, $presentSimpleFromClause);