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
1258 * @return array sql query parts as an array
1261 function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE) {
1263 if (isset($this->_rowCountClause
)) {
1264 $select = "SELECT {$this->_rowCountClause}";
1265 } else if (isset($this->_distinctComponentClause
)) {
1266 // we add distinct to get the right count for components
1267 // for the more complex result set, we use GROUP BY the same id
1269 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1272 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1274 $from = $this->_simpleFromClause
;
1275 if ($this->_useDistinct
) {
1276 $this->_useGroupBy
= TRUE;
1279 elseif ($sortByChar) {
1280 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1281 $from = $this->_simpleFromClause
;
1283 elseif ($groupContacts) {
1284 $select = 'SELECT contact_a.id as id';
1285 if ($this->_useDistinct
) {
1286 $this->_useGroupBy
= TRUE;
1288 $from = $this->_simpleFromClause
;
1291 if (!empty($this->_paramLookup
['group'])) {
1292 // make sure there is only one element
1293 // this is used when we are running under smog and need to know
1294 // how the contact was added (CRM-1203)
1295 if ((count($this->_paramLookup
['group']) == 1) &&
1296 (count($this->_paramLookup
['group'][0][2]) == 1)
1298 $groups = array_keys($this->_paramLookup
['group'][0][2]);
1299 $groupId = $groups[0];
1301 //check if group is saved search
1302 $group = new CRM_Contact_BAO_Group();
1303 $group->id
= $groupId;
1306 if (!isset($group->saved_search_id
)) {
1307 $tbName = "`civicrm_group_contact-{$groupId}`";
1308 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1309 $this->_element
['group_contact_id'] = 1;
1310 $this->_select
['status'] = "$tbName.status as status";
1311 $this->_element
['status'] = 1;
1314 $this->_useGroupBy
= TRUE;
1316 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1317 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1319 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1320 $this->_useDistinct
= FALSE;
1321 $this->_useGroupBy
= TRUE;
1325 $select = "SELECT ";
1326 if (isset($this->_distinctComponentClause
)) {
1327 $select .= "{$this->_distinctComponentClause}, ";
1329 $select .= implode(', ', $this->_select
);
1330 $from = $this->_fromClause
;
1334 if (!empty($this->_whereClause
)) {
1335 $where = "WHERE {$this->_whereClause}";
1339 if (!empty($this->_having
)) {
1340 foreach ($this->_having
as $havingSets) {
1341 foreach ($havingSets as $havingSet) {
1342 $havingValue[] = $havingSet;
1345 $having = ' HAVING ' . implode(' AND ', $havingValue);
1348 // if we are doing a transform, do it here
1349 // use the $from, $where and $having to get the contact ID
1350 if ($this->_displayRelationshipType
) {
1351 $this->filterRelatedContacts($from, $where, $having);
1354 return array($select, $from, $where, $having);
1363 function &getWhereValues($name, $grouping) {
1365 foreach ($this->_params
as $values) {
1366 if ($values[0] == $name && $values[3] == $grouping) {
1379 static function fixDateValues($relative, &$from, &$to) {
1381 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1386 * @param $formValues
1387 * @param int $wildcard
1388 * @param bool $useEquals
1392 static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE) {
1394 if (empty($formValues)) {
1398 foreach ($formValues as $id => $values) {
1399 if ($id == 'privacy') {
1400 if (is_array($formValues['privacy'])) {
1401 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1402 foreach ($formValues['privacy'] as $key => $value) {
1404 $params[] = array($key, $op, $value, 0, 0);
1409 elseif ($id == 'email_on_hold') {
1410 if ($formValues['email_on_hold']['on_hold']) {
1411 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1414 elseif (preg_match('/_date_relative$/', $id) ||
1415 $id == 'event_relative' ||
1416 $id == 'case_from_relative' ||
1417 $id == 'case_to_relative'
1419 if ($id == 'event_relative') {
1420 $fromRange = 'event_start_date_low';
1421 $toRange = 'event_end_date_high';
1423 else if ($id == 'case_from_relative') {
1424 $fromRange = 'case_from_start_date_low';
1425 $toRange = 'case_from_start_date_high';
1427 else if ($id == 'case_to_relative') {
1428 $fromRange = 'case_to_end_date_low';
1429 $toRange = 'case_to_end_date_high';
1432 $dateComponent = explode('_date_relative', $id);
1433 $fromRange = "{$dateComponent[0]}_date_low";
1434 $toRange = "{$dateComponent[0]}_date_high";
1437 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1438 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1443 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals);
1448 $params[] = $values;
1457 * @param int $wildcard
1458 * @param bool $useEquals
1460 * @return array|null
1462 static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE) {
1463 // skip a few search variables
1464 static $skipWhere = NULL;
1465 static $likeNames = NULL;
1468 if (CRM_Utils_System
::isNull($values)) {
1474 'task', 'radio_ts', 'uf_group_id',
1475 'component_mode', 'qfKey', 'operator',
1476 'display_relationship_type',
1480 if (in_array($id, $skipWhere) ||
1481 substr($id, 0, 4) == '_qf_' ||
1482 substr($id, 0, 7) == 'hidden_'
1488 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1491 // email comes in via advanced search
1492 // so use wildcard always
1493 if ($id == 'email') {
1497 if (!$useEquals && in_array($id, $likeNames)) {
1498 $result = array($id, 'LIKE', $values, 0, 1);
1500 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1501 $result = array($id, 'LIKE', $values, 0, 0);
1503 elseif ($id == 'group') {
1504 if (is_array($values)) {
1505 foreach ($values as $groupIds => $val) {
1507 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1508 if (strlen($matches[1]) > 0) {
1509 $values[$matches[1]] = 1;
1510 unset($values[$groupIds]);
1516 $groupIds = explode(',', $values);
1518 foreach ($groupIds as $groupId) {
1519 $values[$groupId] = 1;
1523 $result = array($id, 'IN', $values, 0, 0);
1525 elseif ($id == 'contact_tags' ||
$id == 'tag') {
1526 if (!is_array($values)) {
1527 $tagIds = explode(',', $values);
1529 foreach ($tagIds as $tagId) {
1530 $values[$tagId] = 1;
1533 $result = array($id, 'IN', $values, 0, 0);
1536 $result = array($id, '=', $values, 0, $wildcard);
1545 function whereClauseSingle(&$values) {
1546 // do not process custom fields or prefixed contact ids or component params
1547 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1548 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1549 (substr($values[0], 0, 13) == 'contribution_') ||
1550 (substr($values[0], 0, 6) == 'event_') ||
1551 (substr($values[0], 0, 12) == 'participant_') ||
1552 (substr($values[0], 0, 7) == 'member_') ||
1553 (substr($values[0], 0, 6) == 'grant_') ||
1554 (substr($values[0], 0, 7) == 'pledge_') ||
1555 (substr($values[0], 0, 5) == 'case_') ||
1556 (substr($values[0], 0, 10) == 'financial_') ||
1557 (substr($values[0], 0, 11) == 'membership_')
1562 // skip for hook injected fields / params
1563 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1564 if (array_key_exists($values[0], $extFields)) {
1568 switch ($values[0]) {
1569 case 'deleted_contacts':
1570 $this->deletedContacts($values);
1573 case 'contact_type':
1574 $this->contactType($values);
1577 case 'contact_sub_type':
1578 $this->contactSubType($values);
1582 $this->group($values);
1586 // so we resolve this into a list of groups & proceed as if they had been
1588 list($name, $op, $value, $grouping, $wildcard) = $values;
1589 $values[0] = 'group';
1591 $this->_paramLookup
['group'][0][0] ='group';
1592 $this->_paramLookup
['group'][0][1] = 'IN';
1593 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1594 $this->group($values);
1597 // case tag comes from find contacts
1599 $this->tagSearch($values);
1603 case 'contact_tags':
1604 $this->tag($values);
1609 case 'note_subject':
1610 $this->notes($values);
1614 $this->ufUser($values);
1618 case 'display_name':
1619 $this->sortName($values);
1623 $this->email($values);
1626 case 'phone_numeric':
1627 $this->phone_numeric($values);
1630 case 'phone_phone_type_id':
1631 case 'phone_location_type_id':
1632 $this->phone_option_group($values);
1635 case 'street_address':
1636 $this->street_address($values);
1639 case 'street_number':
1640 $this->street_number($values);
1643 case 'sortByCharacter':
1644 $this->sortByCharacter($values);
1647 case 'location_type':
1648 $this->locationType($values);
1652 $this->county($values);
1655 case 'state_province':
1656 $this->stateProvince($values);
1660 $this->country($values, FALSE);
1664 case 'postal_code_low':
1665 case 'postal_code_high':
1666 $this->postalCode($values);
1669 case 'activity_date':
1670 case 'activity_date_low':
1671 case 'activity_date_high':
1672 case 'activity_role':
1673 case 'activity_status':
1674 case 'followup_parent_id':
1676 case 'activity_subject':
1677 case 'test_activities':
1678 case 'activity_type_id':
1679 case 'activity_type':
1680 case 'activity_survey_id':
1681 case 'activity_tags':
1682 case 'activity_taglist':
1683 case 'activity_test':
1684 case 'activity_campaign_id':
1685 case 'activity_engagement_level':
1687 case 'activity_result':
1688 case 'source_contact':
1689 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1692 case 'birth_date_low':
1693 case 'birth_date_high':
1694 case 'deceased_date_low':
1695 case 'deceased_date_high':
1696 $this->demographics($values);
1699 case 'log_date_low':
1700 case 'log_date_high':
1701 $this->modifiedDates($values);
1705 $this->changeLog($values);
1708 case 'do_not_phone':
1709 case 'do_not_email':
1712 case 'do_not_trade':
1714 $this->privacy($values);
1717 case 'privacy_options':
1718 $this->privacyOptions($values);
1721 case 'privacy_operator':
1722 case 'privacy_toggle':
1723 // these are handled by privacy options
1726 case 'preferred_communication_method':
1727 $this->preferredCommunication($values);
1730 case 'relation_type_id':
1731 case 'relation_start_date_high':
1732 case 'relation_start_date_low':
1733 case 'relation_end_date_high':
1734 case 'relation_end_date_low':
1735 case 'relation_target_name':
1736 case 'relation_status':
1737 case 'relation_date_low':
1738 case 'relation_date_high':
1739 $this->relationship($values);
1740 $this->_relationshipValuesAdded
= TRUE;
1743 case 'task_status_id':
1744 $this->task($values);
1748 // since this case is handled with the above
1751 case 'prox_distance':
1752 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1755 case 'prox_street_address':
1757 case 'prox_postal_code':
1758 case 'prox_state_province_id':
1759 case 'prox_country_id':
1760 // handled by the proximity_distance clause
1764 $this->restWhere($values);
1770 * Given a list of conditions in params generate the required
1776 function whereClause() {
1777 $this->_where
[0] = array();
1778 $this->_qill
[0] = array();
1780 $this->includeContactIds();
1781 if (!empty($this->_params
)) {
1782 foreach (array_keys($this->_params
) as $id) {
1783 if (empty($this->_params
[$id][0])) {
1786 // check for both id and contact_id
1787 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
1789 $this->_params
[$id][1] == 'IS NULL' ||
1790 $this->_params
[$id][1] == 'IS NOT NULL'
1792 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]}";
1794 elseif (is_array($this->_params
[$id][2])) {
1795 $idList = implode("','", $this->_params
[$id][2]);
1796 //why on earth do they put ' in the middle & not on the outside? We have to assume it's
1797 //to support 'something' so lets add them conditionally to support the api (which is a tested flow
1798 // so if you are looking to alter this check api test results
1799 if(strpos(trim($idList), "'") > 0) {
1800 $idList = "'" . $idList . "'";
1803 $this->_where
[0][] = "contact_a.id IN ({$idList})";
1806 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]} {$this->_params[$id][2]}";
1810 $this->whereClauseSingle($this->_params
[$id]);
1814 CRM_Core_Component
::alterQuery($this, 'where');
1816 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
1819 if ($this->_customQuery
) {
1820 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1821 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1822 if (!empty($this->_customQuery
->_where
)) {
1823 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
1826 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
1830 $andClauses = array();
1833 if (!empty($this->_where
)) {
1834 foreach ($this->_where
as $grouping => $values) {
1835 if ($grouping > 0 && !empty($values)) {
1836 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1841 if (!empty($this->_where
[0])) {
1842 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
1844 if (!empty($clauses)) {
1845 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1848 if ($validClauses > 1) {
1849 $this->_useDistinct
= TRUE;
1853 return implode(' AND ', $andClauses);
1861 function restWhere(&$values) {
1862 $name = CRM_Utils_Array
::value(0, $values);
1863 $op = CRM_Utils_Array
::value(1, $values);
1864 $value = CRM_Utils_Array
::value(2, $values);
1865 $grouping = CRM_Utils_Array
::value(3, $values);
1866 $wildcard = CRM_Utils_Array
::value(4, $values);
1868 if (isset($grouping) && empty($this->_where
[$grouping])) {
1869 $this->_where
[$grouping] = array();
1872 $multipleFields = array('url');
1874 //check if the location type exits for fields
1876 $locType = explode('-', $name);
1878 if (!in_array($locType[0], $multipleFields)) {
1879 //add phone type if exists
1880 if (isset($locType[2]) && $locType[2]) {
1881 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
1885 $field = CRM_Utils_Array
::value($name, $this->_fields
);
1888 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
1897 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
1898 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1900 if (substr($name, 0, 14) === 'state_province') {
1901 if (isset($locType[1]) && is_numeric($locType[1])) {
1903 $aName = "{$locationType[$locType[1]]}-address";
1904 $where = "`$aName`.state_province_id";
1907 $where = "civicrm_address.state_province_id";
1910 $states = CRM_Core_PseudoConstant
::stateProvince();
1911 if (is_numeric($value)) {
1912 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1913 $value = $states[(int ) $value];
1916 $intVal = CRM_Utils_Array
::key($value, $states);
1917 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1920 $this->_qill
[$grouping][] = ts('State') . " $op '$value'";
1923 $this->_qill
[$grouping][] = ts('State') . " ($lType) $op '$value'";
1926 elseif (!empty($field['pseudoconstant'])) {
1927 $this->optionValueQuery(
1928 $name, $op, $value, $grouping,
1929 CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', $field['name']),
1935 if ($name == 'gender_id') {
1936 self
::$_openedPanes[ts('Demographics')] = TRUE;
1939 elseif (substr($name, 0, 7) === 'country') {
1940 if (isset($locType[1]) && is_numeric($locType[1])) {
1942 $aName = "{$locationType[$locType[1]]}-address";
1943 $where = "`$aName`.country_id";
1946 $where = "civicrm_address.country_id";
1949 $countries = CRM_Core_PseudoConstant
::country();
1950 if (is_numeric($value)) {
1951 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1952 $value = $countries[(int ) $value];
1955 $intVal = CRM_Utils_Array
::key($value, $countries);
1956 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1960 $this->_qill
[$grouping][] = ts('Country') . " $op '$value'";
1963 $this->_qill
[$grouping][] = ts('Country') . " ($lType) $op '$value'";
1966 elseif (substr($name, 0, 6) === 'county') {
1967 if (isset($locType[1]) && is_numeric($locType[1])) {
1969 $aName = "{$locationType[$locType[1]]}-address";
1970 $where = "`$aName`.county_id";
1973 $where = "civicrm_address.county_id";
1976 $counties = CRM_Core_PseudoConstant
::county();
1977 if (is_numeric($value)) {
1978 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1979 $value = $counties[(int ) $value];
1982 $intVal = CRM_Utils_Array
::key($value, $counties);
1983 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1987 $this->_qill
[$grouping][] = ts('County') . " $op '$value'";
1990 $this->_qill
[$grouping][] = ts('County') . " ($lType) $op '$value'";
1993 elseif ($name === 'world_region') {
1994 $field['where'] = 'civicrm_worldregion.id';
1995 $this->optionValueQuery(
1996 $name, $op, $value, $grouping,
1997 CRM_Core_PseudoConstant
::worldRegion(),
2002 elseif ($name === 'birth_date') {
2003 $date = CRM_Utils_Date
::processDate($value);
2004 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
2007 $date = CRM_Utils_Date
::customFormat($date);
2008 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
2011 $this->_qill
[$grouping][] = "$field[title] $op";
2013 self
::$_openedPanes[ts('Demographics')] = TRUE;
2015 elseif ($name === 'deceased_date') {
2016 $date = CRM_Utils_Date
::processDate($value);
2017 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
2019 $date = CRM_Utils_Date
::customFormat($date);
2020 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
2023 $this->_qill
[$grouping][] = "$field[title] $op";
2025 self
::$_openedPanes[ts('Demographics')] = TRUE;
2027 elseif ($name === 'is_deceased') {
2028 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
2029 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2030 self
::$_openedPanes[ts('Demographics')] = TRUE;
2032 elseif ($name === 'contact_id') {
2033 if (is_int($value)) {
2034 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2035 $this->_qill
[$grouping][] = "$field[title] $op $value";
2038 elseif ($name === 'name') {
2039 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2041 $value = "%$value%";
2044 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2045 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2046 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2048 elseif ($name === 'current_employer') {
2049 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2051 $value = "%$value%";
2054 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
2055 $ceWhereClause = self
::buildClause($wc, $op,
2058 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2059 $this->_where
[$grouping][] = $ceWhereClause;
2060 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2062 elseif ($name === 'email_greeting') {
2063 $filterCondition = array('greeting_type' => 'email_greeting');
2064 $this->optionValueQuery(
2065 $name, $op, $value, $grouping,
2066 CRM_Core_PseudoConstant
::greeting($filterCondition),
2068 ts('Email Greeting')
2071 elseif ($name === 'postal_greeting') {
2072 $filterCondition = array('greeting_type' => 'postal_greeting');
2073 $this->optionValueQuery(
2074 $name, $op, $value, $grouping,
2075 CRM_Core_PseudoConstant
::greeting($filterCondition),
2077 ts('Postal Greeting')
2080 elseif ($name === 'addressee') {
2081 $filterCondition = array('greeting_type' => 'addressee');
2082 $this->optionValueQuery(
2083 $name, $op, $value, $grouping,
2084 CRM_Core_PseudoConstant
::greeting($filterCondition),
2089 elseif (substr($name, 0, 4) === 'url-') {
2090 $tName = 'civicrm_website';
2091 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2092 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2094 $value = "%$value%";
2098 $wc = 'civicrm_website.url';
2099 $this->_where
[$grouping][] = $d = self
::buildClause($wc, $op, $value);
2100 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2102 elseif ($name === 'contact_is_deleted') {
2103 $this->_where
[$grouping][] = self
::buildClause("contact_a.is_deleted", $op, $value);
2104 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2107 if (is_array($value)) {
2108 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2109 // for api style operators for functions that hit this point without worrying about regression
2110 // (the previous comments indicated the condition for hitting this point were unknown
2111 // per CRM-14743 we are adding modified_date & created_date operator support
2112 $operations = array_keys($value);
2113 foreach ($operations as $operator) {
2114 if(!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2115 // we don't know when this might happen
2116 CRM_Core_Error
::fatal();
2119 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($name, $value, NULL);
2120 //since this is not currently being called by the form layer we can skip worrying about the 'qill' for now
2124 if (!empty($field['where'])) {
2126 $value = $strtolower($value);
2129 $value = "%$value%";
2133 if (isset($locType[1]) &&
2134 is_numeric($locType[1])
2138 //get the location name
2139 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2141 $where = "`$tName`.$fldName";
2143 $this->_where
[$grouping][] = self
::buildClause("LOWER($where)", $op, $value);
2144 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2145 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2146 $this->_qill
[$grouping][] = "$field[title] $op '$value'";
2149 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2150 if ($tableName == 'civicrm_contact') {
2151 $fieldName = "LOWER(contact_a.{$fieldName})";
2154 if ($op != 'IN' && !is_numeric($value)) {
2155 $fieldName = "LOWER({$field['where']})";
2158 $fieldName = "{$field['where']}";
2163 if (!empty($field['type'])) {
2164 $type = CRM_Utils_Type
::typeToString($field['type']);
2167 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2168 $this->_qill
[$grouping][] = "$field[title] $op $value";
2173 if ($setTables && isset($field['where'])) {
2174 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2175 if (isset($tableName)) {
2176 $this->_tables
[$tableName] = 1;
2177 $this->_whereTables
[$tableName] = 1;
2190 static function getLocationTableName(&$where, &$locType) {
2191 if (isset($locType[1]) && is_numeric($locType[1])) {
2192 list($tbName, $fldName) = explode(".", $where);
2194 //get the location name
2195 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2196 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2197 if (in_array($locType[0], $specialFields)) {
2198 //hack to fix / special handing for phone_ext
2199 if ($locType[0] == 'phone_ext') {
2200 $locType[0] = 'phone';
2202 if (isset($locType[2]) && $locType[2]) {
2203 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2206 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2209 elseif (in_array($locType[0],
2211 'address_name', 'street_address', 'supplemental_address_1', 'supplemental_address_2',
2212 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
2215 //fix for search by profile with address fields.
2216 $tName = "{$locationType[$locType[1]]}_address";
2218 elseif ($locType[0] == 'on_hold') {
2219 $tName = "{$locationType[$locType[1]]}-email";
2222 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2224 $tName = str_replace(' ', '_', $tName);
2225 return array($tName, $fldName);
2227 CRM_Core_Error
::fatal();
2231 * Given a result dao, extract the values and return that array
2233 * @param Object $dao
2235 * @return array values for this query
2237 function store($dao) {
2240 foreach ($this->_element
as $key => $dontCare) {
2241 if (property_exists($dao, $key)) {
2242 if (strpos($key, '-') !== FALSE) {
2243 $values = explode('-', $key);
2244 $lastElement = array_pop($values);
2246 $cnt = count($values);
2248 foreach ($values as $v) {
2249 if (!array_key_exists($v, $current)) {
2250 $current[$v] = array();
2252 //bad hack for im_provider
2253 if ($lastElement == 'provider_id') {
2254 if ($count < $cnt) {
2255 $current = &$current[$v];
2258 $lastElement = "{$v}_{$lastElement}";
2262 $current = &$current[$v];
2267 $current[$lastElement] = $dao->$key;
2270 $value[$key] = $dao->$key;
2278 * getter for tables array
2284 return $this->_tables
;
2288 * Where tables is sometimes used to create the from clause, but, not reliably, set this AND set tables
2289 * It's unclear the intent - there is a 'simpleFrom' clause which takes whereTables into account & a fromClause which doesn't
2290 * logic may have eroded
2293 function whereTables() {
2294 return $this->_whereTables
;
2298 * generate the where clause (used in match contacts and permissions)
2300 * @param array $params
2301 * @param array $fields
2302 * @param array $tables
2303 * @param $whereTables
2304 * @param boolean $strict
2310 static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2311 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2315 $tables = array_merge($query->tables(), $tables);
2316 $whereTables = array_merge($query->whereTables(), $whereTables);
2318 return $query->_whereClause
;
2322 * create the from clause
2324 * @param array $tables tables that need to be included in this from clause
2325 * if null, return mimimal from clause (i.e. civicrm_contact)
2326 * @param array $inner tables that should be inner-joined
2327 * @param array $right tables that should be right-joined
2329 * @param bool $primaryLocation
2332 * @return string the from clause
2336 static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2338 $from = ' FROM civicrm_contact contact_a';
2339 if (empty($tables)) {
2343 if (!empty($tables['civicrm_worldregion'])) {
2344 $tables = array_merge(array('civicrm_country' => 1), $tables);
2347 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2348 CRM_Utils_Array
::value('civicrm_county', $tables)
2349 ) && empty($tables['civicrm_address'])) {
2350 $tables = array_merge(array('civicrm_address' => 1),
2355 // add group_contact table if group table is present
2356 if (!empty($tables['civicrm_group']) && empty($tables['civicrm_group_contact'])) {
2357 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
2360 // add group_contact and group table is subscription history is present
2361 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2362 $tables = array_merge(array(
2363 'civicrm_group' => 1,
2364 'civicrm_group_contact' => 1,
2370 // to handle table dependencies of components
2371 CRM_Core_Component
::tableNames($tables);
2372 // to handle table dependencies of hook injected tables
2373 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2375 //format the table list according to the weight
2376 $info = CRM_Core_TableHierarchy
::info();
2378 foreach ($tables as $key => $value) {
2380 if (strpos($key, '-') !== FALSE) {
2381 $keyArray = explode('-', $key);
2382 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2384 elseif (strpos($key, '_') !== FALSE) {
2385 $keyArray = explode('_', $key);
2386 if (is_numeric(array_pop($keyArray))) {
2387 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2390 $k = CRM_Utils_Array
::value($key, $info, 99);
2394 $k = CRM_Utils_Array
::value($key, $info, 99);
2396 $tempTable[$k . ".$key"] = $key;
2399 $newTables = array();
2400 foreach ($tempTable as $key) {
2401 $newTables[$key] = $tables[$key];
2404 $tables = $newTables;
2406 foreach ($tables as $name => $value) {
2411 if (!empty($inner[$name])) {
2414 elseif (!empty($right[$name])) {
2422 // if there is already a join statement in value, use value itself
2423 if (strpos($value, 'JOIN')) {
2424 $from .= " $value ";
2427 $from .= " $side JOIN $name ON ( $value ) ";
2432 case 'civicrm_address':
2433 if ($primaryLocation) {
2434 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2437 //CRM-14263 further handling of address joins further down...
2438 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2442 case 'civicrm_phone':
2443 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2446 case 'civicrm_email':
2447 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2451 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2455 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2456 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2457 $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)";
2460 case 'civicrm_openid':
2461 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2464 case 'civicrm_worldregion':
2465 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2466 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2469 case 'civicrm_location_type':
2470 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2473 case 'civicrm_group':
2474 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2477 case 'civicrm_group_contact':
2478 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2481 case 'civicrm_activity':
2482 case 'civicrm_activity_tag':
2483 case 'activity_type':
2484 case 'activity_status':
2486 case 'civicrm_activity_contact':
2487 case 'source_contact':
2488 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2491 case 'civicrm_entity_tag':
2492 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2493 civicrm_entity_tag.entity_id = contact_a.id ) ";
2496 case 'civicrm_note':
2497 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2498 contact_a.id = civicrm_note.entity_id ) ";
2501 case 'civicrm_subscription_history':
2502 $from .= " $side JOIN civicrm_subscription_history
2503 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2504 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2507 case 'civicrm_relationship':
2508 if (self
::$_relType == 'reciprocal') {
2509 if(self
::$_relationshipTempTable) {
2510 // we have a temptable to join on
2511 $tbl = self
::$_relationshipTempTable;
2512 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2515 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2516 $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)";
2519 elseif (self
::$_relType == 'b') {
2520 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2521 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2524 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2525 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2530 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2531 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2535 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2538 case 'civicrm_grant':
2539 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2542 case 'civicrm_website':
2543 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2547 if (strpos($name, '_address') != 0) {
2548 //we have a join on an address table - possibly in conjunction with search builder - CRM-14263
2549 $parts = explode('_', $name);
2550 $locationID = array_search($parts[0], CRM_Core_BAO_Address
::buildOptions('location_type_id', 'get', array('name' => $parts[0])));
2551 $from .= " $side JOIN civicrm_address $name ON ( contact_a.id = {$name}.contact_id ) and location_type_id = $locationID ";
2554 $from .= CRM_Core_Component
::from($name, $mode, $side);
2556 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2565 * WHERE / QILL clause for deleted_contacts
2571 function deletedContacts($values) {
2572 list($_, $_, $value, $grouping, $_) = $values;
2574 // *prepend* to the relevant grouping as this is quite an important factor
2575 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2580 * where / qill clause for contact_type
2587 function contactType(&$values) {
2588 list($name, $op, $value, $grouping, $wildcard) = $values;
2590 $subTypes = array();
2593 // account for search builder mapping multiple values
2594 if (!is_array($value)) {
2595 $values = self
::parseSearchBuilderString($value, 'String');
2596 if (is_array($values)) {
2597 $value = array_flip($values);
2601 if (is_array($value)) {
2602 foreach ($value as $k => $v) {
2607 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2608 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2611 if (!empty($subType)) {
2612 $subTypes[$subType] = 1;
2614 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2619 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2620 $contactType = $contactTypeANDSubType[0];
2621 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2622 if (!empty($subType)) {
2623 $subTypes[$subType] = 1;
2625 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2629 if (!empty($clause)) {
2630 if ($op == 'IN' ||
$op == 'NOT IN') {
2631 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2635 $type = array_pop($clause);
2636 $this->_where
[$grouping][] = "contact_a.contact_type $op $type";
2639 $this->_qill
[$grouping][] = ts('Contact Type') . ' - ' . implode(' ' . ts('or') . ' ', $quill);
2641 if (!empty($subTypes)) {
2642 $this->includeContactSubTypes($subTypes, $grouping);
2648 * where / qill clause for contact_sub_type
2655 function contactSubType(&$values) {
2656 list($name, $op, $value, $grouping, $wildcard) = $values;
2657 $this->includeContactSubTypes($value, $grouping);
2664 function includeContactSubTypes($value, $grouping) {
2667 $alias = "contact_a.contact_sub_type";
2669 if (is_array($value)) {
2670 foreach ($value as $k => $v) {
2672 $clause[$k] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($k, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2677 $clause[$value] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2680 if (!empty($clause)) {
2681 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2682 $this->_qill
[$grouping][] = ts('Contact Subtype') . ' - ' . implode(' ' . ts('or') . ' ', array_keys($clause));
2687 * where / qill clause for groups
2694 function group(&$values) {
2695 list($name, $op, $value, $grouping, $wildcard) = $values;
2697 if (count($value) > 1) {
2698 $this->_useDistinct
= TRUE;
2701 $groupNames = CRM_Core_PseudoConstant
::group();
2702 $groupIds = implode(',', array_keys($value));
2705 foreach ($value as $id => $dontCare) {
2706 if (array_key_exists($id, $groupNames) && $dontCare) {
2707 $names[] = $groupNames[$id];
2713 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2715 is_array($gcsValues[2])
2717 foreach ($gcsValues[2] as $k => $v) {
2719 if ($k == 'Added') {
2722 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2727 $statii[] = '"Added"';
2732 if (count($value) == 1 &&
2733 count($statii) == 1 &&
2734 $statii[0] == '"Added"'
2736 // check if smart group, if so we can get rid of that one additional
2738 $groupIDs = array_keys($value);
2740 if (!empty($groupIDs[0]) &&
2741 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
2751 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2752 $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 ) )";
2755 $qill = ts('Contacts %1', array(1 => $op));
2756 $qill .= ' ' . implode(' ' . ts('or') . ' ', $names);
2758 $groupClause = NULL;
2761 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2762 if (!empty($statii)) {
2763 $groupClause .= " AND {$gcTable}.status IN (" . implode(', ', $statii) . ")";
2764 $qill .= " " . ts('AND') . " " . ts('Group Status') . ' - ' . implode(' ' . ts('or') . ' ', $statii);
2769 $ssClause = $this->savedSearch($values);
2772 $groupClause = "( ( $groupClause ) OR ( $ssClause ) )";
2775 $groupClause = $ssClause;
2780 $this->_where
[$grouping][] = $groupClause;
2781 $this->_qill
[$grouping][] = $qill;
2784 * Function translates selection of group type into a list of groups
2791 function getGroupsFromTypeCriteria($value){
2792 $groupIds = array();
2793 foreach ($value as $groupTypeValue) {
2794 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2795 $groupIds = ($groupIds +
$groupList);
2801 * where / qill clause for smart groups
2805 * @return string|NULL
2808 function savedSearch(&$values) {
2809 list($name, $op, $value, $grouping, $wildcard) = $values;
2810 return $this->addGroupContactCache(array_keys($value));
2814 * @param array $groups
2815 * @param string $tableAlias
2816 * @param string $joinTable
2818 * @return null|string
2820 function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
2821 $config = CRM_Core_Config
::singleton();
2823 // Find all the groups that are part of a saved search.
2824 $groupIDs = implode(',', $groups);
2825 if (empty($groupIDs)) {
2830 SELECT id, cache_date, saved_search_id, children
2832 WHERE id IN ( $groupIDs )
2833 AND ( saved_search_id != 0
2834 OR saved_search_id IS NOT NULL
2835 OR children IS NOT NULL )
2838 $group = CRM_Core_DAO
::executeQuery($sql);
2839 $groupsFiltered = array();
2841 while ($group->fetch()) {
2842 $groupsFiltered[] = $group->id
;
2844 $this->_useDistinct
= TRUE;
2846 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
2847 CRM_Contact_BAO_GroupContactCache
::load($group);
2851 if (count($groupsFiltered)) {
2852 $groupIDsFiltered = implode(',', $groupsFiltered);
2854 if ($tableAlias == NULL) {
2855 $tableAlias = "civicrm_group_contact_cache_{$groupIDsFiltered}";
2858 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache `{$tableAlias}` ON {$joinTable}.id = `{$tableAlias}`.contact_id ";
2860 return "`{$tableAlias}`.group_id IN (" . $groupIDsFiltered . ")";
2867 * where / qill clause for cms users
2874 function ufUser(&$values) {
2875 list($name, $op, $value, $grouping, $wildcard) = $values;
2878 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2880 $this->_qill
[$grouping][] = ts('CMS User');
2882 elseif ($value == 0) {
2883 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2885 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2886 $this->_qill
[$grouping][] = ts('Not a CMS User');
2891 * all tag search specific
2898 function tagSearch(&$values) {
2899 list($name, $op, $value, $grouping, $wildcard) = $values;
2902 $value = "%{$value}%";
2905 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2906 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2908 $etTable = "`civicrm_entity_tag-" . $value . "`";
2909 $tTable = "`civicrm_tag-" . $value . "`";
2911 if ($useAllTagTypes[2]) {
2912 $this->_tables
[$etTable] =
2913 $this->_whereTables
[$etTable] =
2914 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
2915 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
2917 // search tag in cases
2918 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2919 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
2920 $this->_tables
[$etCaseTable] =
2921 $this->_whereTables
[$etCaseTable] =
2922 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2923 LEFT JOIN civicrm_case
2924 ON (civicrm_case_contact.case_id = civicrm_case.id
2925 AND civicrm_case.is_deleted = 0 )
2926 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
2927 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
2928 // search tag in activities
2929 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2930 $tActTable = "`civicrm_act_tag-" . $value . "`";
2931 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2932 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2934 $this->_tables
[$etActTable] =
2935 $this->_whereTables
[$etActTable] =
2936 " LEFT JOIN civicrm_activity_contact
2937 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
2938 LEFT JOIN civicrm_activity
2939 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
2940 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2941 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
2942 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
2944 $this->_where
[$grouping][] = "({$tTable}.name $op '". $value . "' OR {$tCaseTable}.name $op '". $value . "' OR {$tActTable}.name $op '". $value . "')";
2945 $this->_qill
[$grouping][] = ts('Tag %1 %2 ', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
2947 $etTable = "`civicrm_entity_tag-" . $value . "`";
2948 $tTable = "`civicrm_tag-" . $value . "`";
2949 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
2950 {$etTable}.entity_table = 'civicrm_contact' )
2951 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
2953 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
2954 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
2959 * where / qill clause for tag
2966 function tag(&$values) {
2967 list($name, $op, $value, $grouping, $wildcard) = $values;
2969 $tagNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
2970 if (is_array($value)) {
2971 if (count($value) > 1) {
2972 $this->_useDistinct
= TRUE;
2974 foreach ($value as $id => $dontCare) {
2975 $names[] = CRM_Utils_Array
::value($id, $tagNames);
2977 $names = implode(' ' . ts('or') . ' ', $names);
2978 $value = implode(',', array_keys($value));
2981 $names = CRM_Utils_Array
::value($value, $tagNames);
2985 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2986 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2988 $etTable = "`civicrm_entity_tag-" . $value . "`";
2990 if ($useAllTagTypes[2]) {
2991 $this->_tables
[$etTable] =
2992 $this->_whereTables
[$etTable] =
2993 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2995 // search tag in cases
2996 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2997 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2998 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3000 $this->_tables
[$etCaseTable] =
3001 $this->_whereTables
[$etCaseTable] =
3002 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3003 LEFT JOIN civicrm_case
3004 ON (civicrm_case_contact.case_id = civicrm_case.id
3005 AND civicrm_case.is_deleted = 0 )
3006 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3007 // search tag in activities
3008 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3009 $this->_tables
[$etActTable] =
3010 $this->_whereTables
[$etActTable] =
3011 " LEFT JOIN civicrm_activity_contact
3012 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3013 LEFT JOIN civicrm_activity
3014 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3015 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3016 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3019 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3020 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3023 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (". $value . ") OR {$etCaseTable}.tag_id $op (". $value . ") OR {$etActTable}.tag_id $op (". $value . "))";
3025 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
3027 $this->_tables
[$etTable] =
3028 $this->_whereTables
[$etTable] =
3029 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3032 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3033 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3034 $op = str_replace('EMPTY', 'NULL', $op);
3035 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3038 $this->_where
[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
3040 $this->_qill
[$grouping][] = ts('Tagged %1', array( 1 => $op)) . ' ' . $names;
3046 * where/qill clause for notes
3053 function notes(&$values) {
3054 list($name, $op, $value, $grouping, $wildcard) = $values;
3056 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3057 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3058 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3060 $this->_useDistinct
= TRUE;
3062 $this->_tables
['civicrm_note'] =
3063 $this->_whereTables
['civicrm_note'] =
3064 " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3066 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3068 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3069 if ($wildcard ||
$op == 'LIKE') {
3070 if (strpos($value, '%') === FALSE) {
3071 $value = "%$value%";
3075 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3081 if ( $noteOption %
2 == 0 ) {
3082 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3083 $label = ts('Note: Body Only');
3085 if ( $noteOption %
3 == 0 ) {
3086 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3087 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3089 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3090 $this->_qill
[$grouping][] = $label . " $op - '$n'";
3100 function nameNullOrEmptyOp($name, $op, $grouping) {
3104 $this->_where
[$grouping][] = "contact_a.$name $op";
3105 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3109 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3110 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3113 case 'IS NOT EMPTY':
3114 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3115 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3124 * where / qill clause for sort_name
3131 function sortName(&$values) {
3132 list($name, $op, $value, $grouping, $wildcard) = $values;
3134 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3135 if ( $this->nameNullOrEmptyOp( $name, $op, $grouping ) ) {
3140 $name = trim($value);
3146 $config = CRM_Core_Config
::singleton();
3150 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3153 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3154 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3156 if (substr($name, 0, 1) == '"' &&
3157 substr($name, -1, 1) == '"'
3159 //If name is encased in double quotes, the value should be taken to be the string in entirety and the
3160 $value = substr($name, 1, -1);
3161 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
3162 $wc = ($newName == 'sort_name') ?
'LOWER(contact_a.sort_name)' : 'LOWER(contact_a.display_name)';
3163 $sub[] = " ( $wc = '$value' ) ";
3164 if ($config->includeEmailInName
) {
3165 $sub[] = " ( civicrm_email.email = '$value' ) ";
3168 elseif (strpos($name, ',') !== FALSE) {
3169 // if we have a comma in the string, search for the entire string
3170 $value = $strtolower(CRM_Core_DAO
::escapeString($name));
3172 if ($config->includeWildCardInName
) {
3173 $value = "'%$value%'";
3176 $value = "'$value%'";
3181 $value = "'$value'";
3183 if ($newName == 'sort_name') {
3184 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3187 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3189 $sub[] = " ( $wc $op $value )";
3190 if ($config->includeNickNameInName
) {
3191 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3192 $sub[] = " ( $wc $op $value )";
3194 if ($config->includeEmailInName
) {
3195 $sub[] = " ( civicrm_email.email $op $value ) ";
3199 // the string should be treated as a series of keywords to be matched with match ANY OR
3200 // match ALL depending on Civi config settings (see CiviAdmin)
3202 // The Civi configuration setting can be overridden if the string *starts* with the case
3203 // insenstive strings 'AND:' or 'OR:'TO THINK ABOUT: what happens when someone searches
3204 // for the following "AND: 'a string in quotes'"? - probably nothing - it would make the
3205 // AND OR variable reduntant because there is only one search string?
3207 // Check to see if the $subGlue is overridden in the search text
3208 if (strtolower(substr($name, 0, 4)) == 'and:') {
3209 $name = substr($name, 4);
3212 if (strtolower(substr($name, 0, 3)) == 'or:') {
3213 $name = substr($name, 3);
3217 $firstChar = substr($name, 0, 1);
3218 $lastChar = substr($name, -1, 1);
3219 $quotes = array("'", '"');
3220 if ((strlen($name) > 2) && in_array($firstChar, $quotes) &&
3221 in_array($lastChar, $quotes)
3223 $name = substr($name, 1);
3224 $name = substr($name, 0, -1);
3225 $pieces = array($name);
3228 $pieces = explode(' ', $name);
3230 foreach ($pieces as $piece) {
3231 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($piece)));
3232 if (strlen($value)) {
3233 // Added If as a sanitization - without it, when you do an OR search, any string with
3234 // double spaces (i.e. " ") or that has a space after the keyword (e.g. "OR: ") will
3235 // return all contacts because it will include a condition similar to "OR contact
3236 // name LIKE '%'". It might be better to replace this with array_filter.
3237 $fieldsub = array();
3239 if ($config->includeWildCardInName
) {
3240 $value = "'%$value%'";
3243 $value = "'$value%'";
3248 $value = "'$value'";
3250 if ($newName == 'sort_name') {
3251 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3254 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3256 $fieldsub[] = " ( $wc $op $value )";
3257 if ($config->includeNickNameInName
) {
3258 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3259 $fieldsub[] = " ( $wc $op $value )";
3261 if ($config->includeEmailInName
) {
3262 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3264 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3265 // I seperated the glueing in two. The first stage should always be OR because we are searching for matches in *ANY* of these fields
3270 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3272 $this->_where
[$grouping][] = $sub;
3273 if ($config->includeEmailInName
) {
3274 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3275 $this->_qill
[$grouping][] = ts('Name or Email ') . "$op - '$name'";
3278 $this->_qill
[$grouping][] = ts('Name like') . " - '$name'";
3283 * where / qill clause for email
3290 function email(&$values) {
3291 list($name, $op, $value, $grouping, $wildcard) = $values;
3295 $config = CRM_Core_Config
::singleton();
3297 if (substr($n, 0, 1) == '"' &&
3298 substr($n, -1, 1) == '"'
3300 $n = substr($n, 1, -1);
3301 $value = strtolower(CRM_Core_DAO
::escapeString($n));
3302 $value = "'$value'";
3306 $value = strtolower($n);
3308 if (strpos($value, '%') === FALSE) {
3309 $value = "%{$value}%";
3314 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3315 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3318 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3319 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3322 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3326 * where / qill clause for phone number
3333 function phone_numeric(&$values) {
3334 list($name, $op, $value, $grouping, $wildcard) = $values;
3335 // Strip non-numeric characters; allow wildcards
3336 $number = preg_replace('/[^\d%]/', '', $value);
3338 if ( strpos($number, '%') === FALSE ) {
3339 $number = "%$number%";
3342 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3343 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3344 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3349 * where / qill clause for phone type/location
3356 function phone_option_group($values) {
3357 list($name, $op, $value, $grouping, $wildcard) = $values;
3358 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3359 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3360 $optionName = $options[$value];
3361 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3362 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3363 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3367 * where / qill clause for street_address
3374 function street_address(&$values) {
3375 list($name, $op, $value, $grouping, $wildcard) = $values;
3384 $value = strtolower($n);
3385 if (strpos($value, '%') === FALSE) {
3386 // only add wild card if not there
3387 $value = "%{$value}%";
3390 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3391 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3394 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3395 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3398 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3402 * where / qill clause for street_unit
3409 function street_number(&$values) {
3410 list($name, $op, $value, $grouping, $wildcard) = $values;
3418 if (strtolower($n) == 'odd') {
3419 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3420 $this->_qill
[$grouping][] = ts('Street Number is odd');
3422 elseif (strtolower($n) == 'even') {
3423 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3424 $this->_qill
[$grouping][] = ts('Street Number is even');
3427 $value = strtolower($n);
3429 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3430 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3433 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3437 * where / qill clause for sorting by character
3444 function sortByCharacter(&$values) {
3445 list($name, $op, $value, $grouping, $wildcard) = $values;
3447 $name = trim($value);
3448 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3449 $this->_where
[$grouping][] = $cond;
3450 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3454 * where / qill clause for including contact ids
3459 function includeContactIDs() {
3460 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3464 $contactIds = array();
3465 foreach ($this->_params
as $id => $values) {
3466 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3467 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3470 if (!empty($contactIds)) {
3471 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3476 * where / qill clause for postal code
3483 function postalCode(&$values) {
3484 // skip if the fields dont have anything to do with postal_code
3485 if (empty($this->_fields
['postal_code'])) {
3489 list($name, $op, $value, $grouping, $wildcard) = $values;
3491 // Handle numeric postal code range searches properly by casting the column as numeric
3492 if (is_numeric($value)) {
3493 $field = 'ROUND(civicrm_address.postal_code)';
3494 $val = CRM_Utils_Type
::escape($value, 'Integer');
3497 $field = 'civicrm_address.postal_code';
3498 $val = CRM_Utils_Type
::escape($value, 'String');
3501 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3503 if ($name == 'postal_code') {
3504 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3505 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3507 elseif ($name == 'postal_code_low') {
3508 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3509 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3511 elseif ($name == 'postal_code_high') {
3512 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3513 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3518 * where / qill clause for location type
3521 * @param null $status
3526 function locationType(&$values, $status = NULL) {
3527 list($name, $op, $value, $grouping, $wildcard) = $values;
3529 if (is_array($value)) {
3530 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', array_keys($value)) . ')';
3531 $this->_tables
['civicrm_address'] = 1;
3532 $this->_whereTables
['civicrm_address'] = 1;
3534 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3536 foreach (array_keys($value) as $id) {
3537 $names[] = $locationType[$id];
3540 $this->_primaryLocation
= FALSE;
3543 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3546 return implode(' ' . ts('or') . ' ', $names);
3553 * @param bool $fromStateProvince
3557 function country(&$values, $fromStateProvince = TRUE) {
3558 list($name, $op, $value, $grouping, $wildcard) = $values;
3560 if (!$fromStateProvince) {
3561 $stateValues = $this->getWhereValues('state_province', $grouping);
3562 if (!empty($stateValues)) {
3563 // return back to caller if there are state province values
3564 // since that handles this case
3569 $countryClause = $countryQill = NULL;
3575 $this->_tables
['civicrm_address'] = 1;
3576 $this->_whereTables
['civicrm_address'] = 1;
3578 $countries = CRM_Core_PseudoConstant
::country();
3579 if (is_numeric($value)) {
3580 $countryClause = self
::buildClause(
3581 'civicrm_address.country_id',
3586 $countryName = $countries[(int ) $value];
3590 $intValues = self
::parseSearchBuilderString($value);
3591 if ($intValues && ($op == 'IN' ||
$op == 'NOT IN')) {
3592 $countryClause = self
::buildClause(
3593 'civicrm_address.country_id',
3598 $countryNames = array();
3599 foreach ($intValues as $v) {
3600 $countryNames[] = $countries[$v];
3602 $countryName = implode(',', $countryNames);
3605 $countries = CRM_Core_PseudoConstant
::country();
3606 $intVal = CRM_Utils_Array
::key($value, $countries);
3607 $countryClause = self
::buildClause(
3608 'civicrm_address.country_id',
3613 $countryName = $value;
3616 $countryQill = ts('Country') . " {$op} '$countryName'";
3618 if (!$fromStateProvince) {
3619 $this->_where
[$grouping][] = $countryClause;
3620 $this->_qill
[$grouping][] = $countryQill;
3624 if ($fromStateProvince) {
3625 if (!empty($countryClause)) {
3628 " ...AND... " . $countryQill,
3632 return array(NULL, NULL);
3638 * where / qill clause for county (if present)
3641 * @param null $status
3646 function county(&$values, $status = null) {
3647 list($name, $op, $value, $grouping, $wildcard) = $values;
3649 if (! is_array($value)) {
3650 // force the county to be an array
3651 $value = array($value);
3654 // check if the values are ids OR names of the counties
3655 $inputFormat = 'id';
3656 foreach ($value as $v) {
3657 if (!is_numeric($v)) {
3658 $inputFormat = 'name';
3666 else if ($op == '!=') {
3670 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3671 $op = str_replace('EMPTY', 'NULL', $op);
3674 if (in_array( $op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3675 $clause = "civicrm_address.county_id $op";
3677 elseif ($inputFormat == 'id') {
3678 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3680 $county = CRM_Core_PseudoConstant
::county();
3681 foreach ($value as $id) {
3682 $names[] = CRM_Utils_Array
::value($id, $county);
3686 $inputClause = array();
3687 $county = CRM_Core_PseudoConstant
::county();
3688 foreach ($value as $name) {
3689 $name = trim($name);
3690 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3692 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3695 $this->_tables
['civicrm_address'] = 1;
3696 $this->_whereTables
['civicrm_address'] = 1;
3698 $this->_where
[$grouping][] = $clause;
3700 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3702 return implode(' ' . ts('or') . ' ', $names);
3707 * where / qill clause for state/province AND country (if present)
3710 * @param null $status
3715 function stateProvince(&$values, $status = NULL) {
3716 list($name, $op, $value, $grouping, $wildcard) = $values;
3718 // quick escape for IS NULL
3719 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3722 else if (!is_array($value)) {
3723 // force the state to be an array
3724 // check if its in the mapper format!
3725 $values = self
::parseSearchBuilderString($value);
3726 if (is_array($values)) {
3730 $value = array($value);
3734 // check if the values are ids OR names of the states
3735 $inputFormat = 'id';
3737 foreach ($value as $v) {
3738 if (!is_numeric($v)) {
3739 $inputFormat = 'name';
3749 else if ($op == '!=') {
3753 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3754 $op = str_replace('EMPTY', 'NULL', $op);
3756 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3757 $stateClause = "civicrm_address.state_province_id $op";
3759 else if ($inputFormat == 'id') {
3760 if ($op != 'NOT IN') {
3763 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
3765 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3766 foreach ($value as $id) {
3767 $names[] = CRM_Utils_Array
::value($id, $stateProvince);
3771 $inputClause = array();
3772 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3773 foreach ($value as $name) {
3774 $name = trim($name);
3775 $inputClause[] = CRM_Utils_Array
::key($name, $stateProvince);
3777 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
3780 $this->_tables
['civicrm_address'] = 1;
3781 $this->_whereTables
['civicrm_address'] = 1;
3783 $countryValues = $this->getWhereValues('country', $grouping);
3784 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3786 if ($countryClause) {
3787 $clause = "( $stateClause AND $countryClause )";
3790 $clause = $stateClause;
3793 $this->_where
[$grouping][] = $clause;
3795 $this->_qill
[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3798 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
3803 * where / qill clause for change log
3810 function changeLog(&$values) {
3811 list($name, $op, $value, $grouping, $wildcard) = $values;
3813 $targetName = $this->getWhereValues('changed_by', $grouping);
3818 $name = trim($targetName[2]);
3819 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3820 $name = $targetName[4] ?
"%$name%" : $name;
3821 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3822 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3823 $this->_qill
[$grouping][] = ts('Modified by') . ": $name";
3829 function modifiedDates($values) {
3830 $this->_useDistinct
= TRUE;
3832 // CRM-11281, default to added date if not set
3833 $fieldTitle = ts('Added Date');
3834 $fieldName = 'created_date';
3835 foreach (array_keys($this->_params
) as $id) {
3836 if ($this->_params
[$id][0] == 'log_date') {
3837 if ($this->_params
[$id][2] == 2) {
3838 $fieldTitle = ts('Modified Date');
3839 $fieldName = 'modified_date';
3845 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3847 self
::$_openedPanes[ts('Change Log')] = TRUE;
3853 function demographics(&$values) {
3854 list($name, $op, $value, $grouping, $wildcard) = $values;
3856 if (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3858 $this->dateQueryBuilder($values,
3859 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3862 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3864 $this->dateQueryBuilder($values,
3865 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3869 self
::$_openedPanes[ts('Demographics')] = TRUE;
3875 function privacy(&$values) {
3876 list($name, $op, $value, $grouping, $wildcard) = $values;
3877 //fixed for profile search listing CRM-4633
3878 if (strpbrk($value, "[")) {
3879 $value = "'{$value}'";
3881 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3884 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3886 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3887 $title = $field ?
$field['title'] : $name;
3888 $this->_qill
[$grouping][] = "$title $op $value";
3894 function privacyOptions($values) {
3895 list($name, $op, $value, $grouping, $wildcard) = $values;
3897 if (empty($value) ||
!is_array($value)) {
3901 // get the operator and toggle values
3902 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3905 strtolower($opValues[2] == 'AND')
3910 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3912 if ($toggleValues &&
3913 $toggleValues[2] == 2
3920 foreach ($value as $dontCare => $pOption) {
3921 $clauses[] = " ( contact_a.{$pOption} $compareOP 1 ) ";
3922 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3923 $title = $field ?
$field['title'] : $pOption;
3924 $qill[] = " $title $compareOP 1 ";
3927 $this->_where
[$grouping][] = '( ' . implode($operator, $clauses) . ' )';
3928 $this->_qill
[$grouping][] = implode($operator, $qill);
3934 function preferredCommunication(&$values) {
3935 list($name, $op, $value, $grouping, $wildcard) = $values;
3938 if (in_array($op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3941 elseif (!is_array($value)) {
3943 $value = trim($value, ' ()');
3944 if (strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
3945 $v = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
3948 $v = explode(",", $value);
3951 foreach ($v as $item) {
3958 foreach ($value as $key => $checked) {
3965 $commPref = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
3967 $sqlValue = array();
3968 $showValue = array();
3969 $sql = "contact_a.preferred_communication_method";
3970 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3971 $sqlValue[] = "{$sql} {$op}";
3974 foreach ($pref as $val) {
3975 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $val . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' ) ";
3976 $showValue[] = $commPref[$val];
3979 $this->_where
[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
3980 $this->_qill
[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
3984 * where / qill clause for relationship
3991 function relationship(&$values) {
3992 list($name, $op, $value, $grouping, $wildcard) = $values;
3993 if($this->_relationshipValuesAdded
){
3996 // also get values array for relation_target_name
3997 // for relatinship search we always do wildcard
3998 $targetName = $this->getWhereValues('relation_target_name', $grouping);
3999 $relStatus = $this->getWhereValues('relation_status', $grouping);
4000 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4001 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4003 $nameClause = $name = NULL;
4005 $name = trim($targetName[2]);
4006 if (substr($name, 0, 1) == '"' &&
4007 substr($name, -1, 1) == '"'
4009 $name = substr($name, 1, -1);
4010 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4011 $nameClause = "= '$name'";
4014 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4015 $nameClause = "LIKE '%{$name}%'";
4019 $rel = explode('_', $value);
4021 self
::$_relType = $rel[1];
4022 $params = array('id' => $rel[0]);
4023 $rTypeValues = array();
4024 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
4025 if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
4026 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4027 //@todo unless we are dealing with a target group
4028 self
::$_relType = 'reciprocal';
4030 // if we are creating a temp table we build our own where for the relationship table
4031 $relationshipTempTable = NULL;
4032 if(self
::$_relType == 'reciprocal' && empty($targetGroup)) {
4034 self
::$_relationshipTempTable =
4035 $relationshipTempTable =
4036 CRM_Core_DAO
::createTempTableName( 'civicrm_rel');
4038 $where[$grouping][] = " sort_name $nameClause ";
4042 $where = &$this->_where
;
4044 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4049 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
4050 $relTypeOrg = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
4051 $relTypeHou = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Household');
4052 $allRelationshipType = array();
4053 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
4054 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
4056 if ($nameClause ||
!$targetGroup) {
4057 $this->_qill
[$grouping][] = "$allRelationshipType[$value] $name";
4061 //check to see if the target contact is in specified group
4063 //add contacts from static groups
4064 $this->_tables
['civicrm_relationship_group_contact'] =
4065 $this->_whereTables
['civicrm_relationship_group_contact'] =
4066 " 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'";
4068 "( civicrm_relationship_group_contact.group_id IN (" .
4069 implode(",", $targetGroup[2]) . ") ) ";
4071 //add contacts from saved searches
4072 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
4074 //set the group where clause
4076 $groupWhere[] = "( " . $ssWhere . " )";
4078 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4080 //Get the names of the target groups for the qill
4081 $groupNames = CRM_Core_PseudoConstant
::group();
4082 $qillNames = array();
4083 foreach ($targetGroup[2] as $groupId) {
4084 if (array_key_exists($groupId, $groupNames)) {
4085 $qillNames[] = $groupNames[$groupId];
4088 $this->_qill
[$grouping][] = "$allRelationshipType[$value] ( " . implode(", ", $qillNames) . " )";
4091 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4092 $today = date('Ymd');
4093 //check for active, inactive and all relation status
4094 if ($relStatus[2] == 0) {
4095 $where[$grouping][] = "(
4096 civicrm_relationship.is_active = 1 AND
4097 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4098 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4100 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4102 elseif ($relStatus[2] == 1) {
4103 $where[$grouping][] = "(
4104 civicrm_relationship.is_active = 0 OR
4105 civicrm_relationship.end_date < {$today} OR
4106 civicrm_relationship.start_date > {$today}
4108 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4111 //check for permissioned, non-permissioned and all permissioned relations
4112 if ($relPermission[2] == 1) {
4113 $this->_where
[$grouping][] = "(
4114 civicrm_relationship.is_permission_a_b = 1
4116 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4117 } elseif ($relPermission[2] == 2) {
4118 //non-allowed permission relationship.
4119 $this->_where
[$grouping][] = "(
4120 civicrm_relationship.is_permission_a_b = 0
4122 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4125 $this->addRelationshipDateClauses($grouping, $where);
4126 if(!empty($rType) && isset($rType->id
)){
4127 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
4129 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4130 $this->_useDistinct
= TRUE;
4131 $this->_relationshipValuesAdded
= TRUE;
4132 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4134 // @todo creating a temp table could be expanded to group filter
4135 // as even creating a temp table of all relationships is much much more efficient than
4136 // an OR in the join
4137 if($relationshipTempTable) {
4138 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4140 CREATE TEMPORARY TABLE {$relationshipTempTable}
4141 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4142 FROM civicrm_relationship
4143 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4146 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4147 FROM civicrm_relationship
4148 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4151 CRM_Core_DAO
::executeQuery($sql);
4156 * Add start & end date criteria in
4157 * @param string $grouping
4158 * @param array $where = array to add where clauses to, in case you are generating a temp table
4159 * not the main query.
4161 function addRelationshipDateClauses($grouping, &$where){
4162 $dateValues = array();
4168 foreach ($dateTypes as $dateField){
4169 $dateValueLow = $this->getWhereValues('relation_'. $dateField .'_low', $grouping);
4170 $dateValueHigh= $this->getWhereValues('relation_'. $dateField .'_high', $grouping);
4171 if(!empty($dateValueLow)){
4172 $date = date('Ymd', strtotime($dateValueLow[2]));
4173 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4174 $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);
4176 if(!empty($dateValueHigh)){
4177 $date = date('Ymd', strtotime($dateValueHigh[2]));
4178 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4179 $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);
4185 * default set of return properties
4189 * @return array derault return properties
4192 static function &defaultReturnProperties($mode = 1) {
4193 if (!isset(self
::$_defaultReturnProperties)) {
4194 self
::$_defaultReturnProperties = array();
4197 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4198 // add activity return properties
4199 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4200 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4203 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4206 if (empty(self
::$_defaultReturnProperties[$mode])) {
4207 self
::$_defaultReturnProperties[$mode] = array(
4210 'legal_identifier' => 1,
4211 'external_identifier' => 1,
4212 'contact_type' => 1,
4213 'contact_sub_type' => 1,
4215 'display_name' => 1,
4216 'preferred_mail_format' => 1,
4223 'formal_title' => 1,
4224 'communication_style_id' => 1,
4227 'street_address' => 1,
4228 'supplemental_address_1' => 1,
4229 'supplemental_address_2' => 1,
4232 'postal_code_suffix' => 1,
4233 'state_province' => 1,
4235 'world_region' => 1,
4242 'household_name' => 1,
4243 'organization_name' => 1,
4244 'deceased_date' => 1,
4249 'current_employer' => 1,
4250 // FIXME: should we use defaultHierReturnProperties() for the below?
4251 'do_not_email' => 1,
4254 'do_not_phone' => 1,
4255 'do_not_trade' => 1,
4257 'contact_is_deleted' => 1,
4258 'preferred_communication_method' => 1,
4259 'preferred_language' => 1,
4263 return self
::$_defaultReturnProperties[$mode];
4267 * get primary condition for a sql clause
4271 * @return string|NULL
4274 static function getPrimaryCondition($value) {
4275 if (is_numeric($value)) {
4276 $value = (int ) $value;
4277 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4283 * wrapper for a simple search query
4285 * @param array $params
4286 * @param array $returnProperties
4287 * @param bool $count
4292 static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4293 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4294 list($select, $from, $where, $having) = $query->query();
4296 return "$select $from $where $having";
4300 * These are stub comments as this function needs more explanation - particularly in terms of how it
4301 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4303 * This function was originally written as a wrapper for the api query but is called from multiple places
4304 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4305 * but it is unclear as to whehter that is historical or there is a reason
4306 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4308 * @param array $params
4309 * @param array $returnProperties
4310 * @param null $fields
4311 * @param string $sort
4312 * @param int $offset
4313 * @param int $row_count
4314 * @param bool $smartGroupCache
4315 * @param bool $count return count obnly
4316 * @param bool $skipPermissions Should permissions be ignored or should the logged in user's permissions be applied
4318 * @params bool $smartGroupCache ?? update smart group cache?
4323 static function apiQuery(
4325 $returnProperties = NULL,
4330 $smartGroupCache = TRUE,
4332 $skipPermissions = TRUE
4335 $query = new CRM_Contact_BAO_Query(
4336 $params, $returnProperties,
4337 NULL, TRUE, FALSE, 1,
4339 TRUE, $smartGroupCache
4342 //this should add a check for view deleted if permissions are enabled
4343 if ($skipPermissions){
4344 $query->_skipDeleteClause
= TRUE;
4346 $query->generatePermissionClause(FALSE, $count);
4348 // note : this modifies _fromClause and _simpleFromClause
4349 $query->includePseudoFieldsJoin($sort);
4351 list($select, $from, $where, $having) = $query->query($count);
4353 $options = $query->_options
;
4354 if(!empty($query->_permissionWhereClause
)){
4355 if (empty($where)) {
4356 $where = "WHERE $query->_permissionWhereClause";
4359 $where = "$where AND $query->_permissionWhereClause";
4363 $sql = "$select $from $where $having";
4366 if ($query->_useGroupBy
) {
4367 $sql .= ' GROUP BY contact_a.id';
4369 if (!empty($sort)) {
4370 $sort = CRM_Utils_Type
::escape($sort, 'String');
4371 $sql .= " ORDER BY $sort ";
4373 if ($row_count > 0 && $offset >= 0) {
4374 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4375 $rowCount = CRM_Utils_Type
::escape($row_count, 'Int');
4376 $sql .= " LIMIT $offset, $row_count ";
4379 $dao = CRM_Core_DAO
::executeQuery($sql);
4382 while ($dao->fetch()) {
4384 $noRows = $dao->rowCount
;
4386 return array($noRows,NULL);
4388 $val = $query->store($dao);
4389 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4391 if (!empty($convertedVals)) {
4392 $val = array_replace_recursive($val, $convertedVals);
4394 $values[$dao->contact_id
] = $val;
4397 return array($values, $options);
4401 * create and query the db for an contact search
4403 * @param int $offset the offset for the query
4404 * @param int $rowCount the number of rows to return
4405 * @param string $sort the order by string
4406 * @param boolean $count is this a count only query ?
4407 * @param boolean $includeContactIds should we include contact ids?
4408 * @param boolean $sortByChar if true returns the distinct array of first characters for search results
4409 * @param boolean $groupContacts if true, return only the contact ids
4410 * @param boolean $returnQuery should we return the query as a string
4411 * @param string $additionalWhereClause if the caller wants to further restrict the search (used for components)
4412 * @param null $sortOrder
4413 * @param string $additionalFromClause should be clause with proper joins, effective to reduce where clause load.
4415 * @param bool $skipOrderAndLimit
4417 * @return CRM_Core_DAO
4420 function searchQuery(
4421 $offset = 0, $rowCount = 0, $sort = NULL,
4422 $count = FALSE, $includeContactIds = FALSE,
4423 $sortByChar = FALSE, $groupContacts = FALSE,
4424 $returnQuery = FALSE,
4425 $additionalWhereClause = NULL, $sortOrder = NULL,
4426 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4429 if ($includeContactIds) {
4430 $this->_includeContactIds
= TRUE;
4431 $this->_whereClause
= $this->whereClause();
4434 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4436 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4437 // and that contact happens to be deleted, set $onlyDeleted to true
4438 foreach ($this->_params
as $values) {
4439 $name = CRM_Utils_Array
::value(0, $values);
4440 $op = CRM_Utils_Array
::value(1, $values);
4441 $value = CRM_Utils_Array
::value(2, $values);
4442 if ($name == 'contact_id' and $op == '=') {
4443 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4444 $onlyDeleted = TRUE;
4449 $this->generatePermissionClause($onlyDeleted, $count);
4451 // building the query string
4454 if (isset($this->_groupByComponentClause
)) {
4455 $groupBy = $this->_groupByComponentClause
;
4457 elseif ($this->_useGroupBy
) {
4458 $groupBy = ' GROUP BY contact_a.id';
4461 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4462 $groupBy = 'GROUP BY civicrm_activity.id ';
4465 $order = $orderBy = $limit = '';
4467 $config = CRM_Core_Config
::singleton();
4468 if ($config->includeOrderByClause ||
4469 isset($this->_distinctComponentClause
)
4472 if (is_string($sort)) {
4476 $orderBy = trim($sort->orderBy());
4478 if (!empty($orderBy)) {
4479 // this is special case while searching for
4480 // change log CRM-1718
4481 if (preg_match('/sort_name/i', $orderBy)) {
4482 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4485 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
4486 $order = " ORDER BY $orderBy";
4489 $sortOrder = CRM_Utils_Type
::escape($sortOrder, 'String');
4490 $order .= " $sortOrder";
4493 // always add contact_a.id to the ORDER clause
4494 // so the order is deterministic
4495 if (strpos('contact_a.id', $order) === FALSE) {
4496 $order .= ", contact_a.id";
4500 elseif ($sortByChar) {
4501 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4504 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4508 // hack for order clause
4510 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4511 $fieldOrder = explode(' ', $fieldStr);
4512 $field = $fieldOrder[0];
4518 $this->_whereTables
["civicrm_address"] = 1;
4519 $order = str_replace($field, "civicrm_address.{$field}", $order);
4523 case 'state_province':
4524 $this->_whereTables
["civicrm_{$field}"] = 1;
4525 $order = str_replace($field, "civicrm_{$field}.name", $order);
4529 $this->_whereTables
["civicrm_email"] = 1;
4530 $order = str_replace($field, "civicrm_email.{$field}", $order);
4534 //CRM-12565 add "`" around $field if it is a pseudo constant
4535 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
4536 if (!empty($value['element']) && $value['element'] == $field) {
4537 $order = str_replace($field, "`{$field}`", $order);
4541 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4542 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4546 if ($rowCount > 0 && $offset >= 0) {
4547 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4548 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4549 $limit = " LIMIT $offset, $rowCount ";
4553 // note : this modifies _fromClause and _simpleFromClause
4554 $this->includePseudoFieldsJoin($sort);
4556 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts);
4558 if(!empty($this->_permissionWhereClause
)){
4559 if (empty($where)) {
4560 $where = "WHERE $this->_permissionWhereClause";
4563 $where = "$where AND $this->_permissionWhereClause";
4567 if ($additionalWhereClause) {
4568 $where = $where . ' AND ' . $additionalWhereClause;
4571 //additional from clause should be w/ proper joins.
4572 if ($additionalFromClause) {
4573 $from .= "\n" . $additionalFromClause;
4576 // if we are doing a transform, do it here
4577 // use the $from, $where and $having to get the contact ID
4578 if ($this->_displayRelationshipType
) {
4579 $this->filterRelatedContacts($from, $where, $having);
4582 if ($skipOrderAndLimit) {
4583 $query = "$select $from $where $having $groupBy";
4586 $query = "$select $from $where $having $groupBy $order $limit";
4593 return CRM_Core_DAO
::singleValueQuery($query);
4596 $dao = CRM_Core_DAO
::executeQuery($query);
4597 if ($groupContacts) {
4599 while ($dao->fetch()) {
4602 return implode(',', $ids);
4609 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4611 * @param string $cacheKey
4612 * @param int $offset
4613 * @param int $rowCount
4614 * @param bool $includeContactIds
4615 * @return CRM_Core_DAO
4617 function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4618 $this->_includeContactIds
= $includeContactIds;
4619 list($select, $from, $where) = $this->query();
4620 $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);
4621 $order = " ORDER BY pnc.id";
4622 $groupBy = " GROUP BY contact_a.id";
4623 $limit = " LIMIT $offset, $rowCount";
4624 $query = "$select $from $where $groupBy $order $limit";
4626 return CRM_Core_DAO
::executeQuery($query);
4630 * Populate $this->_permissionWhereClause with permission related clause and update other
4631 * query related properties.
4633 * Function calls ACL permission class and hooks to filter the query appropriately
4635 * Note that these 2 params were in the code when extracted from another function
4636 * and a second round extraction would be to make them properties of the class
4638 * @param bool $onlyDeleted Only get deleted contacts
4639 * @param bool $count Return Count only
4643 function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4644 if (!$this->_skipPermission
) {
4645 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4646 CRM_Core_Permission
::VIEW
,
4648 $this->_whereTables
,
4651 $this->_skipDeleteClause
4654 // regenerate fromClause since permission might have added tables
4655 if ($this->_permissionWhereClause
) {
4656 //fix for row count in qill (in contribute/membership find)
4658 $this->_useDistinct
= TRUE;
4660 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4661 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4665 // add delete clause if needed even if we are skipping permission
4667 if (!$this->_skipDeleteClause
) {
4668 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4669 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4673 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4682 function setSkipPermission($val) {
4683 $this->_skipPermission
= $val;
4687 * @param null $context
4691 function &summaryContribution($context = NULL) {
4692 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4696 SELECT COUNT( conts.total_amount ) as total_count,
4697 SUM( conts.total_amount ) as total_amount,
4698 AVG( conts.total_amount ) as total_avg,
4699 conts.currency as currency";
4700 if($this->_permissionWhereClause
) {
4701 $where .= " AND " . $this->_permissionWhereClause
;
4703 if ($context == 'search') {
4704 $where .= " AND contact_a.is_deleted = 0 ";
4707 // make sure contribution is completed - CRM-4989
4708 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4712 $summary['total'] = array();
4713 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4715 $query = "$select FROM (
4716 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $completedWhere
4717 GROUP BY civicrm_contribution.id
4721 $dao = CRM_Core_DAO
::executeQuery($query);
4723 $summary['total']['count'] = 0;
4724 $summary['total']['amount'] = $summary['total']['avg'] = array();
4725 while ($dao->fetch()) {
4726 $summary['total']['count'] +
= $dao->total_count
;
4727 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4728 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4730 if (!empty($summary['total']['amount'])) {
4731 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4732 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4735 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4738 // soft credit summary
4739 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
4740 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
4743 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
4744 GROUP BY civicrm_contribution_soft.id
4747 $dao = CRM_Core_DAO
::executeQuery($query);
4748 $summary['soft_credit']['count'] = 0;
4749 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
4750 while ($dao->fetch()) {
4751 $summary['soft_credit']['count'] +
= $dao->total_count
;
4752 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4753 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4755 if (!empty($summary['soft_credit']['amount'])) {
4756 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
4757 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
4760 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
4765 //@todo - this could be one query using the IF in mysql - eg
4766 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
4767 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
4768 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
4769 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
4770 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
4771 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
4772 // FROM civicrm_contact contact_a
4773 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
4774 // WHERE ( ... where clause....
4775 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
4779 SELECT COUNT( conts.total_amount ) as cancel_count,
4780 SUM( conts.total_amount ) as cancel_amount,
4781 AVG( conts.total_amount ) as cancel_avg,
4782 conts.currency as currency";
4784 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4785 if ($context == 'search') {
4786 $where .= " AND contact_a.is_deleted = 0 ";
4789 $query = "$select FROM (
4790 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
4791 GROUP BY civicrm_contribution.id
4795 $dao = CRM_Core_DAO
::executeQuery($query);
4798 if ($dao->fetch()) {
4799 $summary['cancel']['count'] = $dao->cancel_count
;
4800 $summary['cancel']['amount'] = $dao->cancel_amount
;
4801 $summary['cancel']['avg'] = $dao->cancel_avg
;
4805 $summary['cancel']['count'] = 0;
4806 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4807 while ($dao->fetch()) {
4808 $summary['cancel']['count'] +
= $dao->cancel_count
;
4809 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4810 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4812 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4813 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
4820 * getter for the qill object
4826 return $this->_qill
;
4830 * default set of return default hier return properties
4835 static function &defaultHierReturnProperties() {
4836 if (!isset(self
::$_defaultHierReturnProperties)) {
4837 self
::$_defaultHierReturnProperties = array(
4840 'legal_identifier' => 1,
4841 'external_identifier' => 1,
4842 'contact_type' => 1,
4843 'contact_sub_type' => 1,
4845 'display_name' => 1,
4852 'formal_title' => 1,
4853 'communication_style_id' => 1,
4854 'email_greeting' => 1,
4855 'postal_greeting' => 1,
4859 'preferred_communication_method' => 1,
4860 'do_not_phone' => 1,
4861 'do_not_email' => 1,
4864 'do_not_trade' => 1,
4867 '1' => array('location_type' => 1,
4868 'street_address' => 1,
4870 'state_province' => 1,
4872 'postal_code_suffix' => 1,
4875 'phone-Mobile' => 1,
4888 'location_type' => 1,
4889 'street_address' => 1,
4891 'state_province' => 1,
4893 'postal_code_suffix' => 1,
4896 'phone-Mobile' => 1,
4910 return self
::$_defaultHierReturnProperties;
4917 * @param $dbFieldName
4918 * @param $fieldTitle
4919 * @param bool $appendTimeStamp
4921 function dateQueryBuilder(
4922 &$values, $tableName, $fieldName,
4923 $dbFieldName, $fieldTitle,
4924 $appendTimeStamp = TRUE
4926 list($name, $op, $value, $grouping, $wildcard) = $values;
4932 if ($name == "{$fieldName}_low" ||
4933 $name == "{$fieldName}_high"
4935 if (isset($this->_rangeCache
[$fieldName])) {
4938 $this->_rangeCache
[$fieldName] = 1;
4940 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4942 if ($name == $fieldName . '_low') {
4944 $firstPhrase = ts('greater than or equal to');
4945 $firstDate = CRM_Utils_Date
::processDate($value);
4947 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4948 if (!empty($secondValues) && $secondValues[2]) {
4950 $secondPhrase = ts('less than or equal to');
4951 $secondValue = $secondValues[2];
4953 if ($appendTimeStamp && strlen($secondValue) == 10) {
4954 $secondValue .= ' 23:59:59';
4956 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4959 elseif ($name == $fieldName . '_high') {
4961 $firstPhrase = ts('less than or equal to');
4963 if ($appendTimeStamp && strlen($value) == 10) {
4964 $value .= ' 23:59:59';
4966 $firstDate = CRM_Utils_Date
::processDate($value);
4968 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4969 if (!empty($secondValues) && $secondValues[2]) {
4971 $secondPhrase = ts('greater than or equal to');
4972 $secondValue = $secondValues[2];
4973 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4977 if (!$appendTimeStamp) {
4978 $firstDate = substr($firstDate, 0, 8);
4980 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
4983 if (!$appendTimeStamp) {
4984 $secondDate = substr($secondDate, 0, 8);
4986 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
4989 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4991 $this->_where
[$grouping][] = "
4992 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
4993 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
4995 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
4998 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
4999 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5003 if ($name == $fieldName) {
5007 $date = CRM_Utils_Date
::processDate($value);
5009 if (!$appendTimeStamp) {
5010 $date = substr($date, 0, 8);
5013 $format = CRM_Utils_Date
::customFormat($date);
5016 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'";
5019 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op";
5021 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5022 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$format\"";
5030 * @param $dbFieldName
5031 * @param $fieldTitle
5032 * @param null $options
5034 function numberRangeBuilder(&$values,
5035 $tableName, $fieldName,
5036 $dbFieldName, $fieldTitle,
5039 list($name, $op, $value, $grouping, $wildcard) = $values;
5041 if ($name == "{$fieldName}_low" ||
5042 $name == "{$fieldName}_high"
5044 if (isset($this->_rangeCache
[$fieldName])) {
5047 $this->_rangeCache
[$fieldName] = 1;
5049 $secondOP = $secondPhrase = $secondValue = NULL;
5051 if ($name == "{$fieldName}_low") {
5053 $firstPhrase = ts('greater than');
5055 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5056 if (!empty($secondValues)) {
5058 $secondPhrase = ts('less than');
5059 $secondValue = $secondValues[2];
5064 $firstPhrase = ts('less than');
5066 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5067 if (!empty($secondValues)) {
5069 $secondPhrase = ts('greater than');
5070 $secondValue = $secondValues[2];
5075 $this->_where
[$grouping][] = "
5076 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5077 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5079 $displayValue = $options ?
$options[$value] : $value;
5080 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5082 $this->_qill
[$grouping][] =
5083 "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5086 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5087 $displayValue = $options ?
$options[$value] : $value;
5088 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5090 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5095 if ($name == $fieldName) {
5099 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5101 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5102 $displayValue = $options ?
$options[$value] : $value;
5103 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5110 * Given the field name, operator, value & its data type
5111 * builds the where Clause for the query
5112 * used for handling 'IS NULL'/'IS NOT NULL' operators
5114 * @param string $field fieldname
5115 * @param string $op operator
5116 * @param string $value value
5117 * @param string $dataType data type of the field
5119 * @return string where clause for the query
5122 static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5124 $clause = "$field $op";
5132 $clause = " ( $field IS NULL OR $field = '' ) ";
5135 case 'IS NOT EMPTY':
5136 $clause = " ( $field IS NOT NULL AND $field <> '' ) ";
5141 if (isset($dataType)) {
5142 if (is_array($value)) {
5146 $value = CRM_Utils_Type
::escape($value, "String");
5147 $values = explode(',', CRM_Utils_Array
::value(0, explode(')', CRM_Utils_Array
::value(1, explode('(', $value)))));
5149 // supporting multiple values in IN clause
5151 foreach ($values as $v) {
5153 $val[] = "'" . CRM_Utils_Type
::escape($v, $dataType) . "'";
5155 $value = "(" . implode($val, ",") . ")";
5157 return "$clause $value";
5160 if (empty($dataType)) {
5161 $dataType = 'String';
5164 $value = CRM_Utils_Type
::escape($value, $dataType);
5165 // if we don't have a dataType we should assume
5166 if ($dataType == 'String' ||
$dataType == 'Text') {
5167 $value = "'" . strtolower($value) . "'";
5169 return "$clause $value";
5174 * @param bool $reset
5178 function openedSearchPanes($reset = FALSE) {
5179 if (!$reset ||
empty($this->_whereTables
)) {
5180 return self
::$_openedPanes;
5183 // pane name to table mapper
5184 $panesMapper = array(
5185 ts('Contributions') => 'civicrm_contribution',
5186 ts('Memberships') => 'civicrm_membership',
5187 ts('Events') => 'civicrm_participant',
5188 ts('Relationships') => 'civicrm_relationship',
5189 ts('Activities') => 'civicrm_activity',
5190 ts('Pledges') => 'civicrm_pledge',
5191 ts('Cases') => 'civicrm_case',
5192 ts('Grants') => 'civicrm_grant',
5193 ts('Address Fields') => 'civicrm_address',
5194 ts('Notes') => 'civicrm_note',
5195 ts('Change Log') => 'civicrm_log',
5196 ts('Mailings') => 'civicrm_mailing_event_queue',
5198 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5200 foreach (array_keys($this->_whereTables
) as $table) {
5201 if ($panName = array_search($table, $panesMapper)) {
5202 self
::$_openedPanes[$panName] = TRUE;
5206 return self
::$_openedPanes;
5212 function setOperator($operator) {
5213 $validOperators = array('AND', 'OR');
5214 if (!in_array($operator, $validOperators)) {
5217 $this->_operator
= $operator;
5223 function getOperator() {
5224 return $this->_operator
;
5232 function filterRelatedContacts(&$from, &$where, &$having) {
5233 static $_rTypeProcessed = NULL;
5234 static $_rTypeFrom = NULL;
5235 static $_rTypeWhere = NULL;
5237 if (!$_rTypeProcessed) {
5238 $_rTypeProcessed = TRUE;
5240 // create temp table with contact ids
5241 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5242 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5243 CRM_Core_DAO
::executeQuery($sql);
5246 REPLACE INTO $tableName ( contact_id )
5252 CRM_Core_DAO
::executeQuery($sql);
5254 $qillMessage = ts('Contacts with a Relationship Type of: ');
5255 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5257 if (is_numeric($this->_displayRelationshipType
)) {
5258 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5260 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5261 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5264 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5265 AND displayRelType.is_active = 1
5269 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5270 if ($dirOne == 'a') {
5271 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5273 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5274 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5278 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5280 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5281 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5285 WHERE displayRelType.relationship_type_id = $relType
5286 AND displayRelType.is_active = 1
5289 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5292 if (strpos($from, $_rTypeFrom) === FALSE) {
5293 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5294 // this happens when we have an event_type in the quert (CRM-7969)
5295 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5296 $from .= $_rTypeFrom;
5297 $where = $_rTypeWhere;
5308 static function caseImportant( $op ) {
5310 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5314 * @param $returnProperties
5319 static function componentPresent( &$returnProperties, $prefix ) {
5320 foreach ($returnProperties as $name => $dontCare ) {
5321 if (substr($name, 0, strlen($prefix)) == $prefix) {
5329 * Builds the necessary structures for all fields that are similar to option value lookups
5331 * @param $name string the name of the field
5332 * @param $op string the sql operator, this function should handle ALL SQL operators
5333 * @param $value string|integer|array depends on the operator and who's calling the query builder
5334 * @param $grouping int the index where to place the where clause
5335 * @param $selectValues
5336 * @param $field array an array that contains various properties of the field identified by $name
5337 * @param $label string The label for this field element
5338 * @param $dataType string The data type for this element
5340 * @param bool $useIDsOnly
5342 * @internal param array $selectValue the key value pairs for this element. This allows us to use this function for things besides option-value pairs
5343 * @return void adds the where clause and qill to the query object
5345 function optionValueQuery(
5353 $dataType = 'String',
5357 if (!empty($selectValues)) {
5358 $qill = $selectValues[$value];
5364 $pseudoFields = array('email_greeting', 'postal_greeting', 'addressee', 'gender_id', 'prefix_id', 'suffix_id', 'communication_style_id');
5366 if (is_numeric($value)) {
5367 $qill = $selectValues[(int ) $value];
5369 elseif ($op == 'IN' ||
$op == 'NOT IN') {
5370 $values = self
::parseSearchBuilderString($value);
5371 if (is_array($values)) {
5373 $newValues = array();
5374 foreach ($values as $v) {
5375 $intVals[] = (int) $v;
5376 $newValues[] = $selectValues[(int ) $v];
5379 $value = (in_array($name, $pseudoFields)) ?
$intVals : $newValues;
5380 $qill = implode(', ', $newValues);
5383 elseif (!array_key_exists($value, $selectValues)) {
5384 // its a string, lets get the int value
5385 $value = array_search($value, $selectValues);
5388 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5389 if ($tableName == 'civicrm_contact') {
5390 $wc = "contact_a.$fieldName";
5394 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5397 if (in_array($name, $pseudoFields)) {
5398 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5399 $wc = "contact_a.{$name}_id";
5401 $dataType = 'Positive';
5402 $value = (!$value) ?
0 : $value;
5405 $this->_qill
[$grouping][] = $label . " $op '$qill'";
5406 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' ||
$op == 'RLIKE')) ?
'=' : $op;
5407 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5411 * function to check and explode a user defined numeric string into an array
5412 * this was the protocol used by search builder in the old old days before we had
5413 * super nice js widgets to do the hard work
5415 * @param string $string
5416 * @param string $dataType the dataType we should check for the values, default integer
5418 * @return bool|array if string does not match the patter
5419 * array of numeric values if string does match the pattern
5422 static function parseSearchBuilderString($string, $dataType = 'Integer') {
5423 $string = trim($string);
5424 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5428 $string = substr($string, 1, -1);
5429 $values = explode(',', $string);
5430 if (empty($values)) {
5434 $returnValues = array();
5435 foreach ($values as $v) {
5436 if ($dataType == 'Integer' && ! is_numeric($v)) {
5439 else if ($dataType == 'String' && ! is_string($v)) {
5442 $returnValues[] = trim($v);
5445 if (empty($returnValues)) {
5449 return $returnValues;
5453 * convert the pseudo constants id's to their names
5455 * @param CRM_Core_DAO dao
5456 * @param bool $return
5460 function convertToPseudoNames(&$dao, $return = FALSE) {
5461 if (empty($this->_pseudoConstantsSelect
)) {
5465 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5466 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5470 if (property_exists($dao, $value['idCol'])) {
5471 $val = $dao->$value['idCol'];
5473 if (CRM_Utils_System
::isNull($val)) {
5476 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5478 $idColumn = "{$key}_id";
5479 $dao->$idColumn = $val;
5480 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5482 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5483 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5485 // FIX ME: we should potentially move this to component Query and write a wrapper function that
5486 // handles pseudoconstant fixes for all component
5487 elseif ($value['pseudoField'] == 'participant_role') {
5488 $viewRoles = array();
5489 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val) as $k => $v) {
5490 $viewRoles[] = CRM_Event_PseudoConstant
::participantRole($v);
5492 $dao->$key = implode(', ', $viewRoles);
5495 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5496 $dao->$key = $labels[$val];
5499 // return converted values in array format
5501 if (strpos($key, '-') !== FALSE) {
5502 $keyVal = explode('-', $key);
5503 $current = &$values;
5504 $lastElement = array_pop($keyVal);
5505 foreach ($keyVal as $v) {
5506 if (!array_key_exists($v, $current)) {
5507 $current[$v] = array();
5509 $current = &$current[$v];
5511 $current[$lastElement] = $dao->$key;
5514 $values[$key] = $dao->$key;
5523 * include pseudo fields LEFT JOIN
5524 * @param string|array $sort can be a object or string
5528 function includePseudoFieldsJoin($sort) {
5529 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5532 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5535 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5536 if (!empty($value['table'])) {
5537 $regex = "/({$value['table']}\.|{$name})/";
5538 if (preg_match($regex, $sort)) {
5539 $this->_elemnt
[$value['element']] = 1;
5540 $this->_select
[$value['element']] = $value['select'];
5541 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5542 $present[$value['table']] = $value['join'];
5546 $presentSimpleFrom = $present;
5548 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5549 array_key_exists('civicrm_country', $presentSimpleFrom)) {
5550 unset($presentSimpleFrom['civicrm_country']);
5552 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5553 array_key_exists('civicrm_country', $present)) {
5554 unset($present['civicrm_country']);
5557 $presentClause = $presentSimpleFromClause = NULL;
5558 if (!empty($present)) {
5559 $presentClause = implode(' ', $present);
5561 if (!empty($presentSimpleFrom)) {
5562 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5565 $this->_fromClause
= $this->_fromClause
. $presentClause;
5566 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5568 return array($presentClause, $presentSimpleFromClause);