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 // Set wildcard value based on "and/or" selection
567 foreach ($this->_params
as $key => $param) {
568 if ($param[0] == $value[0] . '_operator') {
569 $value[4] = $param[2] == 'or';
573 $this->_cfIDs
[$cfID][] = $value;
576 if (!array_key_exists($value[0], $this->_paramLookup
)) {
577 $this->_paramLookup
[$value[0]] = array();
579 $this->_paramLookup
[$value[0]][] = $value;
584 * Some composite fields do not appear in the fields array
585 * hack to make them part of the query
590 function addSpecialFields() {
591 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
592 foreach ($special as $name) {
593 if (!empty($this->_returnProperties
[$name])) {
594 $this->_select
[$name] = "contact_a.{$name} as $name";
595 $this->_element
[$name] = 1;
601 * Given a list of conditions in params and a list of desired
602 * return Properties generate the required select and from
603 * clauses. Note that since the where clause introduces new
604 * tables, the initial attempt also retrieves all variables used
610 function selectClause() {
612 $this->addSpecialFields();
614 foreach ($this->_fields
as $name => $field) {
615 // skip component fields
616 // there are done by the alter query below
617 // and need not be done on every field
619 (substr($name, 0, 12) == 'participant_') ||
620 (substr($name, 0, 7) == 'pledge_') ||
621 (substr($name, 0, 5) == 'case_')
626 // redirect to activity select clause
628 (substr($name, 0, 9) == 'activity_') ||
629 ($name == 'parent_id')
631 CRM_Activity_BAO_Query
::select($this);
635 // if this is a hierarchical name, we ignore it
636 $names = explode('-', $name);
637 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
641 // make an exception for special cases, to add the field in select clause
642 $makeException = FALSE;
644 //special handling for groups/tags
645 if (in_array($name, array('groups', 'tags', 'notes'))
646 && isset($this->_returnProperties
[substr($name, 0, -1)])
648 $makeException = TRUE;
651 // since note has 3 different options we need special handling
652 // note / note_subject / note_body
653 if ($name == 'notes') {
654 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
655 if (isset($this->_returnProperties
[$noteField])) {
656 $makeException = TRUE;
662 if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id'))) {
663 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
664 $makeException = TRUE;
668 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
669 if (!empty($this->_paramLookup
[$name]) ||
!empty($this->_returnProperties
[$name]) ||
673 // add to cfIDs array if not present
674 if (!array_key_exists($cfID, $this->_cfIDs
)) {
675 $this->_cfIDs
[$cfID] = array();
678 elseif (isset($field['where'])) {
679 list($tableName, $fieldName) = explode('.', $field['where'], 2);
680 if (isset($tableName)) {
681 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
682 $this->_tables
['civicrm_address'] = 1;
683 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
684 $this->_element
['address_id'] = 1;
687 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
688 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
690 if ($tableName == 'im_provider') {
691 CRM_Core_OptionValue
::select($this);
694 if (in_array($tableName,
695 array('email_greeting', 'postal_greeting', 'addressee'))) {
696 $this->_element
["{$name}_id"] = 1;
697 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
698 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
699 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
700 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
702 if ($tableName == 'email_greeting') {
703 $this->_pseudoConstantsSelect
[$name]['join'] =
704 " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
705 $this->_pseudoConstantsSelect
[$name]['join'] .=
706 " 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 ) ";
708 elseif ($tableName == 'postal_greeting') {
709 $this->_pseudoConstantsSelect
[$name]['join'] =
710 " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
711 $this->_pseudoConstantsSelect
[$name]['join'] .=
712 " 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 ) ";
714 elseif ($tableName == 'addressee') {
715 $this->_pseudoConstantsSelect
[$name]['join'] =
716 " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
717 $this->_pseudoConstantsSelect
[$name]['join'] .=
718 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
720 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
723 $greetField = "{$name}_display";
724 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
725 $this->_element
[$greetField] = 1;
727 $greetField = "{$name}_custom";
728 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
729 $this->_element
[$greetField] = 1;
733 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
734 $this->_tables
[$tableName] = 1;
737 // also get the id of the tableName
738 $tName = substr($tableName, 8);
739 if (in_array($tName, array('country', 'state_province', 'county'))) {
740 if ($tName == 'state_province') {
741 $this->_pseudoConstantsSelect
['state_province_name'] =
742 array('pseudoField' => "{$tName}", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address',
743 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
745 $this->_pseudoConstantsSelect
[$tName] =
746 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id",
747 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
750 $this->_pseudoConstantsSelect
[$name] =
751 array('pseudoField' => "{$tName}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address',
752 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
755 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
756 $this->_element
["{$tName}_id"] = 1;
758 elseif ($tName != 'contact') {
759 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
760 $this->_element
["{$tName}_id"] = 1;
763 //special case for phone
764 if ($name == 'phone') {
765 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
766 $this->_element
['phone_type_id'] = 1;
769 // if IM then select provider_id also
770 // to get "IM Service Provider" in a file to be exported, CRM-3140
772 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
773 $this->_element
['provider_id'] = 1;
776 if ($tName == 'contact') {
777 // special case, when current employer is set for Individual contact
778 if ($fieldName == 'organization_name') {
779 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
781 elseif ($fieldName != 'id') {
782 if ($fieldName == 'prefix_id') {
783 $this->_pseudoConstantsSelect
['individual_prefix'] = array('pseudoField' => 'prefix_id', 'idCol' => "prefix_id", 'bao' => 'CRM_Contact_BAO_Contact');
785 if ($fieldName == 'suffix_id') {
786 $this->_pseudoConstantsSelect
['individual_suffix'] = array('pseudoField' => 'suffix_id', 'idCol' => "suffix_id", 'bao' => 'CRM_Contact_BAO_Contact');
788 if ($fieldName == 'gender_id') {
789 $this->_pseudoConstantsSelect
['gender'] = array('pseudoField' => 'gender_id', 'idCol' => "gender_id", 'bao' => 'CRM_Contact_BAO_Contact');
791 if ($name == 'communication_style_id') {
792 $this->_pseudoConstantsSelect
['communication_style'] = array('pseudoField' => 'communication_style_id', 'idCol' => "communication_style_id", 'bao' => 'CRM_Contact_BAO_Contact');
794 $this->_select
[$name] = "contact_a.{$fieldName} as `$name`";
797 elseif (in_array($tName, array('country', 'county'))) {
798 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
799 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
801 elseif ($tName == 'state_province') {
802 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
803 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
806 $this->_select
[$name] = "{$field['where']} as `$name`";
808 if (!in_array($tName, array('state_province', 'country', 'county'))) {
809 $this->_element
[$name] = 1;
814 elseif ($name === 'tags') {
815 $this->_useGroupBy
= TRUE;
816 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
817 $this->_element
[$name] = 1;
818 $this->_tables
['civicrm_tag'] = 1;
819 $this->_tables
['civicrm_entity_tag'] = 1;
821 elseif ($name === 'groups') {
822 $this->_useGroupBy
= TRUE;
823 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
824 $this->_element
[$name] = 1;
825 $this->_tables
['civicrm_group'] = 1;
827 elseif ($name === 'notes') {
828 // if note field is subject then return subject else body of the note
829 $noteColumn = 'note';
830 if (isset($noteField) && $noteField == 'note_subject') {
831 $noteColumn = 'subject';
834 $this->_useGroupBy
= TRUE;
835 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
836 $this->_element
[$name] = 1;
837 $this->_tables
['civicrm_note'] = 1;
839 elseif ($name === 'current_employer') {
840 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
841 $this->_element
[$name] = 1;
845 if ($cfID && !empty($field['is_search_range'])) {
846 // this is a custom field with range search enabled, so we better check for two/from values
847 if (!empty($this->_paramLookup
[$name . '_from'])) {
848 if (!array_key_exists($cfID, $this->_cfIDs
)) {
849 $this->_cfIDs
[$cfID] = array();
851 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
852 // search in the cdID array for the same grouping
854 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
855 if ($c[3] == $p[3]) {
856 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
861 $p[2] = array('from' => $p[2]);
862 $this->_cfIDs
[$cfID][] = $p;
866 if (!empty($this->_paramLookup
[$name . '_to'])) {
867 if (!array_key_exists($cfID, $this->_cfIDs
)) {
868 $this->_cfIDs
[$cfID] = array();
870 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
871 // search in the cdID array for the same grouping
873 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
874 if ($c[4] == $p[4]) {
875 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
880 $p[2] = array('to' => $p[2]);
881 $this->_cfIDs
[$cfID][] = $p;
888 // add location as hierarchical elements
889 $this->addHierarchicalElements();
891 // add multiple field like website
892 $this->addMultipleElements();
895 CRM_Core_Component
::alterQuery($this, 'select');
897 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
899 if (!empty($this->_cfIDs
)) {
900 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
901 $this->_customQuery
->query();
902 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
903 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
904 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
905 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
906 $this->_options
= $this->_customQuery
->_options
;
911 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
917 function addHierarchicalElements() {
918 if (empty($this->_returnProperties
['location'])) {
921 if (!is_array($this->_returnProperties
['location'])) {
925 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
926 $processed = array();
929 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
930 $addressCustomFieldIds = array();
932 foreach ($this->_returnProperties
['location'] as $name => $elements) {
933 $lCond = self
::getPrimaryCondition($name);
936 $locationTypeId = array_search($name, $locationTypes);
937 if ($locationTypeId === FALSE) {
940 $lCond = "location_type_id = $locationTypeId";
941 $this->_useDistinct
= TRUE;
943 //commented for CRM-3256
944 $this->_useGroupBy
= TRUE;
947 $name = str_replace(' ', '_', $name);
949 $tName = "$name-location_type";
950 $ltName = "`$name-location_type`";
951 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
952 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
953 $this->_element
["{$tName}_id"] = 1;
954 $this->_element
["{$tName}"] = 1;
956 $locationTypeName = $tName;
957 $locationTypeJoin = array();
961 foreach ($elements as $elementFullName => $dontCare) {
963 $elementName = $elementCmpName = $elementFullName;
965 if (substr($elementCmpName, 0, 5) == 'phone') {
966 $elementCmpName = 'phone';
969 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
970 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
971 $addressCustomFieldIds[$cfID][$name] = 1;
974 //add address table only once
975 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
977 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
979 $tName = "$name-address";
980 $aName = "`$name-address`";
981 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
982 $this->_element
["{$tName}_id"] = 1;
983 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
984 $this->_tables
[$tName] = $addressJoin;
985 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
986 $processed[$aName] = 1;
990 $cond = $elementType = '';
991 if (strpos($elementName, '-') !== FALSE) {
992 // this is either phone, email or IM
993 list($elementName, $elementType) = explode('-', $elementName);
996 if (($elementName != 'phone') && ($elementName != 'im')) {
997 $cond = self
::getPrimaryCondition($elementType);
999 // CRM-13011 : If location type is primary, do not restrict search to the phone
1000 // type id - we want the primary phone, regardless of what type it is.
1001 // Otherwise, restrict to the specified phone type for the given field.
1002 if ((!$cond) && ($elementName == 'phone') && $elements['location_type'] != 'Primary') {
1003 $cond = "phone_type_id = '$elementType'";
1005 elseif ((!$cond) && ($elementName == 'im')) {
1006 // IM service provider id, CRM-3140
1007 $cond = "provider_id = '$elementType'";
1009 $elementType = '-' . $elementType;
1012 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
1014 // hack for profile, add location id
1017 // fix for CRM-882( to handle phone types )
1018 !is_numeric($elementType)
1020 if (is_numeric($name)) {
1021 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1024 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1027 elseif (is_numeric($name)) {
1028 //this for phone type to work
1029 if (in_array($elementName, array('phone', 'phone_ext'))) {
1030 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1033 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1037 //this is for phone type to work for profile edit
1038 if (in_array($elementName, array('phone', 'phone_ext'))) {
1039 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1042 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1047 // Check if there is a value, if so also add to where Clause
1049 if ($this->_params
) {
1051 if (isset($locationTypeId)) {
1052 $nm .= "-$locationTypeId";
1054 if (!is_numeric($elementType)) {
1055 $nm .= "$elementType";
1058 foreach ($this->_params
as $id => $values) {
1059 if ((is_array($values) && $values[0] == $nm) ||
1060 (in_array($elementName, array('phone', 'im'))
1061 && (strpos($values[0], $nm) !== FALSE)
1071 if ($field && isset($field['where'])) {
1072 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1073 $pf = substr($tableName, 8);
1074 $tName = $name . '-' . $pf . $elementType;
1075 if (isset($tableName)) {
1076 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1077 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1080 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1083 $this->_element
["{$tName}_id"] = 1;
1084 if (substr($tName, -15) == '-state_province') {
1085 // FIXME: hack to fix CRM-1900
1086 $a = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1090 if (substr_count($a, 'state_province_name') > 0) {
1091 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1092 array('pseudoField' => "{$pf}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1093 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1096 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1097 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id");
1098 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1102 if (substr($elementFullName, 0, 2) == 'im') {
1103 $provider = "{$name}-{$elementFullName}-provider_id";
1104 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1105 $this->_element
[$provider] = 1;
1107 if ($pf == 'country' ||
$pf == 'county') {
1108 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array('pseudoField' => "{$pf}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1109 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1112 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1116 if (in_array($pf, array('state_province', 'country', 'county'))) {
1117 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1120 $this->_element
["{$name}-{$elementFullName}"] = 1;
1123 if (empty($processed["`$tName`"])) {
1124 $processed["`$tName`"] = 1;
1125 $newName = $tableName . '_' . $index;
1126 switch ($tableName) {
1127 case 'civicrm_phone':
1128 case 'civicrm_email':
1130 case 'civicrm_openid':
1132 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id AND `$tName`.$lCond";
1133 // this special case to add phone type
1135 $phoneTypeCondition = " AND `$tName`.$cond ";
1136 //gross hack to pickup corrupted data also, CRM-7603
1137 if (strpos($cond, 'phone_type_id') !== FALSE) {
1138 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1140 $this->_tables
[$tName] .= $phoneTypeCondition;
1143 //build locationType join
1144 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1147 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1151 case 'civicrm_state_province':
1152 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1153 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1154 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1156 $this->_whereTables
["{$name}-address"] = $addressJoin;
1160 case 'civicrm_country':
1161 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1162 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1163 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1165 $this->_whereTables
["{$name}-address"] = $addressJoin;
1169 case 'civicrm_county':
1170 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1171 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1172 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1174 $this->_whereTables
["{$name}-address"] = $addressJoin;
1180 $this->_whereTables
["{$name}-address"] = $addressJoin;
1189 // add location type join
1190 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1191 $this->_tables
[$locationTypeName] = $ltypeJoin;
1193 // table should be present in $this->_whereTables,
1194 // to add its condition in location type join, CRM-3939.
1195 if ($addWhereCount) {
1196 $locClause = array();
1197 foreach ($this->_whereTables
as $tableName => $clause) {
1198 if (!empty($locationTypeJoin[$tableName])) {
1199 $locClause[] = $locationTypeJoin[$tableName];
1203 if (!empty($locClause)) {
1204 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1209 if (!empty($addressCustomFieldIds)) {
1210 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1211 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1212 foreach ($locTypeName as $name => $dnc) {
1213 $this->_locationSpecificCustomFields
[$cfID] = array($name, array_search($name, $locationTypes));
1214 $fieldName = "$name-custom_{$cfID}";
1215 $tName = "$name-address-custom-{$cfID}";
1216 $aName = "`$name-address-custom-{$cfID}`";
1217 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1218 $this->_element
["{$tName}_id"] = 1;
1219 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1220 $this->_element
[$fieldName] = 1;
1221 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1228 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
1234 function addMultipleElements() {
1235 if (empty($this->_returnProperties
['website'])) {
1238 if (!is_array($this->_returnProperties
['website'])) {
1242 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1243 foreach ($elements as $elementFullName => $dontCare) {
1244 $tName = "website-{$key}-{$elementFullName}";
1245 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1246 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1247 $this->_element
["{$tName}_id"] = 1;
1248 $this->_element
["{$tName}"] = 1;
1250 $type = "website-{$key}-website_type_id";
1251 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1252 $this->_element
[$type] = 1;
1253 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1259 * generate the query based on what type of query we need
1261 * @param boolean $count
1262 * @param boolean $sortByChar
1263 * @param boolean $groupContacts
1264 * @param boolean $onlyDeleted
1266 * @return array sql query parts as an array
1269 function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1270 // build permission clause
1271 $this->generatePermissionClause($onlyDeleted, $count);
1274 if (isset($this->_rowCountClause
)) {
1275 $select = "SELECT {$this->_rowCountClause}";
1276 } else if (isset($this->_distinctComponentClause
)) {
1277 // we add distinct to get the right count for components
1278 // for the more complex result set, we use GROUP BY the same id
1280 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1283 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1285 $from = $this->_simpleFromClause
;
1286 if ($this->_useDistinct
) {
1287 $this->_useGroupBy
= TRUE;
1290 elseif ($sortByChar) {
1291 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1292 $from = $this->_simpleFromClause
;
1294 elseif ($groupContacts) {
1295 $select = 'SELECT contact_a.id as id';
1296 if ($this->_useDistinct
) {
1297 $this->_useGroupBy
= TRUE;
1299 $from = $this->_simpleFromClause
;
1302 if (!empty($this->_paramLookup
['group'])) {
1303 // make sure there is only one element
1304 // this is used when we are running under smog and need to know
1305 // how the contact was added (CRM-1203)
1306 if ((count($this->_paramLookup
['group']) == 1) &&
1307 (count($this->_paramLookup
['group'][0][2]) == 1)
1309 $groups = array_keys($this->_paramLookup
['group'][0][2]);
1310 $groupId = $groups[0];
1312 //check if group is saved search
1313 $group = new CRM_Contact_BAO_Group();
1314 $group->id
= $groupId;
1317 if (!isset($group->saved_search_id
)) {
1318 $tbName = "`civicrm_group_contact-{$groupId}`";
1319 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1320 $this->_element
['group_contact_id'] = 1;
1321 $this->_select
['status'] = "$tbName.status as status";
1322 $this->_element
['status'] = 1;
1325 $this->_useGroupBy
= TRUE;
1327 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1328 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1330 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1331 $this->_useDistinct
= FALSE;
1332 $this->_useGroupBy
= TRUE;
1336 $select = "SELECT ";
1337 if (isset($this->_distinctComponentClause
)) {
1338 $select .= "{$this->_distinctComponentClause}, ";
1340 $select .= implode(', ', $this->_select
);
1341 $from = $this->_fromClause
;
1345 if (!empty($this->_whereClause
)) {
1346 $where = "WHERE {$this->_whereClause}";
1349 if (!empty($this->_permissionWhereClause
)) {
1350 if (empty($where)) {
1351 $where = "WHERE $this->_permissionWhereClause";
1354 $where = "$where AND $this->_permissionWhereClause";
1359 if (!empty($this->_having
)) {
1360 foreach ($this->_having
as $havingSets) {
1361 foreach ($havingSets as $havingSet) {
1362 $havingValue[] = $havingSet;
1365 $having = ' HAVING ' . implode(' AND ', $havingValue);
1368 // if we are doing a transform, do it here
1369 // use the $from, $where and $having to get the contact ID
1370 if ($this->_displayRelationshipType
) {
1371 $this->filterRelatedContacts($from, $where, $having);
1374 return array($select, $from, $where, $having);
1383 function &getWhereValues($name, $grouping) {
1385 foreach ($this->_params
as $values) {
1386 if ($values[0] == $name && $values[3] == $grouping) {
1399 static function fixDateValues($relative, &$from, &$to) {
1401 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1406 * @param $formValues
1407 * @param int $wildcard
1408 * @param bool $useEquals
1412 static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE) {
1414 if (empty($formValues)) {
1418 foreach ($formValues as $id => $values) {
1419 if ($id == 'privacy') {
1420 if (is_array($formValues['privacy'])) {
1421 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1422 foreach ($formValues['privacy'] as $key => $value) {
1424 $params[] = array($key, $op, $value, 0, 0);
1429 elseif ($id == 'email_on_hold') {
1430 if ($formValues['email_on_hold']['on_hold']) {
1431 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1434 elseif (preg_match('/_date_relative$/', $id) ||
1435 $id == 'event_relative' ||
1436 $id == 'case_from_relative' ||
1437 $id == 'case_to_relative'
1439 if ($id == 'event_relative') {
1440 $fromRange = 'event_start_date_low';
1441 $toRange = 'event_end_date_high';
1443 else if ($id == 'case_from_relative') {
1444 $fromRange = 'case_from_start_date_low';
1445 $toRange = 'case_from_start_date_high';
1447 else if ($id == 'case_to_relative') {
1448 $fromRange = 'case_to_end_date_low';
1449 $toRange = 'case_to_end_date_high';
1452 $dateComponent = explode('_date_relative', $id);
1453 $fromRange = "{$dateComponent[0]}_date_low";
1454 $toRange = "{$dateComponent[0]}_date_high";
1457 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1458 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1463 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals);
1468 $params[] = $values;
1477 * @param int $wildcard
1478 * @param bool $useEquals
1480 * @return array|null
1482 static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE) {
1483 // skip a few search variables
1484 static $skipWhere = NULL;
1485 static $likeNames = NULL;
1488 if (CRM_Utils_System
::isNull($values)) {
1494 'task', 'radio_ts', 'uf_group_id',
1495 'component_mode', 'qfKey', 'operator',
1496 'display_relationship_type',
1500 if (in_array($id, $skipWhere) ||
1501 substr($id, 0, 4) == '_qf_' ||
1502 substr($id, 0, 7) == 'hidden_'
1508 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1511 // email comes in via advanced search
1512 // so use wildcard always
1513 if ($id == 'email') {
1517 if (!$useEquals && in_array($id, $likeNames)) {
1518 $result = array($id, 'LIKE', $values, 0, 1);
1520 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1521 $result = array($id, 'LIKE', $values, 0, 0);
1523 elseif ($id == 'group') {
1524 if (is_array($values)) {
1525 foreach ($values as $groupIds => $val) {
1527 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1528 if (strlen($matches[1]) > 0) {
1529 $values[$matches[1]] = 1;
1530 unset($values[$groupIds]);
1536 $groupIds = explode(',', $values);
1538 foreach ($groupIds as $groupId) {
1539 $values[$groupId] = 1;
1543 $result = array($id, 'IN', $values, 0, 0);
1545 elseif ($id == 'contact_tags' ||
$id == 'tag') {
1546 if (!is_array($values)) {
1547 $tagIds = explode(',', $values);
1549 foreach ($tagIds as $tagId) {
1550 $values[$tagId] = 1;
1553 $result = array($id, 'IN', $values, 0, 0);
1555 elseif ($id == 'contact_type') {
1556 $result = array($id, 'IN', $values, 0, $wildcard);
1559 $result = array($id, '=', $values, 0, $wildcard);
1568 function whereClauseSingle(&$values) {
1569 // do not process custom fields or prefixed contact ids or component params
1570 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1571 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1572 (substr($values[0], 0, 13) == 'contribution_') ||
1573 (substr($values[0], 0, 6) == 'event_') ||
1574 (substr($values[0], 0, 12) == 'participant_') ||
1575 (substr($values[0], 0, 7) == 'member_') ||
1576 (substr($values[0], 0, 6) == 'grant_') ||
1577 (substr($values[0], 0, 7) == 'pledge_') ||
1578 (substr($values[0], 0, 5) == 'case_') ||
1579 (substr($values[0], 0, 10) == 'financial_') ||
1580 (substr($values[0], 0, 11) == 'membership_')
1585 // skip for hook injected fields / params
1586 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1587 if (array_key_exists($values[0], $extFields)) {
1591 switch ($values[0]) {
1592 case 'deleted_contacts':
1593 $this->deletedContacts($values);
1596 case 'contact_type':
1597 $this->contactType($values);
1600 case 'contact_sub_type':
1601 $this->contactSubType($values);
1605 $this->group($values);
1609 // so we resolve this into a list of groups & proceed as if they had been
1611 list($name, $op, $value, $grouping, $wildcard) = $values;
1612 $values[0] = 'group';
1614 $this->_paramLookup
['group'][0][0] ='group';
1615 $this->_paramLookup
['group'][0][1] = 'IN';
1616 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1617 $this->group($values);
1620 // case tag comes from find contacts
1622 $this->tagSearch($values);
1626 case 'contact_tags':
1627 $this->tag($values);
1632 case 'note_subject':
1633 $this->notes($values);
1637 $this->ufUser($values);
1641 case 'display_name':
1642 $this->sortName($values);
1646 $this->email($values);
1649 case 'phone_numeric':
1650 $this->phone_numeric($values);
1653 case 'phone_phone_type_id':
1654 case 'phone_location_type_id':
1655 $this->phone_option_group($values);
1658 case 'street_address':
1659 $this->street_address($values);
1662 case 'street_number':
1663 $this->street_number($values);
1666 case 'sortByCharacter':
1667 $this->sortByCharacter($values);
1670 case 'location_type':
1671 $this->locationType($values);
1675 $this->county($values);
1678 case 'state_province':
1679 $this->stateProvince($values);
1683 $this->country($values, FALSE);
1687 case 'postal_code_low':
1688 case 'postal_code_high':
1689 $this->postalCode($values);
1692 case 'activity_date':
1693 case 'activity_date_low':
1694 case 'activity_date_high':
1695 case 'activity_role':
1696 case 'activity_status':
1697 case 'followup_parent_id':
1699 case 'activity_subject':
1700 case 'test_activities':
1701 case 'activity_type_id':
1702 case 'activity_type':
1703 case 'activity_survey_id':
1704 case 'activity_tags':
1705 case 'activity_taglist':
1706 case 'activity_test':
1707 case 'activity_campaign_id':
1708 case 'activity_engagement_level':
1710 case 'activity_result':
1711 case 'source_contact':
1712 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1715 case 'birth_date_low':
1716 case 'birth_date_high':
1717 case 'deceased_date_low':
1718 case 'deceased_date_high':
1719 $this->demographics($values);
1722 case 'log_date_low':
1723 case 'log_date_high':
1724 $this->modifiedDates($values);
1728 $this->changeLog($values);
1731 case 'do_not_phone':
1732 case 'do_not_email':
1735 case 'do_not_trade':
1737 $this->privacy($values);
1740 case 'privacy_options':
1741 $this->privacyOptions($values);
1744 case 'privacy_operator':
1745 case 'privacy_toggle':
1746 // these are handled by privacy options
1749 case 'preferred_communication_method':
1750 $this->preferredCommunication($values);
1753 case 'relation_type_id':
1754 case 'relation_start_date_high':
1755 case 'relation_start_date_low':
1756 case 'relation_end_date_high':
1757 case 'relation_end_date_low':
1758 case 'relation_target_name':
1759 case 'relation_status':
1760 case 'relation_date_low':
1761 case 'relation_date_high':
1762 $this->relationship($values);
1763 $this->_relationshipValuesAdded
= TRUE;
1766 case 'task_status_id':
1767 $this->task($values);
1771 // since this case is handled with the above
1774 case 'prox_distance':
1775 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1778 case 'prox_street_address':
1780 case 'prox_postal_code':
1781 case 'prox_state_province_id':
1782 case 'prox_country_id':
1783 // handled by the proximity_distance clause
1787 $this->restWhere($values);
1793 * Given a list of conditions in params generate the required
1799 function whereClause() {
1800 $this->_where
[0] = array();
1801 $this->_qill
[0] = array();
1803 $this->includeContactIds();
1804 if (!empty($this->_params
)) {
1805 foreach (array_keys($this->_params
) as $id) {
1806 if (empty($this->_params
[$id][0])) {
1809 // check for both id and contact_id
1810 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
1812 $this->_params
[$id][1] == 'IS NULL' ||
1813 $this->_params
[$id][1] == 'IS NOT NULL'
1815 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]}";
1817 elseif (is_array($this->_params
[$id][2])) {
1818 $idList = implode("','", $this->_params
[$id][2]);
1819 //why on earth do they put ' in the middle & not on the outside? We have to assume it's
1820 //to support 'something' so lets add them conditionally to support the api (which is a tested flow
1821 // so if you are looking to alter this check api test results
1822 if(strpos(trim($idList), "'") > 0) {
1823 $idList = "'" . $idList . "'";
1826 $this->_where
[0][] = "contact_a.id IN ({$idList})";
1829 $this->_where
[0][] = self
::buildClause("contact_a.id", "{$this->_params[$id][1]}", "{$this->_params[$id][2]}");
1833 $this->whereClauseSingle($this->_params
[$id]);
1837 CRM_Core_Component
::alterQuery($this, 'where');
1839 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
1842 if ($this->_customQuery
) {
1843 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1844 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1845 if (!empty($this->_customQuery
->_where
)) {
1846 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
1849 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
1853 $andClauses = array();
1856 if (!empty($this->_where
)) {
1857 foreach ($this->_where
as $grouping => $values) {
1858 if ($grouping > 0 && !empty($values)) {
1859 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1864 if (!empty($this->_where
[0])) {
1865 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
1867 if (!empty($clauses)) {
1868 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1871 if ($validClauses > 1) {
1872 $this->_useDistinct
= TRUE;
1876 return implode(' AND ', $andClauses);
1884 function restWhere(&$values) {
1885 $name = CRM_Utils_Array
::value(0, $values);
1886 $op = CRM_Utils_Array
::value(1, $values);
1887 $value = CRM_Utils_Array
::value(2, $values);
1888 $grouping = CRM_Utils_Array
::value(3, $values);
1889 $wildcard = CRM_Utils_Array
::value(4, $values);
1891 if (isset($grouping) && empty($this->_where
[$grouping])) {
1892 $this->_where
[$grouping] = array();
1895 $multipleFields = array('url');
1897 //check if the location type exits for fields
1899 $locType = explode('-', $name);
1901 if (!in_array($locType[0], $multipleFields)) {
1902 //add phone type if exists
1903 if (isset($locType[2]) && $locType[2]) {
1904 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
1908 $field = CRM_Utils_Array
::value($name, $this->_fields
);
1911 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
1920 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
1921 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1923 if (substr($name, 0, 14) === 'state_province') {
1924 if (isset($locType[1]) && is_numeric($locType[1])) {
1926 $aName = "{$locationType[$locType[1]]}-address";
1927 $where = "`$aName`.state_province_id";
1930 $where = "civicrm_address.state_province_id";
1933 $states = CRM_Core_PseudoConstant
::stateProvince();
1934 if (is_numeric($value)) {
1935 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1936 $value = $states[(int ) $value];
1939 $intVal = CRM_Utils_Array
::key($value, $states);
1940 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1943 $this->_qill
[$grouping][] = ts('State') . " $op '$value'";
1946 $this->_qill
[$grouping][] = ts('State') . " ($lType) $op '$value'";
1949 elseif (!empty($field['pseudoconstant'])) {
1950 $this->optionValueQuery(
1951 $name, $op, $value, $grouping,
1952 CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', $field['name']),
1958 if ($name == 'gender_id') {
1959 self
::$_openedPanes[ts('Demographics')] = TRUE;
1962 elseif (substr($name, 0, 7) === 'country') {
1963 if (isset($locType[1]) && is_numeric($locType[1])) {
1965 $aName = "{$locationType[$locType[1]]}-address";
1966 $where = "`$aName`.country_id";
1969 $where = "civicrm_address.country_id";
1972 $countries = CRM_Core_PseudoConstant
::country();
1973 if (is_numeric($value)) {
1974 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1975 $value = $countries[(int ) $value];
1978 $intVal = CRM_Utils_Array
::key($value, $countries);
1979 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1983 $this->_qill
[$grouping][] = ts('Country') . " $op '$value'";
1986 $this->_qill
[$grouping][] = ts('Country') . " ($lType) $op '$value'";
1989 elseif (substr($name, 0, 6) === 'county') {
1990 if (isset($locType[1]) && is_numeric($locType[1])) {
1992 $aName = "{$locationType[$locType[1]]}-address";
1993 $where = "`$aName`.county_id";
1996 $where = "civicrm_address.county_id";
1999 $counties = CRM_Core_PseudoConstant
::county();
2000 if (is_numeric($value)) {
2001 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2002 $value = $counties[(int ) $value];
2005 $intVal = CRM_Utils_Array
::key($value, $counties);
2006 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
2010 $this->_qill
[$grouping][] = ts('County') . " $op '$value'";
2013 $this->_qill
[$grouping][] = ts('County') . " ($lType) $op '$value'";
2016 elseif ($name === 'world_region') {
2017 $field['where'] = 'civicrm_worldregion.id';
2018 $this->optionValueQuery(
2019 $name, $op, $value, $grouping,
2020 CRM_Core_PseudoConstant
::worldRegion(),
2027 elseif ($name === 'birth_date') {
2028 $date = CRM_Utils_Date
::processDate($value);
2029 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
2032 $date = CRM_Utils_Date
::customFormat($date);
2033 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
2036 $this->_qill
[$grouping][] = "$field[title] $op";
2038 self
::$_openedPanes[ts('Demographics')] = TRUE;
2040 elseif ($name === 'deceased_date') {
2041 $date = CRM_Utils_Date
::processDate($value);
2042 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
2044 $date = CRM_Utils_Date
::customFormat($date);
2045 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
2048 $this->_qill
[$grouping][] = "$field[title] $op";
2050 self
::$_openedPanes[ts('Demographics')] = TRUE;
2052 elseif ($name === 'is_deceased') {
2053 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
2054 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2055 self
::$_openedPanes[ts('Demographics')] = TRUE;
2057 elseif ($name === 'contact_id') {
2058 if (is_int($value)) {
2059 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2060 $this->_qill
[$grouping][] = "$field[title] $op $value";
2063 elseif ($name === 'name') {
2064 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2066 $value = "%$value%";
2069 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2070 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2071 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2073 elseif ($name === 'current_employer') {
2074 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2076 $value = "%$value%";
2079 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
2080 $ceWhereClause = self
::buildClause($wc, $op,
2083 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2084 $this->_where
[$grouping][] = $ceWhereClause;
2085 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2087 elseif ($name === 'email_greeting') {
2088 $filterCondition = array('greeting_type' => 'email_greeting');
2089 $this->optionValueQuery(
2090 $name, $op, $value, $grouping,
2091 CRM_Core_PseudoConstant
::greeting($filterCondition),
2093 ts('Email Greeting')
2096 elseif ($name === 'postal_greeting') {
2097 $filterCondition = array('greeting_type' => 'postal_greeting');
2098 $this->optionValueQuery(
2099 $name, $op, $value, $grouping,
2100 CRM_Core_PseudoConstant
::greeting($filterCondition),
2102 ts('Postal Greeting')
2105 elseif ($name === 'addressee') {
2106 $filterCondition = array('greeting_type' => 'addressee');
2107 $this->optionValueQuery(
2108 $name, $op, $value, $grouping,
2109 CRM_Core_PseudoConstant
::greeting($filterCondition),
2114 elseif (substr($name, 0, 4) === 'url-') {
2115 $tName = 'civicrm_website';
2116 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2117 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2119 $value = "%$value%";
2123 $wc = 'civicrm_website.url';
2124 $this->_where
[$grouping][] = $d = self
::buildClause($wc, $op, $value);
2125 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2127 elseif ($name === 'contact_is_deleted') {
2128 $this->_where
[$grouping][] = self
::buildClause("contact_a.is_deleted", $op, $value);
2129 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2132 if (is_array($value)) {
2133 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2134 // for api style operators for functions that hit this point without worrying about regression
2135 // (the previous comments indicated the condition for hitting this point were unknown
2136 // per CRM-14743 we are adding modified_date & created_date operator support
2137 $operations = array_keys($value);
2138 foreach ($operations as $operator) {
2139 if(!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2140 // we don't know when this might happen
2141 CRM_Core_Error
::fatal();
2144 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($name, $value, NULL);
2145 //since this is not currently being called by the form layer we can skip worrying about the 'qill' for now
2149 if (!empty($field['where'])) {
2151 $value = $strtolower($value);
2154 $value = "%$value%";
2158 if (isset($locType[1]) &&
2159 is_numeric($locType[1])
2163 //get the location name
2164 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2166 $where = "`$tName`.$fldName";
2168 $this->_where
[$grouping][] = self
::buildClause("LOWER($where)", $op, $value);
2169 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2170 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2171 $this->_qill
[$grouping][] = "$field[title] $op '$value'";
2174 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2175 if ($tableName == 'civicrm_contact') {
2176 $fieldName = "LOWER(contact_a.{$fieldName})";
2179 if ($op != 'IN' && !is_numeric($value)) {
2180 $fieldName = "LOWER({$field['where']})";
2183 $fieldName = "{$field['where']}";
2188 if (!empty($field['type'])) {
2189 $type = CRM_Utils_Type
::typeToString($field['type']);
2192 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2193 $this->_qill
[$grouping][] = "$field[title] $op $value";
2198 if ($setTables && isset($field['where'])) {
2199 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2200 if (isset($tableName)) {
2201 $this->_tables
[$tableName] = 1;
2202 $this->_whereTables
[$tableName] = 1;
2215 static function getLocationTableName(&$where, &$locType) {
2216 if (isset($locType[1]) && is_numeric($locType[1])) {
2217 list($tbName, $fldName) = explode(".", $where);
2219 //get the location name
2220 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2221 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2222 if (in_array($locType[0], $specialFields)) {
2223 //hack to fix / special handing for phone_ext
2224 if ($locType[0] == 'phone_ext') {
2225 $locType[0] = 'phone';
2227 if (isset($locType[2]) && $locType[2]) {
2228 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2231 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2234 elseif (in_array($locType[0],
2236 'address_name', 'street_address', 'supplemental_address_1', 'supplemental_address_2',
2237 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
2240 //fix for search by profile with address fields.
2241 $tName = "{$locationType[$locType[1]]}-address";
2243 elseif ($locType[0] == 'on_hold') {
2244 $tName = "{$locationType[$locType[1]]}-email";
2247 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2249 $tName = str_replace(' ', '_', $tName);
2250 return array($tName, $fldName);
2252 CRM_Core_Error
::fatal();
2256 * Given a result dao, extract the values and return that array
2258 * @param Object $dao
2260 * @return array values for this query
2262 function store($dao) {
2265 foreach ($this->_element
as $key => $dontCare) {
2266 if (property_exists($dao, $key)) {
2267 if (strpos($key, '-') !== FALSE) {
2268 $values = explode('-', $key);
2269 $lastElement = array_pop($values);
2271 $cnt = count($values);
2273 foreach ($values as $v) {
2274 if (!array_key_exists($v, $current)) {
2275 $current[$v] = array();
2277 //bad hack for im_provider
2278 if ($lastElement == 'provider_id') {
2279 if ($count < $cnt) {
2280 $current = &$current[$v];
2283 $lastElement = "{$v}_{$lastElement}";
2287 $current = &$current[$v];
2292 $current[$lastElement] = $dao->$key;
2295 $value[$key] = $dao->$key;
2303 * getter for tables array
2309 return $this->_tables
;
2313 * Where tables is sometimes used to create the from clause, but, not reliably, set this AND set tables
2314 * It's unclear the intent - there is a 'simpleFrom' clause which takes whereTables into account & a fromClause which doesn't
2315 * logic may have eroded
2318 function whereTables() {
2319 return $this->_whereTables
;
2323 * generate the where clause (used in match contacts and permissions)
2325 * @param array $params
2326 * @param array $fields
2327 * @param array $tables
2328 * @param $whereTables
2329 * @param boolean $strict
2335 static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2336 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2340 $tables = array_merge($query->tables(), $tables);
2341 $whereTables = array_merge($query->whereTables(), $whereTables);
2343 return $query->_whereClause
;
2347 * create the from clause
2349 * @param array $tables tables that need to be included in this from clause
2350 * if null, return mimimal from clause (i.e. civicrm_contact)
2351 * @param array $inner tables that should be inner-joined
2352 * @param array $right tables that should be right-joined
2354 * @param bool $primaryLocation
2357 * @return string the from clause
2361 static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2363 $from = ' FROM civicrm_contact contact_a';
2364 if (empty($tables)) {
2368 if (!empty($tables['civicrm_worldregion'])) {
2369 $tables = array_merge(array('civicrm_country' => 1), $tables);
2372 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2373 CRM_Utils_Array
::value('civicrm_county', $tables)
2374 ) && empty($tables['civicrm_address'])) {
2375 $tables = array_merge(array('civicrm_address' => 1),
2380 // add group_contact table if group table is present
2381 if (!empty($tables['civicrm_group']) && empty($tables['civicrm_group_contact'])) {
2382 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
2385 // add group_contact and group table is subscription history is present
2386 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2387 $tables = array_merge(array(
2388 'civicrm_group' => 1,
2389 'civicrm_group_contact' => 1,
2395 // to handle table dependencies of components
2396 CRM_Core_Component
::tableNames($tables);
2397 // to handle table dependencies of hook injected tables
2398 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2400 //format the table list according to the weight
2401 $info = CRM_Core_TableHierarchy
::info();
2403 foreach ($tables as $key => $value) {
2405 if (strpos($key, '-') !== FALSE) {
2406 $keyArray = explode('-', $key);
2407 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2409 elseif (strpos($key, '_') !== FALSE) {
2410 $keyArray = explode('_', $key);
2411 if (is_numeric(array_pop($keyArray))) {
2412 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2415 $k = CRM_Utils_Array
::value($key, $info, 99);
2419 $k = CRM_Utils_Array
::value($key, $info, 99);
2421 $tempTable[$k . ".$key"] = $key;
2424 $newTables = array();
2425 foreach ($tempTable as $key) {
2426 $newTables[$key] = $tables[$key];
2429 $tables = $newTables;
2431 foreach ($tables as $name => $value) {
2436 if (!empty($inner[$name])) {
2439 elseif (!empty($right[$name])) {
2447 // if there is already a join statement in value, use value itself
2448 if (strpos($value, 'JOIN')) {
2449 $from .= " $value ";
2452 $from .= " $side JOIN $name ON ( $value ) ";
2457 case 'civicrm_address':
2458 if ($primaryLocation) {
2459 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2462 //CRM-14263 further handling of address joins further down...
2463 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2467 case 'civicrm_phone':
2468 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2471 case 'civicrm_email':
2472 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2476 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2480 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2481 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2482 $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)";
2485 case 'civicrm_openid':
2486 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2489 case 'civicrm_worldregion':
2490 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2491 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2494 case 'civicrm_location_type':
2495 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2498 case 'civicrm_group':
2499 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2502 case 'civicrm_group_contact':
2503 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2506 case 'civicrm_activity':
2507 case 'civicrm_activity_tag':
2508 case 'activity_type':
2509 case 'activity_status':
2511 case 'civicrm_activity_contact':
2512 case 'source_contact':
2513 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2516 case 'civicrm_entity_tag':
2517 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2518 civicrm_entity_tag.entity_id = contact_a.id ) ";
2521 case 'civicrm_note':
2522 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2523 contact_a.id = civicrm_note.entity_id ) ";
2526 case 'civicrm_subscription_history':
2527 $from .= " $side JOIN civicrm_subscription_history
2528 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2529 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2532 case 'civicrm_relationship':
2533 if (self
::$_relType == 'reciprocal') {
2534 if(self
::$_relationshipTempTable) {
2535 // we have a temptable to join on
2536 $tbl = self
::$_relationshipTempTable;
2537 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2540 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2541 $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)";
2544 elseif (self
::$_relType == 'b') {
2545 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2546 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2549 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2550 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2555 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2556 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2560 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2563 case 'civicrm_grant':
2564 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2567 case 'civicrm_website':
2568 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2572 $locationTypeName = '';
2573 if (strpos($name, '-address') != 0) {
2574 $locationTypeName = 'address';
2576 elseif (strpos($name, '-phone') != 0) {
2577 $locationTypeName = 'phone';
2579 elseif (strpos($name, '-email') != 0) {
2580 $locationTypeName = 'email';
2582 if($locationTypeName) {
2583 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2584 $parts = explode('-', $name);
2585 $locationID = array_search($parts[0], CRM_Core_BAO_Address
::buildOptions('location_type_id', 'get', array('name' => $parts[0])));
2586 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2589 $from .= CRM_Core_Component
::from($name, $mode, $side);
2591 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2600 * WHERE / QILL clause for deleted_contacts
2606 function deletedContacts($values) {
2607 list($_, $_, $value, $grouping, $_) = $values;
2609 // *prepend* to the relevant grouping as this is quite an important factor
2610 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2615 * where / qill clause for contact_type
2622 function contactType(&$values) {
2623 list($name, $op, $value, $grouping, $wildcard) = $values;
2625 $subTypes = array();
2628 // account for search builder mapping multiple values
2629 if (!is_array($value)) {
2630 $values = self
::parseSearchBuilderString($value, 'String');
2631 if (is_array($values)) {
2632 $value = array_flip($values);
2636 if (is_array($value)) {
2637 foreach ($value as $k => $v) {
2642 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2643 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2646 if (!empty($subType)) {
2647 $subTypes[$subType] = 1;
2649 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2654 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2655 $contactType = $contactTypeANDSubType[0];
2656 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2657 if (!empty($subType)) {
2658 $subTypes[$subType] = 1;
2660 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2664 if (!empty($clause)) {
2666 if ($op == 'IN' ||
$op == 'NOT IN') {
2667 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2670 $type = array_pop($clause);
2671 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2674 $this->_qill
[$grouping][] = ts('Contact Type') . ' - ' . implode(' ' . ts('or') . ' ', $quill);
2676 if (!empty($subTypes)) {
2677 $this->includeContactSubTypes($subTypes, $grouping);
2683 * where / qill clause for contact_sub_type
2690 function contactSubType(&$values) {
2691 list($name, $op, $value, $grouping, $wildcard) = $values;
2692 $this->includeContactSubTypes($value, $grouping);
2699 function includeContactSubTypes($value, $grouping) {
2702 $alias = "contact_a.contact_sub_type";
2704 if (is_array($value)) {
2705 foreach ($value as $k => $v) {
2707 $clause[$k] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($k, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2712 $clause[$value] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2715 if (!empty($clause)) {
2716 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2717 $this->_qill
[$grouping][] = ts('Contact Subtype') . ' - ' . implode(' ' . ts('or') . ' ', array_keys($clause));
2722 * where / qill clause for groups
2729 function group(&$values) {
2730 list($name, $op, $value, $grouping, $wildcard) = $values;
2732 if (count($value) > 1) {
2733 $this->_useDistinct
= TRUE;
2736 $groupNames = CRM_Core_PseudoConstant
::group();
2737 $groupIds = implode(',', array_keys($value));
2740 foreach ($value as $id => $dontCare) {
2741 if (array_key_exists($id, $groupNames) && $dontCare) {
2742 $names[] = $groupNames[$id];
2748 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2750 is_array($gcsValues[2])
2752 foreach ($gcsValues[2] as $k => $v) {
2754 if ($k == 'Added') {
2757 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2762 $statii[] = '"Added"';
2767 if (count($value) == 1 &&
2768 count($statii) == 1 &&
2769 $statii[0] == '"Added"'
2771 // check if smart group, if so we can get rid of that one additional
2773 $groupIDs = array_keys($value);
2775 if (!empty($groupIDs[0]) &&
2776 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
2786 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2787 $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 ) )";
2790 $qill = ts('Contacts %1', array(1 => $op));
2791 $qill .= ' ' . implode(' ' . ts('or') . ' ', $names);
2793 $groupClause = NULL;
2796 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2797 if (!empty($statii)) {
2798 $groupClause .= " AND {$gcTable}.status IN (" . implode(', ', $statii) . ")";
2799 $qill .= " " . ts('AND') . " " . ts('Group Status') . ' - ' . implode(' ' . ts('or') . ' ', $statii);
2804 $ssClause = $this->savedSearch($values);
2807 $groupClause = "( ( $groupClause ) OR ( $ssClause ) )";
2810 $groupClause = $ssClause;
2815 $this->_where
[$grouping][] = $groupClause;
2816 $this->_qill
[$grouping][] = $qill;
2819 * Function translates selection of group type into a list of groups
2826 function getGroupsFromTypeCriteria($value){
2827 $groupIds = array();
2828 foreach ($value as $groupTypeValue) {
2829 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2830 $groupIds = ($groupIds +
$groupList);
2836 * where / qill clause for smart groups
2840 * @return string|NULL
2843 function savedSearch(&$values) {
2844 list($name, $op, $value, $grouping, $wildcard) = $values;
2845 return $this->addGroupContactCache(array_keys($value));
2849 * @param array $groups
2850 * @param string $tableAlias
2851 * @param string $joinTable
2853 * @return null|string
2855 function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
2856 $config = CRM_Core_Config
::singleton();
2858 // Find all the groups that are part of a saved search.
2859 $groupIDs = implode(',', $groups);
2860 if (empty($groupIDs)) {
2865 SELECT id, cache_date, saved_search_id, children
2867 WHERE id IN ( $groupIDs )
2868 AND ( saved_search_id != 0
2869 OR saved_search_id IS NOT NULL
2870 OR children IS NOT NULL )
2873 $group = CRM_Core_DAO
::executeQuery($sql);
2874 $groupsFiltered = array();
2876 while ($group->fetch()) {
2877 $groupsFiltered[] = $group->id
;
2879 $this->_useDistinct
= TRUE;
2881 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
2882 CRM_Contact_BAO_GroupContactCache
::load($group);
2886 if (count($groupsFiltered)) {
2887 $groupIDsFiltered = implode(',', $groupsFiltered);
2889 if ($tableAlias == NULL) {
2890 $tableAlias = "civicrm_group_contact_cache_{$groupIDsFiltered}";
2893 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache `{$tableAlias}` ON {$joinTable}.id = `{$tableAlias}`.contact_id ";
2895 return "`{$tableAlias}`.group_id IN (" . $groupIDsFiltered . ")";
2902 * where / qill clause for cms users
2909 function ufUser(&$values) {
2910 list($name, $op, $value, $grouping, $wildcard) = $values;
2913 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2915 $this->_qill
[$grouping][] = ts('CMS User');
2917 elseif ($value == 0) {
2918 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2920 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2921 $this->_qill
[$grouping][] = ts('Not a CMS User');
2926 * all tag search specific
2933 function tagSearch(&$values) {
2934 list($name, $op, $value, $grouping, $wildcard) = $values;
2937 $value = "%{$value}%";
2940 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2941 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2943 $etTable = "`civicrm_entity_tag-" . $value . "`";
2944 $tTable = "`civicrm_tag-" . $value . "`";
2946 if ($useAllTagTypes[2]) {
2947 $this->_tables
[$etTable] =
2948 $this->_whereTables
[$etTable] =
2949 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
2950 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
2952 // search tag in cases
2953 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2954 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
2955 $this->_tables
[$etCaseTable] =
2956 $this->_whereTables
[$etCaseTable] =
2957 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2958 LEFT JOIN civicrm_case
2959 ON (civicrm_case_contact.case_id = civicrm_case.id
2960 AND civicrm_case.is_deleted = 0 )
2961 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
2962 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
2963 // search tag in activities
2964 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2965 $tActTable = "`civicrm_act_tag-" . $value . "`";
2966 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2967 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2969 $this->_tables
[$etActTable] =
2970 $this->_whereTables
[$etActTable] =
2971 " LEFT JOIN civicrm_activity_contact
2972 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
2973 LEFT JOIN civicrm_activity
2974 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
2975 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2976 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
2977 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
2979 $this->_where
[$grouping][] = "({$tTable}.name $op '". $value . "' OR {$tCaseTable}.name $op '". $value . "' OR {$tActTable}.name $op '". $value . "')";
2980 $this->_qill
[$grouping][] = ts('Tag %1 %2 ', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
2982 $etTable = "`civicrm_entity_tag-" . $value . "`";
2983 $tTable = "`civicrm_tag-" . $value . "`";
2984 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
2985 {$etTable}.entity_table = 'civicrm_contact' )
2986 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
2988 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
2989 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
2994 * where / qill clause for tag
3001 function tag(&$values) {
3002 list($name, $op, $value, $grouping, $wildcard) = $values;
3004 $tagNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
3005 if (is_array($value)) {
3006 if (count($value) > 1) {
3007 $this->_useDistinct
= TRUE;
3009 foreach ($value as $id => $dontCare) {
3010 $names[] = CRM_Utils_Array
::value($id, $tagNames);
3012 $names = implode(' ' . ts('or') . ' ', $names);
3013 $value = implode(',', array_keys($value));
3016 $names = CRM_Utils_Array
::value($value, $tagNames);
3020 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3021 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3023 $etTable = "`civicrm_entity_tag-" . $value . "`";
3025 if ($useAllTagTypes[2]) {
3026 $this->_tables
[$etTable] =
3027 $this->_whereTables
[$etTable] =
3028 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3030 // search tag in cases
3031 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3032 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3033 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3035 $this->_tables
[$etCaseTable] =
3036 $this->_whereTables
[$etCaseTable] =
3037 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3038 LEFT JOIN civicrm_case
3039 ON (civicrm_case_contact.case_id = civicrm_case.id
3040 AND civicrm_case.is_deleted = 0 )
3041 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3042 // search tag in activities
3043 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3044 $this->_tables
[$etActTable] =
3045 $this->_whereTables
[$etActTable] =
3046 " LEFT JOIN civicrm_activity_contact
3047 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3048 LEFT JOIN civicrm_activity
3049 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3050 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3051 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3054 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3055 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3058 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (". $value . ") OR {$etCaseTable}.tag_id $op (". $value . ") OR {$etActTable}.tag_id $op (". $value . "))";
3060 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
3062 $this->_tables
[$etTable] =
3063 $this->_whereTables
[$etTable] =
3064 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3067 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3068 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3069 $op = str_replace('EMPTY', 'NULL', $op);
3070 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3073 $this->_where
[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
3075 $this->_qill
[$grouping][] = ts('Tagged %1', array( 1 => $op)) . ' ' . $names;
3081 * where/qill clause for notes
3088 function notes(&$values) {
3089 list($name, $op, $value, $grouping, $wildcard) = $values;
3091 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3092 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3093 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3095 $this->_useDistinct
= TRUE;
3097 $this->_tables
['civicrm_note'] =
3098 $this->_whereTables
['civicrm_note'] =
3099 " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3101 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3103 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3104 if ($wildcard ||
$op == 'LIKE') {
3105 if (strpos($value, '%') === FALSE) {
3106 $value = "%$value%";
3110 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3116 if ( $noteOption %
2 == 0 ) {
3117 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3118 $label = ts('Note: Body Only');
3120 if ( $noteOption %
3 == 0 ) {
3121 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3122 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3124 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3125 $this->_qill
[$grouping][] = $label . " $op - '$n'";
3135 function nameNullOrEmptyOp($name, $op, $grouping) {
3139 $this->_where
[$grouping][] = "contact_a.$name $op";
3140 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3144 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3145 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3148 case 'IS NOT EMPTY':
3149 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3150 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3159 * where / qill clause for sort_name
3166 function sortName(&$values) {
3167 list($name, $op, $value, $grouping, $wildcard) = $values;
3169 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3170 if ( $this->nameNullOrEmptyOp( $name, $op, $grouping ) ) {
3175 $name = trim($value);
3181 $config = CRM_Core_Config
::singleton();
3185 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3188 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3189 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3191 if (substr($name, 0, 1) == '"' &&
3192 substr($name, -1, 1) == '"'
3194 //If name is encased in double quotes, the value should be taken to be the string in entirety and the
3195 $value = substr($name, 1, -1);
3196 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
3197 $wc = ($newName == 'sort_name') ?
'LOWER(contact_a.sort_name)' : 'LOWER(contact_a.display_name)';
3198 $sub[] = " ( $wc = '$value' ) ";
3199 if ($config->includeEmailInName
) {
3200 $sub[] = " ( civicrm_email.email = '$value' ) ";
3203 elseif (strpos($name, ',') !== FALSE) {
3204 // if we have a comma in the string, search for the entire string
3205 $value = $strtolower(CRM_Core_DAO
::escapeString($name));
3207 if ($config->includeWildCardInName
) {
3208 $value = "'%$value%'";
3211 $value = "'$value%'";
3216 $value = "'$value'";
3218 if ($newName == 'sort_name') {
3219 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3222 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3224 $sub[] = " ( $wc $op $value )";
3225 if ($config->includeNickNameInName
) {
3226 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3227 $sub[] = " ( $wc $op $value )";
3229 if ($config->includeEmailInName
) {
3230 $sub[] = " ( civicrm_email.email $op $value ) ";
3234 // the string should be treated as a series of keywords to be matched with match ANY OR
3235 // match ALL depending on Civi config settings (see CiviAdmin)
3237 // The Civi configuration setting can be overridden if the string *starts* with the case
3238 // insenstive strings 'AND:' or 'OR:'TO THINK ABOUT: what happens when someone searches
3239 // for the following "AND: 'a string in quotes'"? - probably nothing - it would make the
3240 // AND OR variable reduntant because there is only one search string?
3242 // Check to see if the $subGlue is overridden in the search text
3243 if (strtolower(substr($name, 0, 4)) == 'and:') {
3244 $name = substr($name, 4);
3247 if (strtolower(substr($name, 0, 3)) == 'or:') {
3248 $name = substr($name, 3);
3252 $firstChar = substr($name, 0, 1);
3253 $lastChar = substr($name, -1, 1);
3254 $quotes = array("'", '"');
3255 if ((strlen($name) > 2) && in_array($firstChar, $quotes) &&
3256 in_array($lastChar, $quotes)
3258 $name = substr($name, 1);
3259 $name = substr($name, 0, -1);
3260 $pieces = array($name);
3263 $pieces = explode(' ', $name);
3265 foreach ($pieces as $piece) {
3266 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($piece)));
3267 if (strlen($value)) {
3268 // Added If as a sanitization - without it, when you do an OR search, any string with
3269 // double spaces (i.e. " ") or that has a space after the keyword (e.g. "OR: ") will
3270 // return all contacts because it will include a condition similar to "OR contact
3271 // name LIKE '%'". It might be better to replace this with array_filter.
3272 $fieldsub = array();
3274 if ($config->includeWildCardInName
) {
3275 $value = "'%$value%'";
3278 $value = "'$value%'";
3283 $value = "'$value'";
3285 if ($newName == 'sort_name') {
3286 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3289 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3291 $fieldsub[] = " ( $wc $op $value )";
3292 if ($config->includeNickNameInName
) {
3293 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3294 $fieldsub[] = " ( $wc $op $value )";
3296 if ($config->includeEmailInName
) {
3297 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3299 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3300 // I seperated the glueing in two. The first stage should always be OR because we are searching for matches in *ANY* of these fields
3305 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3307 $this->_where
[$grouping][] = $sub;
3308 if ($config->includeEmailInName
) {
3309 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3310 $this->_qill
[$grouping][] = ts('Name or Email ') . "$op - '$name'";
3313 $this->_qill
[$grouping][] = ts('Name like') . " - '$name'";
3318 * where / qill clause for email
3325 function email(&$values) {
3326 list($name, $op, $value, $grouping, $wildcard) = $values;
3330 $config = CRM_Core_Config
::singleton();
3332 if (substr($n, 0, 1) == '"' &&
3333 substr($n, -1, 1) == '"'
3335 $n = substr($n, 1, -1);
3336 $value = strtolower(CRM_Core_DAO
::escapeString($n));
3337 $value = "'$value'";
3341 $value = strtolower($n);
3343 if (strpos($value, '%') === FALSE) {
3344 $value = "%{$value}%";
3349 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3350 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3353 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3354 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3357 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3361 * where / qill clause for phone number
3368 function phone_numeric(&$values) {
3369 list($name, $op, $value, $grouping, $wildcard) = $values;
3370 // Strip non-numeric characters; allow wildcards
3371 $number = preg_replace('/[^\d%]/', '', $value);
3373 if ( strpos($number, '%') === FALSE ) {
3374 $number = "%$number%";
3377 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3378 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3379 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3384 * where / qill clause for phone type/location
3391 function phone_option_group($values) {
3392 list($name, $op, $value, $grouping, $wildcard) = $values;
3393 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3394 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3395 $optionName = $options[$value];
3396 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3397 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3398 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3402 * where / qill clause for street_address
3409 function street_address(&$values) {
3410 list($name, $op, $value, $grouping, $wildcard) = $values;
3419 $value = strtolower($n);
3420 if (strpos($value, '%') === FALSE) {
3421 // only add wild card if not there
3422 $value = "%{$value}%";
3425 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3426 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3429 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3430 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3433 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3437 * where / qill clause for street_unit
3444 function street_number(&$values) {
3445 list($name, $op, $value, $grouping, $wildcard) = $values;
3453 if (strtolower($n) == 'odd') {
3454 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3455 $this->_qill
[$grouping][] = ts('Street Number is odd');
3457 elseif (strtolower($n) == 'even') {
3458 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3459 $this->_qill
[$grouping][] = ts('Street Number is even');
3462 $value = strtolower($n);
3464 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3465 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3468 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3472 * where / qill clause for sorting by character
3479 function sortByCharacter(&$values) {
3480 list($name, $op, $value, $grouping, $wildcard) = $values;
3482 $name = trim($value);
3483 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3484 $this->_where
[$grouping][] = $cond;
3485 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3489 * where / qill clause for including contact ids
3494 function includeContactIDs() {
3495 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3499 $contactIds = array();
3500 foreach ($this->_params
as $id => $values) {
3501 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3502 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3505 if (!empty($contactIds)) {
3506 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3511 * where / qill clause for postal code
3518 function postalCode(&$values) {
3519 // skip if the fields dont have anything to do with postal_code
3520 if (empty($this->_fields
['postal_code'])) {
3524 list($name, $op, $value, $grouping, $wildcard) = $values;
3526 // Handle numeric postal code range searches properly by casting the column as numeric
3527 if (is_numeric($value)) {
3528 $field = 'ROUND(civicrm_address.postal_code)';
3529 $val = CRM_Utils_Type
::escape($value, 'Integer');
3532 $field = 'civicrm_address.postal_code';
3533 $val = CRM_Utils_Type
::escape($value, 'String');
3536 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3538 if ($name == 'postal_code') {
3539 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3540 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3542 elseif ($name == 'postal_code_low') {
3543 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3544 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3546 elseif ($name == 'postal_code_high') {
3547 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3548 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3553 * where / qill clause for location type
3556 * @param null $status
3561 function locationType(&$values, $status = NULL) {
3562 list($name, $op, $value, $grouping, $wildcard) = $values;
3564 if (is_array($value)) {
3565 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3566 $this->_tables
['civicrm_address'] = 1;
3567 $this->_whereTables
['civicrm_address'] = 1;
3569 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3571 foreach ($value as $id) {
3572 $names[] = $locationType[$id];
3575 $this->_primaryLocation
= FALSE;
3578 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3581 return implode(' ' . ts('or') . ' ', $names);
3588 * @param bool $fromStateProvince
3592 function country(&$values, $fromStateProvince = TRUE) {
3593 list($name, $op, $value, $grouping, $wildcard) = $values;
3595 if (!$fromStateProvince) {
3596 $stateValues = $this->getWhereValues('state_province', $grouping);
3597 if (!empty($stateValues)) {
3598 // return back to caller if there are state province values
3599 // since that handles this case
3604 $countryClause = $countryQill = NULL;
3610 $this->_tables
['civicrm_address'] = 1;
3611 $this->_whereTables
['civicrm_address'] = 1;
3613 $countries = CRM_Core_PseudoConstant
::country();
3614 if (is_numeric($value)) {
3615 $countryClause = self
::buildClause(
3616 'civicrm_address.country_id',
3621 $countryName = $countries[(int ) $value];
3625 $intValues = self
::parseSearchBuilderString($value);
3626 if ($intValues && ($op == 'IN' ||
$op == 'NOT IN')) {
3627 $countryClause = self
::buildClause(
3628 'civicrm_address.country_id',
3633 $countryNames = array();
3634 foreach ($intValues as $v) {
3635 $countryNames[] = $countries[$v];
3637 $countryName = implode(',', $countryNames);
3640 $countries = CRM_Core_PseudoConstant
::country();
3641 $intVal = CRM_Utils_Array
::key($value, $countries);
3642 $countryClause = self
::buildClause(
3643 'civicrm_address.country_id',
3648 $countryName = $value;
3651 $countryQill = ts('Country') . " {$op} '$countryName'";
3653 if (!$fromStateProvince) {
3654 $this->_where
[$grouping][] = $countryClause;
3655 $this->_qill
[$grouping][] = $countryQill;
3659 if ($fromStateProvince) {
3660 if (!empty($countryClause)) {
3663 " ...AND... " . $countryQill,
3667 return array(NULL, NULL);
3673 * where / qill clause for county (if present)
3676 * @param null $status
3681 function county(&$values, $status = null) {
3682 list($name, $op, $value, $grouping, $wildcard) = $values;
3684 if (! is_array($value)) {
3685 // force the county to be an array
3686 $value = array($value);
3689 // check if the values are ids OR names of the counties
3690 $inputFormat = 'id';
3691 foreach ($value as $v) {
3692 if (!is_numeric($v)) {
3693 $inputFormat = 'name';
3701 else if ($op == '!=') {
3705 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3706 $op = str_replace('EMPTY', 'NULL', $op);
3709 if (in_array( $op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3710 $clause = "civicrm_address.county_id $op";
3712 elseif ($inputFormat == 'id') {
3713 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3715 $county = CRM_Core_PseudoConstant
::county();
3716 foreach ($value as $id) {
3717 $names[] = CRM_Utils_Array
::value($id, $county);
3721 $inputClause = array();
3722 $county = CRM_Core_PseudoConstant
::county();
3723 foreach ($value as $name) {
3724 $name = trim($name);
3725 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3727 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3730 $this->_tables
['civicrm_address'] = 1;
3731 $this->_whereTables
['civicrm_address'] = 1;
3733 $this->_where
[$grouping][] = $clause;
3735 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3737 return implode(' ' . ts('or') . ' ', $names);
3742 * where / qill clause for state/province AND country (if present)
3745 * @param null $status
3750 function stateProvince(&$values, $status = NULL) {
3751 list($name, $op, $value, $grouping, $wildcard) = $values;
3753 // quick escape for IS NULL
3754 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3757 else if (!is_array($value)) {
3758 // force the state to be an array
3759 // check if its in the mapper format!
3760 $values = self
::parseSearchBuilderString($value);
3761 if (is_array($values)) {
3765 $value = array($value);
3769 // check if the values are ids OR names of the states
3770 $inputFormat = 'id';
3772 foreach ($value as $v) {
3773 if (!is_numeric($v)) {
3774 $inputFormat = 'name';
3784 else if ($op == '!=') {
3788 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3789 $op = str_replace('EMPTY', 'NULL', $op);
3791 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3792 $stateClause = "civicrm_address.state_province_id $op";
3794 else if ($inputFormat == 'id') {
3795 if ($op != 'NOT IN') {
3798 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
3800 foreach ($value as $id) {
3801 $names[] = CRM_Core_PseudoConstant
::stateProvince($id, FALSE);
3805 $inputClause = array();
3806 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3807 foreach ($value as $name) {
3808 $name = trim($name);
3809 $inputClause[] = CRM_Utils_Array
::key($name, $stateProvince);
3811 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
3814 $this->_tables
['civicrm_address'] = 1;
3815 $this->_whereTables
['civicrm_address'] = 1;
3817 $countryValues = $this->getWhereValues('country', $grouping);
3818 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3820 if ($countryClause) {
3821 $clause = "( $stateClause AND $countryClause )";
3824 $clause = $stateClause;
3827 $this->_where
[$grouping][] = $clause;
3829 $this->_qill
[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3832 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
3837 * where / qill clause for change log
3844 function changeLog(&$values) {
3845 list($name, $op, $value, $grouping, $wildcard) = $values;
3847 $targetName = $this->getWhereValues('changed_by', $grouping);
3852 $name = trim($targetName[2]);
3853 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3854 $name = $targetName[4] ?
"%$name%" : $name;
3855 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3856 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3857 $this->_qill
[$grouping][] = ts('Modified by') . ": $name";
3863 function modifiedDates($values) {
3864 $this->_useDistinct
= TRUE;
3866 // CRM-11281, default to added date if not set
3867 $fieldTitle = ts('Added Date');
3868 $fieldName = 'created_date';
3869 foreach (array_keys($this->_params
) as $id) {
3870 if ($this->_params
[$id][0] == 'log_date') {
3871 if ($this->_params
[$id][2] == 2) {
3872 $fieldTitle = ts('Modified Date');
3873 $fieldName = 'modified_date';
3879 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3881 self
::$_openedPanes[ts('Change Log')] = TRUE;
3887 function demographics(&$values) {
3888 list($name, $op, $value, $grouping, $wildcard) = $values;
3890 if (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3892 $this->dateQueryBuilder($values,
3893 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3896 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3898 $this->dateQueryBuilder($values,
3899 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3903 self
::$_openedPanes[ts('Demographics')] = TRUE;
3909 function privacy(&$values) {
3910 list($name, $op, $value, $grouping, $wildcard) = $values;
3911 //fixed for profile search listing CRM-4633
3912 if (strpbrk($value, "[")) {
3913 $value = "'{$value}'";
3915 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3918 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3920 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3921 $title = $field ?
$field['title'] : $name;
3922 $this->_qill
[$grouping][] = "$title $op $value";
3928 function privacyOptions($values) {
3929 list($name, $op, $value, $grouping, $wildcard) = $values;
3931 if (empty($value) ||
!is_array($value)) {
3935 // get the operator and toggle values
3936 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3939 strtolower($opValues[2] == 'AND')
3944 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3946 if ($toggleValues &&
3947 $toggleValues[2] == 2
3954 foreach ($value as $dontCare => $pOption) {
3955 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
3956 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3957 $title = $field ?
$field['title'] : $pOption;
3958 $qill[] = " $title = 1 ";
3961 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
3962 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
3968 function preferredCommunication(&$values) {
3969 list($name, $op, $value, $grouping, $wildcard) = $values;
3972 if (in_array($op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3975 elseif (!is_array($value)) {
3977 $value = trim($value, ' ()');
3978 if (strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
3979 $v = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
3982 $v = explode(",", $value);
3985 foreach ($v as $item) {
3992 foreach ($value as $key => $checked) {
3999 $commPref = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
4001 $sqlValue = array();
4002 $showValue = array();
4003 $sql = "contact_a.preferred_communication_method";
4004 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
4005 $sqlValue[] = "{$sql} {$op}";
4008 foreach ($pref as $val) {
4009 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $val . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' ) ";
4010 $showValue[] = $commPref[$val];
4013 $this->_where
[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
4014 $this->_qill
[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
4018 * where / qill clause for relationship
4025 function relationship(&$values) {
4026 list($name, $op, $value, $grouping, $wildcard) = $values;
4027 if($this->_relationshipValuesAdded
){
4030 // also get values array for relation_target_name
4031 // for relatinship search we always do wildcard
4032 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4033 $relStatus = $this->getWhereValues('relation_status', $grouping);
4034 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4035 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4037 $nameClause = $name = NULL;
4039 $name = trim($targetName[2]);
4040 if (substr($name, 0, 1) == '"' &&
4041 substr($name, -1, 1) == '"'
4043 $name = substr($name, 1, -1);
4044 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4045 $nameClause = "= '$name'";
4048 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4049 $nameClause = "LIKE '%{$name}%'";
4053 $rel = explode('_', $value);
4055 self
::$_relType = $rel[1];
4056 $params = array('id' => $rel[0]);
4057 $rTypeValues = array();
4058 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
4059 if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
4060 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4061 //@todo unless we are dealing with a target group
4062 self
::$_relType = 'reciprocal';
4064 // if we are creating a temp table we build our own where for the relationship table
4065 $relationshipTempTable = NULL;
4066 if(self
::$_relType == 'reciprocal' && empty($targetGroup)) {
4068 self
::$_relationshipTempTable =
4069 $relationshipTempTable =
4070 CRM_Core_DAO
::createTempTableName( 'civicrm_rel');
4072 $where[$grouping][] = " sort_name $nameClause ";
4076 $where = &$this->_where
;
4078 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4083 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
4084 $relTypeOrg = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
4085 $relTypeHou = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Household');
4086 $allRelationshipType = array();
4087 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
4088 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
4090 if ($nameClause ||
!$targetGroup) {
4091 $this->_qill
[$grouping][] = "$allRelationshipType[$value] $name";
4095 //check to see if the target contact is in specified group
4097 //add contacts from static groups
4098 $this->_tables
['civicrm_relationship_group_contact'] =
4099 $this->_whereTables
['civicrm_relationship_group_contact'] =
4100 " 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'";
4102 "( civicrm_relationship_group_contact.group_id IN (" .
4103 implode(",", $targetGroup[2]) . ") ) ";
4105 //add contacts from saved searches
4106 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
4108 //set the group where clause
4110 $groupWhere[] = "( " . $ssWhere . " )";
4112 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4114 //Get the names of the target groups for the qill
4115 $groupNames = CRM_Core_PseudoConstant
::group();
4116 $qillNames = array();
4117 foreach ($targetGroup[2] as $groupId) {
4118 if (array_key_exists($groupId, $groupNames)) {
4119 $qillNames[] = $groupNames[$groupId];
4122 $this->_qill
[$grouping][] = "$allRelationshipType[$value] ( " . implode(", ", $qillNames) . " )";
4125 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4126 $today = date('Ymd');
4127 //check for active, inactive and all relation status
4128 if ($relStatus[2] == 0) {
4129 $where[$grouping][] = "(
4130 civicrm_relationship.is_active = 1 AND
4131 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4132 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4134 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4136 elseif ($relStatus[2] == 1) {
4137 $where[$grouping][] = "(
4138 civicrm_relationship.is_active = 0 OR
4139 civicrm_relationship.end_date < {$today} OR
4140 civicrm_relationship.start_date > {$today}
4142 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4145 //check for permissioned, non-permissioned and all permissioned relations
4146 if ($relPermission[2] == 1) {
4147 $this->_where
[$grouping][] = "(
4148 civicrm_relationship.is_permission_a_b = 1
4150 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4151 } elseif ($relPermission[2] == 2) {
4152 //non-allowed permission relationship.
4153 $this->_where
[$grouping][] = "(
4154 civicrm_relationship.is_permission_a_b = 0
4156 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4159 $this->addRelationshipDateClauses($grouping, $where);
4160 if(!empty($rType) && isset($rType->id
)){
4161 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
4163 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4164 $this->_useDistinct
= TRUE;
4165 $this->_relationshipValuesAdded
= TRUE;
4166 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4168 // @todo creating a temp table could be expanded to group filter
4169 // as even creating a temp table of all relationships is much much more efficient than
4170 // an OR in the join
4171 if($relationshipTempTable) {
4172 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4174 CREATE TEMPORARY TABLE {$relationshipTempTable}
4175 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4176 FROM civicrm_relationship
4177 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4180 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4181 FROM civicrm_relationship
4182 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4185 CRM_Core_DAO
::executeQuery($sql);
4190 * Add start & end date criteria in
4191 * @param string $grouping
4192 * @param array $where = array to add where clauses to, in case you are generating a temp table
4193 * not the main query.
4195 function addRelationshipDateClauses($grouping, &$where){
4196 $dateValues = array();
4202 foreach ($dateTypes as $dateField){
4203 $dateValueLow = $this->getWhereValues('relation_'. $dateField .'_low', $grouping);
4204 $dateValueHigh= $this->getWhereValues('relation_'. $dateField .'_high', $grouping);
4205 if(!empty($dateValueLow)){
4206 $date = date('Ymd', strtotime($dateValueLow[2]));
4207 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4208 $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);
4210 if(!empty($dateValueHigh)){
4211 $date = date('Ymd', strtotime($dateValueHigh[2]));
4212 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4213 $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);
4219 * default set of return properties
4223 * @return array derault return properties
4226 static function &defaultReturnProperties($mode = 1) {
4227 if (!isset(self
::$_defaultReturnProperties)) {
4228 self
::$_defaultReturnProperties = array();
4231 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4232 // add activity return properties
4233 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4234 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4237 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4240 if (empty(self
::$_defaultReturnProperties[$mode])) {
4241 self
::$_defaultReturnProperties[$mode] = array(
4244 'legal_identifier' => 1,
4245 'external_identifier' => 1,
4246 'contact_type' => 1,
4247 'contact_sub_type' => 1,
4249 'display_name' => 1,
4250 'preferred_mail_format' => 1,
4257 'formal_title' => 1,
4258 'communication_style_id' => 1,
4261 'street_address' => 1,
4262 'supplemental_address_1' => 1,
4263 'supplemental_address_2' => 1,
4266 'postal_code_suffix' => 1,
4267 'state_province' => 1,
4269 'world_region' => 1,
4276 'household_name' => 1,
4277 'organization_name' => 1,
4278 'deceased_date' => 1,
4283 'current_employer' => 1,
4284 // FIXME: should we use defaultHierReturnProperties() for the below?
4285 'do_not_email' => 1,
4288 'do_not_phone' => 1,
4289 'do_not_trade' => 1,
4291 'contact_is_deleted' => 1,
4292 'preferred_communication_method' => 1,
4293 'preferred_language' => 1,
4297 return self
::$_defaultReturnProperties[$mode];
4301 * get primary condition for a sql clause
4305 * @return string|NULL
4308 static function getPrimaryCondition($value) {
4309 if (is_numeric($value)) {
4310 $value = (int ) $value;
4311 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4317 * wrapper for a simple search query
4319 * @param array $params
4320 * @param array $returnProperties
4321 * @param bool $count
4326 static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4327 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4328 list($select, $from, $where, $having) = $query->query();
4330 return "$select $from $where $having";
4334 * These are stub comments as this function needs more explanation - particularly in terms of how it
4335 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4337 * This function was originally written as a wrapper for the api query but is called from multiple places
4338 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4339 * but it is unclear as to whehter that is historical or there is a reason
4340 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4342 * @param array $params
4343 * @param array $returnProperties
4344 * @param null $fields
4345 * @param string $sort
4346 * @param int $offset
4347 * @param int $row_count
4348 * @param bool $smartGroupCache
4349 * @param bool $count return count obnly
4350 * @param bool $skipPermissions Should permissions be ignored or should the logged in user's permissions be applied
4352 * @params bool $smartGroupCache ?? update smart group cache?
4357 static function apiQuery(
4359 $returnProperties = NULL,
4364 $smartGroupCache = TRUE,
4366 $skipPermissions = TRUE
4369 $query = new CRM_Contact_BAO_Query(
4370 $params, $returnProperties,
4371 NULL, TRUE, FALSE, 1,
4373 TRUE, $smartGroupCache
4376 //this should add a check for view deleted if permissions are enabled
4377 if ($skipPermissions){
4378 $query->_skipDeleteClause
= TRUE;
4380 $query->generatePermissionClause(FALSE, $count);
4382 // note : this modifies _fromClause and _simpleFromClause
4383 $query->includePseudoFieldsJoin($sort);
4385 list($select, $from, $where, $having) = $query->query($count);
4387 $options = $query->_options
;
4388 if(!empty($query->_permissionWhereClause
)){
4389 if (empty($where)) {
4390 $where = "WHERE $query->_permissionWhereClause";
4393 $where = "$where AND $query->_permissionWhereClause";
4397 $sql = "$select $from $where $having";
4400 if ($query->_useGroupBy
) {
4401 $sql .= ' GROUP BY contact_a.id';
4403 if (!empty($sort)) {
4404 $sort = CRM_Utils_Type
::escape($sort, 'String');
4405 $sql .= " ORDER BY $sort ";
4407 if ($row_count > 0 && $offset >= 0) {
4408 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4409 $rowCount = CRM_Utils_Type
::escape($row_count, 'Int');
4410 $sql .= " LIMIT $offset, $row_count ";
4413 $dao = CRM_Core_DAO
::executeQuery($sql);
4416 while ($dao->fetch()) {
4418 $noRows = $dao->rowCount
;
4420 return array($noRows,NULL);
4422 $val = $query->store($dao);
4423 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4425 if (!empty($convertedVals)) {
4426 $val = array_replace_recursive($val, $convertedVals);
4428 $values[$dao->contact_id
] = $val;
4431 return array($values, $options);
4435 * create and query the db for an contact search
4437 * @param int $offset the offset for the query
4438 * @param int $rowCount the number of rows to return
4439 * @param string $sort the order by string
4440 * @param boolean $count is this a count only query ?
4441 * @param boolean $includeContactIds should we include contact ids?
4442 * @param boolean $sortByChar if true returns the distinct array of first characters for search results
4443 * @param boolean $groupContacts if true, return only the contact ids
4444 * @param boolean $returnQuery should we return the query as a string
4445 * @param string $additionalWhereClause if the caller wants to further restrict the search (used for components)
4446 * @param null $sortOrder
4447 * @param string $additionalFromClause should be clause with proper joins, effective to reduce where clause load.
4449 * @param bool $skipOrderAndLimit
4451 * @return CRM_Core_DAO
4454 function searchQuery(
4455 $offset = 0, $rowCount = 0, $sort = NULL,
4456 $count = FALSE, $includeContactIds = FALSE,
4457 $sortByChar = FALSE, $groupContacts = FALSE,
4458 $returnQuery = FALSE,
4459 $additionalWhereClause = NULL, $sortOrder = NULL,
4460 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4463 if ($includeContactIds) {
4464 $this->_includeContactIds
= TRUE;
4465 $this->_whereClause
= $this->whereClause();
4468 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4470 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4471 // and that contact happens to be deleted, set $onlyDeleted to true
4472 foreach ($this->_params
as $values) {
4473 $name = CRM_Utils_Array
::value(0, $values);
4474 $op = CRM_Utils_Array
::value(1, $values);
4475 $value = CRM_Utils_Array
::value(2, $values);
4476 if ($name == 'contact_id' and $op == '=') {
4477 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4478 $onlyDeleted = TRUE;
4484 // building the query string
4487 if (isset($this->_groupByComponentClause
)) {
4488 $groupBy = $this->_groupByComponentClause
;
4490 elseif ($this->_useGroupBy
) {
4491 $groupBy = ' GROUP BY contact_a.id';
4494 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4495 $groupBy = 'GROUP BY civicrm_activity.id ';
4498 $order = $orderBy = $limit = '';
4500 $config = CRM_Core_Config
::singleton();
4501 if ($config->includeOrderByClause ||
4502 isset($this->_distinctComponentClause
)
4505 if (is_string($sort)) {
4509 $orderBy = trim($sort->orderBy());
4511 if (!empty($orderBy)) {
4512 // this is special case while searching for
4513 // change log CRM-1718
4514 if (preg_match('/sort_name/i', $orderBy)) {
4515 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4518 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
4519 $order = " ORDER BY $orderBy";
4522 $sortOrder = CRM_Utils_Type
::escape($sortOrder, 'String');
4523 $order .= " $sortOrder";
4526 // always add contact_a.id to the ORDER clause
4527 // so the order is deterministic
4528 if (strpos('contact_a.id', $order) === FALSE) {
4529 $order .= ", contact_a.id";
4533 elseif ($sortByChar) {
4534 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4537 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4541 // hack for order clause
4543 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4544 $fieldOrder = explode(' ', $fieldStr);
4545 $field = $fieldOrder[0];
4551 $this->_whereTables
["civicrm_address"] = 1;
4552 $order = str_replace($field, "civicrm_address.{$field}", $order);
4556 case 'state_province':
4557 $this->_whereTables
["civicrm_{$field}"] = 1;
4558 $order = str_replace($field, "civicrm_{$field}.name", $order);
4562 $this->_whereTables
["civicrm_email"] = 1;
4563 $order = str_replace($field, "civicrm_email.{$field}", $order);
4567 //CRM-12565 add "`" around $field if it is a pseudo constant
4568 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
4569 if (!empty($value['element']) && $value['element'] == $field) {
4570 $order = str_replace($field, "`{$field}`", $order);
4574 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4575 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4579 if ($rowCount > 0 && $offset >= 0) {
4580 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4581 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4582 $limit = " LIMIT $offset, $rowCount ";
4586 // note : this modifies _fromClause and _simpleFromClause
4587 $this->includePseudoFieldsJoin($sort);
4589 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4591 if ($additionalWhereClause) {
4592 $where = $where . ' AND ' . $additionalWhereClause;
4595 //additional from clause should be w/ proper joins.
4596 if ($additionalFromClause) {
4597 $from .= "\n" . $additionalFromClause;
4600 // if we are doing a transform, do it here
4601 // use the $from, $where and $having to get the contact ID
4602 if ($this->_displayRelationshipType
) {
4603 $this->filterRelatedContacts($from, $where, $having);
4606 if ($skipOrderAndLimit) {
4607 $query = "$select $from $where $having $groupBy";
4610 $query = "$select $from $where $having $groupBy $order $limit";
4617 return CRM_Core_DAO
::singleValueQuery($query);
4620 $dao = CRM_Core_DAO
::executeQuery($query);
4621 if ($groupContacts) {
4623 while ($dao->fetch()) {
4626 return implode(',', $ids);
4633 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4635 * @param string $cacheKey
4636 * @param int $offset
4637 * @param int $rowCount
4638 * @param bool $includeContactIds
4639 * @return CRM_Core_DAO
4641 function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4642 $this->_includeContactIds
= $includeContactIds;
4643 list($select, $from, $where) = $this->query();
4644 $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);
4645 $order = " ORDER BY pnc.id";
4646 $groupBy = " GROUP BY contact_a.id";
4647 $limit = " LIMIT $offset, $rowCount";
4648 $query = "$select $from $where $groupBy $order $limit";
4650 return CRM_Core_DAO
::executeQuery($query);
4654 * Populate $this->_permissionWhereClause with permission related clause and update other
4655 * query related properties.
4657 * Function calls ACL permission class and hooks to filter the query appropriately
4659 * Note that these 2 params were in the code when extracted from another function
4660 * and a second round extraction would be to make them properties of the class
4662 * @param bool $onlyDeleted Only get deleted contacts
4663 * @param bool $count Return Count only
4667 function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4668 if (!$this->_skipPermission
) {
4669 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4670 CRM_Core_Permission
::VIEW
,
4672 $this->_whereTables
,
4675 $this->_skipDeleteClause
4678 // regenerate fromClause since permission might have added tables
4679 if ($this->_permissionWhereClause
) {
4680 //fix for row count in qill (in contribute/membership find)
4682 $this->_useDistinct
= TRUE;
4685 if (empty($this->_fromClause
)) {
4686 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4689 if (empty($this->_simpleFromClause
)) {
4690 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4695 // add delete clause if needed even if we are skipping permission
4697 if (!$this->_skipDeleteClause
) {
4698 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4699 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4703 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4712 function setSkipPermission($val) {
4713 $this->_skipPermission
= $val;
4717 * @param null $context
4721 function &summaryContribution($context = NULL) {
4722 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4726 SELECT COUNT( conts.total_amount ) as total_count,
4727 SUM( conts.total_amount ) as total_amount,
4728 AVG( conts.total_amount ) as total_avg,
4729 conts.currency as currency";
4730 if($this->_permissionWhereClause
) {
4731 $where .= " AND " . $this->_permissionWhereClause
;
4733 if ($context == 'search') {
4734 $where .= " AND contact_a.is_deleted = 0 ";
4737 // make sure contribution is completed - CRM-4989
4738 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4742 $summary['total'] = array();
4743 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4745 $query = "$select FROM (
4746 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $completedWhere
4747 GROUP BY civicrm_contribution.id
4751 $dao = CRM_Core_DAO
::executeQuery($query);
4753 $summary['total']['count'] = 0;
4754 $summary['total']['amount'] = $summary['total']['avg'] = array();
4755 while ($dao->fetch()) {
4756 $summary['total']['count'] +
= $dao->total_count
;
4757 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4758 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4760 if (!empty($summary['total']['amount'])) {
4761 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4762 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4765 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4768 // soft credit summary
4769 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
4770 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
4773 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
4774 GROUP BY civicrm_contribution_soft.id
4777 $dao = CRM_Core_DAO
::executeQuery($query);
4778 $summary['soft_credit']['count'] = 0;
4779 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
4780 while ($dao->fetch()) {
4781 $summary['soft_credit']['count'] +
= $dao->total_count
;
4782 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4783 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4785 if (!empty($summary['soft_credit']['amount'])) {
4786 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
4787 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
4790 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
4795 //@todo - this could be one query using the IF in mysql - eg
4796 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
4797 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
4798 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
4799 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
4800 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
4801 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
4802 // FROM civicrm_contact contact_a
4803 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
4804 // WHERE ( ... where clause....
4805 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
4809 SELECT COUNT( conts.total_amount ) as cancel_count,
4810 SUM( conts.total_amount ) as cancel_amount,
4811 AVG( conts.total_amount ) as cancel_avg,
4812 conts.currency as currency";
4814 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4815 if ($context == 'search') {
4816 $where .= " AND contact_a.is_deleted = 0 ";
4819 $query = "$select FROM (
4820 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
4821 GROUP BY civicrm_contribution.id
4825 $dao = CRM_Core_DAO
::executeQuery($query);
4828 if ($dao->fetch()) {
4829 $summary['cancel']['count'] = $dao->cancel_count
;
4830 $summary['cancel']['amount'] = $dao->cancel_amount
;
4831 $summary['cancel']['avg'] = $dao->cancel_avg
;
4835 $summary['cancel']['count'] = 0;
4836 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4837 while ($dao->fetch()) {
4838 $summary['cancel']['count'] +
= $dao->cancel_count
;
4839 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4840 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4842 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4843 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
4850 * getter for the qill object
4856 return $this->_qill
;
4860 * default set of return default hier return properties
4865 static function &defaultHierReturnProperties() {
4866 if (!isset(self
::$_defaultHierReturnProperties)) {
4867 self
::$_defaultHierReturnProperties = array(
4870 'legal_identifier' => 1,
4871 'external_identifier' => 1,
4872 'contact_type' => 1,
4873 'contact_sub_type' => 1,
4875 'display_name' => 1,
4882 'formal_title' => 1,
4883 'communication_style_id' => 1,
4884 'email_greeting' => 1,
4885 'postal_greeting' => 1,
4889 'preferred_communication_method' => 1,
4890 'do_not_phone' => 1,
4891 'do_not_email' => 1,
4894 'do_not_trade' => 1,
4897 '1' => array('location_type' => 1,
4898 'street_address' => 1,
4900 'state_province' => 1,
4902 'postal_code_suffix' => 1,
4905 'phone-Mobile' => 1,
4918 'location_type' => 1,
4919 'street_address' => 1,
4921 'state_province' => 1,
4923 'postal_code_suffix' => 1,
4926 'phone-Mobile' => 1,
4940 return self
::$_defaultHierReturnProperties;
4947 * @param $dbFieldName
4948 * @param $fieldTitle
4949 * @param bool $appendTimeStamp
4951 function dateQueryBuilder(
4952 &$values, $tableName, $fieldName,
4953 $dbFieldName, $fieldTitle,
4954 $appendTimeStamp = TRUE
4956 list($name, $op, $value, $grouping, $wildcard) = $values;
4962 if ($name == "{$fieldName}_low" ||
4963 $name == "{$fieldName}_high"
4965 if (isset($this->_rangeCache
[$fieldName])) {
4968 $this->_rangeCache
[$fieldName] = 1;
4970 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4972 if ($name == $fieldName . '_low') {
4974 $firstPhrase = ts('greater than or equal to');
4975 $firstDate = CRM_Utils_Date
::processDate($value);
4977 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4978 if (!empty($secondValues) && $secondValues[2]) {
4980 $secondPhrase = ts('less than or equal to');
4981 $secondValue = $secondValues[2];
4983 if ($appendTimeStamp && strlen($secondValue) == 10) {
4984 $secondValue .= ' 23:59:59';
4986 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4989 elseif ($name == $fieldName . '_high') {
4991 $firstPhrase = ts('less than or equal to');
4993 if ($appendTimeStamp && strlen($value) == 10) {
4994 $value .= ' 23:59:59';
4996 $firstDate = CRM_Utils_Date
::processDate($value);
4998 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4999 if (!empty($secondValues) && $secondValues[2]) {
5001 $secondPhrase = ts('greater than or equal to');
5002 $secondValue = $secondValues[2];
5003 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5007 if (!$appendTimeStamp) {
5008 $firstDate = substr($firstDate, 0, 8);
5010 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5013 if (!$appendTimeStamp) {
5014 $secondDate = substr($secondDate, 0, 8);
5016 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5019 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5021 $this->_where
[$grouping][] = "
5022 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5023 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5025 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5028 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5029 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5033 if ($name == $fieldName) {
5037 $date = CRM_Utils_Date
::processDate($value);
5039 if (!$appendTimeStamp) {
5040 $date = substr($date, 0, 8);
5043 $format = CRM_Utils_Date
::customFormat($date);
5046 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'";
5049 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op";
5051 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5052 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$format\"";
5060 * @param $dbFieldName
5061 * @param $fieldTitle
5062 * @param null $options
5064 function numberRangeBuilder(&$values,
5065 $tableName, $fieldName,
5066 $dbFieldName, $fieldTitle,
5069 list($name, $op, $value, $grouping, $wildcard) = $values;
5071 if ($name == "{$fieldName}_low" ||
5072 $name == "{$fieldName}_high"
5074 if (isset($this->_rangeCache
[$fieldName])) {
5077 $this->_rangeCache
[$fieldName] = 1;
5079 $secondOP = $secondPhrase = $secondValue = NULL;
5081 if ($name == "{$fieldName}_low") {
5083 $firstPhrase = ts('greater than');
5085 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5086 if (!empty($secondValues)) {
5088 $secondPhrase = ts('less than');
5089 $secondValue = $secondValues[2];
5094 $firstPhrase = ts('less than');
5096 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5097 if (!empty($secondValues)) {
5099 $secondPhrase = ts('greater than');
5100 $secondValue = $secondValues[2];
5105 $this->_where
[$grouping][] = "
5106 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5107 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5109 $displayValue = $options ?
$options[$value] : $value;
5110 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5112 $this->_qill
[$grouping][] =
5113 "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5116 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5117 $displayValue = $options ?
$options[$value] : $value;
5118 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5120 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5125 if ($name == $fieldName) {
5129 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5131 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5132 $displayValue = $options ?
$options[$value] : $value;
5133 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5140 * Given the field name, operator, value & its data type
5141 * builds the where Clause for the query
5142 * used for handling 'IS NULL'/'IS NOT NULL' operators
5144 * @param string $field fieldname
5145 * @param string $op operator
5146 * @param string $value value
5147 * @param string $dataType data type of the field
5149 * @return string where clause for the query
5152 static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5154 $clause = "$field $op";
5162 $clause = " (NULLIF($field, '') IS NULL) ";
5165 case 'IS NOT EMPTY':
5166 $clause = " (NULLIF($field, '') IS NOT NULL) ";
5171 if (isset($dataType)) {
5172 if (is_array($value)) {
5176 $value = CRM_Utils_Type
::escape($value, "String");
5177 $values = explode(',', CRM_Utils_Array
::value(0, explode(')', CRM_Utils_Array
::value(1, explode('(', $value)))));
5179 // supporting multiple values in IN clause
5181 foreach ($values as $v) {
5183 $val[] = "'" . CRM_Utils_Type
::escape($v, $dataType) . "'";
5185 $value = "(" . implode($val, ",") . ")";
5187 return "$clause $value";
5190 if (empty($dataType)) {
5191 $dataType = 'String';
5194 $value = CRM_Utils_Type
::escape($value, $dataType);
5195 // if we don't have a dataType we should assume
5196 if ($dataType == 'String' ||
$dataType == 'Text') {
5197 $value = "'" . strtolower($value) . "'";
5199 return "$clause $value";
5204 * @param bool $reset
5208 function openedSearchPanes($reset = FALSE) {
5209 if (!$reset ||
empty($this->_whereTables
)) {
5210 return self
::$_openedPanes;
5213 // pane name to table mapper
5214 $panesMapper = array(
5215 ts('Contributions') => 'civicrm_contribution',
5216 ts('Memberships') => 'civicrm_membership',
5217 ts('Events') => 'civicrm_participant',
5218 ts('Relationships') => 'civicrm_relationship',
5219 ts('Activities') => 'civicrm_activity',
5220 ts('Pledges') => 'civicrm_pledge',
5221 ts('Cases') => 'civicrm_case',
5222 ts('Grants') => 'civicrm_grant',
5223 ts('Address Fields') => 'civicrm_address',
5224 ts('Notes') => 'civicrm_note',
5225 ts('Change Log') => 'civicrm_log',
5226 ts('Mailings') => 'civicrm_mailing_event_queue',
5228 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5230 foreach (array_keys($this->_whereTables
) as $table) {
5231 if ($panName = array_search($table, $panesMapper)) {
5232 self
::$_openedPanes[$panName] = TRUE;
5236 return self
::$_openedPanes;
5242 function setOperator($operator) {
5243 $validOperators = array('AND', 'OR');
5244 if (!in_array($operator, $validOperators)) {
5247 $this->_operator
= $operator;
5253 function getOperator() {
5254 return $this->_operator
;
5262 function filterRelatedContacts(&$from, &$where, &$having) {
5263 static $_rTypeProcessed = NULL;
5264 static $_rTypeFrom = NULL;
5265 static $_rTypeWhere = NULL;
5267 if (!$_rTypeProcessed) {
5268 $_rTypeProcessed = TRUE;
5270 // create temp table with contact ids
5271 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5272 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5273 CRM_Core_DAO
::executeQuery($sql);
5276 REPLACE INTO $tableName ( contact_id )
5282 CRM_Core_DAO
::executeQuery($sql);
5284 $qillMessage = ts('Contacts with a Relationship Type of: ');
5285 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5287 if (is_numeric($this->_displayRelationshipType
)) {
5288 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5290 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5291 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5294 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5295 AND displayRelType.is_active = 1
5299 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5300 if ($dirOne == 'a') {
5301 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5303 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5304 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5308 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5310 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5311 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5315 WHERE displayRelType.relationship_type_id = $relType
5316 AND displayRelType.is_active = 1
5319 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5322 if (strpos($from, $_rTypeFrom) === FALSE) {
5323 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5324 // this happens when we have an event_type in the quert (CRM-7969)
5325 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5326 $from .= $_rTypeFrom;
5327 $where = $_rTypeWhere;
5338 static function caseImportant( $op ) {
5340 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5344 * @param $returnProperties
5349 static function componentPresent( &$returnProperties, $prefix ) {
5350 foreach ($returnProperties as $name => $dontCare ) {
5351 if (substr($name, 0, strlen($prefix)) == $prefix) {
5359 * Builds the necessary structures for all fields that are similar to option value lookups
5361 * @param $name string the name of the field
5362 * @param $op string the sql operator, this function should handle ALL SQL operators
5363 * @param $value string|integer|array depends on the operator and who's calling the query builder
5364 * @param $grouping int the index where to place the where clause
5365 * @param $selectValues
5366 * @param $field array an array that contains various properties of the field identified by $name
5367 * @param $label string The label for this field element
5368 * @param $dataType string The data type for this element
5370 * @param bool $useIDsOnly
5372 * @internal param array $selectValue the key value pairs for this element. This allows us to use this function for things besides option-value pairs
5373 * @return void adds the where clause and qill to the query object
5375 function optionValueQuery(
5383 $dataType = 'String',
5387 if (!empty($selectValues) && !is_array($value) && !empty($selectValues[$value])) {
5388 $qill = $selectValues[$value];
5394 $pseudoFields = array('email_greeting', 'postal_greeting', 'addressee', 'gender_id', 'prefix_id', 'suffix_id', 'communication_style_id');
5396 if (is_numeric($value)) {
5397 $qill = $selectValues[(int ) $value];
5399 elseif ($op == 'IN' ||
$op == 'NOT IN') {
5400 if (is_array($value)) {
5402 $newValues = array();
5403 foreach ($value as $k => $v) {
5404 $intVals[$k] = (int) $k;
5405 $newValues[] = $selectValues[(int) $k];
5408 $value = (in_array($name, $pseudoFields)) ?
$intVals : $newValues;
5409 $qill = implode(', ', $newValues);
5412 elseif (!array_key_exists($value, $selectValues)) {
5413 // its a string, lets get the int value
5414 $value = array_search($value, $selectValues);
5417 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5418 if ($tableName == 'civicrm_contact') {
5419 $wc = "contact_a.$fieldName";
5422 $wc = "$tableName.id";
5426 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5429 if (in_array($name, $pseudoFields)) {
5430 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5431 $wc = "contact_a.{$name}_id";
5433 $dataType = 'Positive';
5434 $value = (!$value) ?
0 : $value;
5437 $this->_qill
[$grouping][] = $label . " $op '$qill'";
5438 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' ||
$op == 'RLIKE')) ?
'=' : $op;
5439 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5443 * function to check and explode a user defined numeric string into an array
5444 * this was the protocol used by search builder in the old old days before we had
5445 * super nice js widgets to do the hard work
5447 * @param string $string
5448 * @param string $dataType the dataType we should check for the values, default integer
5450 * @return bool|array if string does not match the patter
5451 * array of numeric values if string does match the pattern
5454 static function parseSearchBuilderString($string, $dataType = 'Integer') {
5455 $string = trim($string);
5456 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5460 $string = substr($string, 1, -1);
5461 $values = explode(',', $string);
5462 if (empty($values)) {
5466 $returnValues = array();
5467 foreach ($values as $v) {
5468 if ($dataType == 'Integer' && ! is_numeric($v)) {
5471 else if ($dataType == 'String' && ! is_string($v)) {
5474 $returnValues[] = trim($v);
5477 if (empty($returnValues)) {
5481 return $returnValues;
5485 * convert the pseudo constants id's to their names
5487 * @param CRM_Core_DAO dao
5488 * @param bool $return
5492 function convertToPseudoNames(&$dao, $return = FALSE) {
5493 if (empty($this->_pseudoConstantsSelect
)) {
5497 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5498 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5502 if (property_exists($dao, $value['idCol'])) {
5503 $val = $dao->$value['idCol'];
5505 if (CRM_Utils_System
::isNull($val)) {
5508 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5510 $idColumn = "{$key}_id";
5511 $dao->$idColumn = $val;
5513 if ($key == 'state_province_name') {
5514 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5517 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5520 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5521 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5523 // FIX ME: we should potentially move this to component Query and write a wrapper function that
5524 // handles pseudoconstant fixes for all component
5525 elseif ($value['pseudoField'] == 'participant_role') {
5526 $viewRoles = array();
5527 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val) as $k => $v) {
5528 $viewRoles[] = CRM_Event_PseudoConstant
::participantRole($v);
5530 $dao->$key = implode(', ', $viewRoles);
5533 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5534 $dao->$key = $labels[$val];
5537 // return converted values in array format
5539 if (strpos($key, '-') !== FALSE) {
5540 $keyVal = explode('-', $key);
5541 $current = &$values;
5542 $lastElement = array_pop($keyVal);
5543 foreach ($keyVal as $v) {
5544 if (!array_key_exists($v, $current)) {
5545 $current[$v] = array();
5547 $current = &$current[$v];
5549 $current[$lastElement] = $dao->$key;
5552 $values[$key] = $dao->$key;
5561 * include pseudo fields LEFT JOIN
5562 * @param string|array $sort can be a object or string
5566 function includePseudoFieldsJoin($sort) {
5567 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5570 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5573 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5574 if (!empty($value['table'])) {
5575 $regex = "/({$value['table']}\.|{$name})/";
5576 if (preg_match($regex, $sort)) {
5577 $this->_elemnt
[$value['element']] = 1;
5578 $this->_select
[$value['element']] = $value['select'];
5579 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5580 $present[$value['table']] = $value['join'];
5584 $presentSimpleFrom = $present;
5586 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5587 array_key_exists('civicrm_country', $presentSimpleFrom)) {
5588 unset($presentSimpleFrom['civicrm_country']);
5590 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5591 array_key_exists('civicrm_country', $present)) {
5592 unset($present['civicrm_country']);
5595 $presentClause = $presentSimpleFromClause = NULL;
5596 if (!empty($present)) {
5597 $presentClause = implode(' ', $present);
5599 if (!empty($presentSimpleFrom)) {
5600 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5603 $this->_fromClause
= $this->_fromClause
. $presentClause;
5604 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5606 return array($presentClause, $presentSimpleFromClause);