3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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
89 * The set of output params
93 public $_returnProperties;
103 * The name of the elements that are in the select clause
104 * used to extract the values
111 * The tables involved in the query
118 * The table involved in the where clause
122 public $_whereTables;
137 public $_whereClause;
140 * Additional permission Where Clause
145 public $_permissionWhereClause;
156 * Additional permission from clause
161 public $_permissionFromClause;
164 * The from clause for the simple select and alphabetical
169 public $_simpleFromClause;
180 * The english language version of the query
187 * All the fields that could potentially be involved in
195 * The cache to translate the option values into labels
202 * Are we in search mode
206 public $_search = TRUE;
209 * Should we skip permission checking
213 public $_skipPermission = FALSE;
216 * Should we skip adding of delete clause
220 public $_skipDeleteClause = FALSE;
223 * Are we in strict mode (use equality over LIKE)
227 public $_strict = FALSE;
230 * What operator to use to group the clauses
234 public $_operator = 'AND';
239 * Should we only search on primary location
243 public $_primaryLocation = TRUE;
246 * Are contact ids part of the query
250 public $_includeContactIds = FALSE;
253 * Should we use the smart group cache
257 public $_smartGroupCache = TRUE;
260 * Should we display contacts with a specific relationship type
264 public $_displayRelationshipType = NULL;
267 * Reference to the query object for custom values
271 public $_customQuery;
274 * Should we enable the distinct clause, used if we are including
275 * more than one group
279 public $_useDistinct = FALSE;
282 * Should we just display one contact record
284 public $_useGroupBy = FALSE;
287 * The relationship type direction
300 static $_activityRole;
303 * Consider the component activity type
304 * during activity search.
309 static $_considerCompActivities;
312 * Consider with contact activities only,
313 * during activity search.
318 static $_withContactActivitiesOnly;
321 * Use distinct component clause for component searches
325 public $_distinctComponentClause;
327 public $_rowCountClause;
330 * Use groupBy component clause for component searches
334 public $_groupByComponentClause;
337 * Track open panes, useful in advance search
342 public static $_openedPanes = array();
345 * For search builder - which custom fields are location-dependent
348 public $_locationSpecificCustomFields = array();
351 * The tables which have a dependency on location and/or address
356 static $_dependencies = array(
357 'civicrm_state_province' => 1,
358 'civicrm_country' => 1,
359 'civicrm_county' => 1,
360 'civicrm_address' => 1,
361 'civicrm_location_type' => 1,
365 * List of location specific fields
367 static $_locationSpecificFields = array(
372 'supplemental_address_1',
373 'supplemental_address_2',
376 'postal_code_suffix',
389 * Remember if we handle either end of a number or date range
390 * so we can skip the other
392 protected $_rangeCache = array();
394 * Set to true when $this->relationship is run to avoid adding twice
397 protected $_relationshipValuesAdded = FALSE;
400 * Set to the name of the temp table if one has been created
403 static $_relationshipTempTable = NULL;
405 public $_pseudoConstantsSelect = array();
408 * Class constructor which also does all the work
410 * @param array $params
411 * @param array $returnProperties
412 * @param array $fields
413 * @param bool $includeContactIds
414 * @param bool $strict
415 * @param bool|int $mode - mode the search is operating on
417 * @param bool $skipPermission
418 * @param bool $searchDescendentGroups
419 * @param bool $smartGroupCache
420 * @param null $displayRelationshipType
421 * @param string $operator
423 * @return \CRM_Contact_BAO_Query
426 function __construct(
427 $params = NULL, $returnProperties = NULL, $fields = NULL,
428 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
429 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
430 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
433 $this->_params
= &$params;
434 if ($this->_params
== NULL) {
435 $this->_params
= array();
438 if (empty($returnProperties)) {
439 $this->_returnProperties
= self
::defaultReturnProperties($mode);
442 $this->_returnProperties
= &$returnProperties;
445 $this->_includeContactIds
= $includeContactIds;
446 $this->_strict
= $strict;
447 $this->_mode
= $mode;
448 $this->_skipPermission
= $skipPermission;
449 $this->_smartGroupCache
= $smartGroupCache;
450 $this->_displayRelationshipType
= $displayRelationshipType;
451 $this->setOperator($operator);
454 $this->_fields
= &$fields;
455 $this->_search
= FALSE;
456 $this->_skipPermission
= TRUE;
459 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE);
461 $fields = CRM_Core_Component
::getQueryFields();
462 unset($fields['note']);
463 $this->_fields
= array_merge($this->_fields
, $fields);
465 // add activity fields
466 $fields = CRM_Activity_BAO_Activity
::exportableFields();
467 $this->_fields
= array_merge($this->_fields
, $fields);
469 // add any fields provided by hook implementers
470 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
471 $this->_fields
= array_merge($this->_fields
, $extFields);
474 // basically do all the work once, and then reuse it
479 * Function which actually does all the work for the constructor
483 public 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 public 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
)
547 $this->_params
[] = array(
548 'contact_is_deleted',
558 foreach ($this->_params
as $value) {
559 if (empty($value[0])) {
562 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
564 if (!array_key_exists($cfID, $this->_cfIDs
)) {
565 $this->_cfIDs
[$cfID] = array();
567 // Set wildcard value based on "and/or" selection
568 foreach ($this->_params
as $key => $param) {
569 if ($param[0] == $value[0] . '_operator') {
570 $value[4] = $param[2] == 'or';
574 $this->_cfIDs
[$cfID][] = $value;
577 if (!array_key_exists($value[0], $this->_paramLookup
)) {
578 $this->_paramLookup
[$value[0]] = array();
580 $this->_paramLookup
[$value[0]][] = $value;
585 * Some composite fields do not appear in the fields array
586 * hack to make them part of the query
590 public 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
609 public function selectClause() {
611 $this->addSpecialFields();
613 foreach ($this->_fields
as $name => $field) {
614 // skip component fields
615 // there are done by the alter query below
616 // and need not be done on every field
618 (substr($name, 0, 12) == 'participant_') ||
619 (substr($name, 0, 7) == 'pledge_') ||
620 (substr($name, 0, 5) == 'case_')
625 // redirect to activity select clause
627 (substr($name, 0, 9) == 'activity_') ||
628 ($name == 'parent_id')
630 CRM_Activity_BAO_Query
::select($this);
634 // if this is a hierarchical name, we ignore it
635 $names = explode('-', $name);
636 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
640 // make an exception for special cases, to add the field in select clause
641 $makeException = FALSE;
643 //special handling for groups/tags
644 if (in_array($name, array('groups', 'tags', 'notes'))
645 && isset($this->_returnProperties
[substr($name, 0, -1)])
647 $makeException = TRUE;
650 // since note has 3 different options we need special handling
651 // note / note_subject / note_body
652 if ($name == 'notes') {
653 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
654 if (isset($this->_returnProperties
[$noteField])) {
655 $makeException = TRUE;
661 if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id', 'communication_style_id'))) {
662 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
663 $makeException = TRUE;
667 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
668 if (!empty($this->_paramLookup
[$name]) ||
!empty($this->_returnProperties
[$name]) ||
672 // add to cfIDs array if not present
673 if (!array_key_exists($cfID, $this->_cfIDs
)) {
674 $this->_cfIDs
[$cfID] = array();
677 elseif (isset($field['where'])) {
678 list($tableName, $fieldName) = explode('.', $field['where'], 2);
679 if (isset($tableName)) {
680 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
681 $this->_tables
['civicrm_address'] = 1;
682 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
683 $this->_element
['address_id'] = 1;
686 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
687 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
689 if ($tableName == 'im_provider') {
690 CRM_Core_OptionValue
::select($this);
693 if (in_array($tableName,
694 array('email_greeting', 'postal_greeting', 'addressee'))) {
695 $this->_element
["{$name}_id"] = 1;
696 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
697 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
698 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
699 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
701 if ($tableName == 'email_greeting') {
702 $this->_pseudoConstantsSelect
[$name]['join'] =
703 " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
704 $this->_pseudoConstantsSelect
[$name]['join'] .=
705 " 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 ) ";
707 elseif ($tableName == 'postal_greeting') {
708 $this->_pseudoConstantsSelect
[$name]['join'] =
709 " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
710 $this->_pseudoConstantsSelect
[$name]['join'] .=
711 " 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 ) ";
713 elseif ($tableName == 'addressee') {
714 $this->_pseudoConstantsSelect
[$name]['join'] =
715 " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
716 $this->_pseudoConstantsSelect
[$name]['join'] .=
717 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
719 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
722 $greetField = "{$name}_display";
723 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
724 $this->_element
[$greetField] = 1;
726 $greetField = "{$name}_custom";
727 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
728 $this->_element
[$greetField] = 1;
732 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
733 $this->_tables
[$tableName] = 1;
736 // also get the id of the tableName
737 $tName = substr($tableName, 8);
738 if (in_array($tName, array('country', 'state_province', 'county'))) {
739 if ($tName == 'state_province') {
740 $this->_pseudoConstantsSelect
['state_province_name'] =
742 'pseudoField' => "{$tName}",
743 'idCol' => "{$tName}_id",
744 'bao' => 'CRM_Core_BAO_Address',
745 'table' => "civicrm_{$tName}",
746 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id "
749 $this->_pseudoConstantsSelect
[$tName] =
751 'pseudoField' => 'state_province_abbreviation',
752 'idCol' => "{$tName}_id",
753 'table' => "civicrm_{$tName}",
754 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id "
758 $this->_pseudoConstantsSelect
[$name] =
760 'pseudoField' => "{$tName}_id",
761 'idCol' => "{$tName}_id",
762 'bao' => 'CRM_Core_BAO_Address',
763 'table' => "civicrm_{$tName}",
764 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id "
768 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
769 $this->_element
["{$tName}_id"] = 1;
771 elseif ($tName != 'contact') {
772 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
773 $this->_element
["{$tName}_id"] = 1;
776 //special case for phone
777 if ($name == 'phone') {
778 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
779 $this->_element
['phone_type_id'] = 1;
782 // if IM then select provider_id also
783 // to get "IM Service Provider" in a file to be exported, CRM-3140
785 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
786 $this->_element
['provider_id'] = 1;
789 if ($tName == 'contact') {
790 // special case, when current employer is set for Individual contact
791 if ($fieldName == 'organization_name') {
792 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
794 elseif ($fieldName != 'id') {
795 if ($fieldName == 'prefix_id') {
796 $this->_pseudoConstantsSelect
['individual_prefix'] = array(
797 'pseudoField' => 'prefix_id',
798 'idCol' => "prefix_id",
799 'bao' => 'CRM_Contact_BAO_Contact'
802 if ($fieldName == 'suffix_id') {
803 $this->_pseudoConstantsSelect
['individual_suffix'] = array(
804 'pseudoField' => 'suffix_id',
805 'idCol' => "suffix_id",
806 'bao' => 'CRM_Contact_BAO_Contact'
809 if ($fieldName == 'gender_id') {
810 $this->_pseudoConstantsSelect
['gender'] = array(
811 'pseudoField' => 'gender_id',
812 'idCol' => "gender_id",
813 'bao' => 'CRM_Contact_BAO_Contact'
816 if ($name == 'communication_style_id') {
817 $this->_pseudoConstantsSelect
['communication_style'] = array(
818 'pseudoField' => 'communication_style_id',
819 'idCol' => "communication_style_id",
820 'bao' => 'CRM_Contact_BAO_Contact'
823 $this->_select
[$name] = "contact_a.{$fieldName} as `$name`";
826 elseif (in_array($tName, array('country', 'county'))) {
827 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
828 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
830 elseif ($tName == 'state_province') {
831 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
832 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
835 $this->_select
[$name] = "{$field['where']} as `$name`";
837 if (!in_array($tName, array('state_province', 'country', 'county'))) {
838 $this->_element
[$name] = 1;
843 elseif ($name === 'tags') {
844 $this->_useGroupBy
= TRUE;
845 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
846 $this->_element
[$name] = 1;
847 $this->_tables
['civicrm_tag'] = 1;
848 $this->_tables
['civicrm_entity_tag'] = 1;
850 elseif ($name === 'groups') {
851 $this->_useGroupBy
= TRUE;
852 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
853 $this->_element
[$name] = 1;
854 $this->_tables
['civicrm_group'] = 1;
856 elseif ($name === 'notes') {
857 // if note field is subject then return subject else body of the note
858 $noteColumn = 'note';
859 if (isset($noteField) && $noteField == 'note_subject') {
860 $noteColumn = 'subject';
863 $this->_useGroupBy
= TRUE;
864 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
865 $this->_element
[$name] = 1;
866 $this->_tables
['civicrm_note'] = 1;
868 elseif ($name === 'current_employer') {
869 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
870 $this->_element
[$name] = 1;
874 if ($cfID && !empty($field['is_search_range'])) {
875 // this is a custom field with range search enabled, so we better check for two/from values
876 if (!empty($this->_paramLookup
[$name . '_from'])) {
877 if (!array_key_exists($cfID, $this->_cfIDs
)) {
878 $this->_cfIDs
[$cfID] = array();
880 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
881 // search in the cdID array for the same grouping
883 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
884 if ($c[3] == $p[3]) {
885 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
890 $p[2] = array('from' => $p[2]);
891 $this->_cfIDs
[$cfID][] = $p;
895 if (!empty($this->_paramLookup
[$name . '_to'])) {
896 if (!array_key_exists($cfID, $this->_cfIDs
)) {
897 $this->_cfIDs
[$cfID] = array();
899 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
900 // search in the cdID array for the same grouping
902 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
903 if ($c[4] == $p[4]) {
904 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
909 $p[2] = array('to' => $p[2]);
910 $this->_cfIDs
[$cfID][] = $p;
917 // add location as hierarchical elements
918 $this->addHierarchicalElements();
920 // add multiple field like website
921 $this->addMultipleElements();
924 CRM_Core_Component
::alterQuery($this, 'select');
926 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
928 if (!empty($this->_cfIDs
)) {
929 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
930 $this->_customQuery
->query();
931 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
932 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
933 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
934 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
935 $this->_options
= $this->_customQuery
->_options
;
940 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
945 public function addHierarchicalElements() {
946 if (empty($this->_returnProperties
['location'])) {
949 if (!is_array($this->_returnProperties
['location'])) {
953 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
954 $processed = array();
957 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
958 $addressCustomFieldIds = array();
960 foreach ($this->_returnProperties
['location'] as $name => $elements) {
961 $lCond = self
::getPrimaryCondition($name);
964 $locationTypeId = array_search($name, $locationTypes);
965 if ($locationTypeId === FALSE) {
968 $lCond = "location_type_id = $locationTypeId";
969 $this->_useDistinct
= TRUE;
971 //commented for CRM-3256
972 $this->_useGroupBy
= TRUE;
975 $name = str_replace(' ', '_', $name);
977 $tName = "$name-location_type";
978 $ltName = "`$name-location_type`";
979 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
980 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
981 $this->_element
["{$tName}_id"] = 1;
982 $this->_element
["{$tName}"] = 1;
984 $locationTypeName = $tName;
985 $locationTypeJoin = array();
989 foreach ($elements as $elementFullName => $dontCare) {
991 $elementName = $elementCmpName = $elementFullName;
993 if (substr($elementCmpName, 0, 5) == 'phone') {
994 $elementCmpName = 'phone';
997 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
998 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
999 $addressCustomFieldIds[$cfID][$name] = 1;
1002 //add address table only once
1003 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
1005 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
1007 $tName = "$name-address";
1008 $aName = "`$name-address`";
1009 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1010 $this->_element
["{$tName}_id"] = 1;
1011 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
1012 $this->_tables
[$tName] = $addressJoin;
1013 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1014 $processed[$aName] = 1;
1018 $cond = $elementType = '';
1019 if (strpos($elementName, '-') !== FALSE) {
1020 // this is either phone, email or IM
1021 list($elementName, $elementType) = explode('-', $elementName);
1024 if (($elementName != 'phone') && ($elementName != 'im')) {
1025 $cond = self
::getPrimaryCondition($elementType);
1027 // CRM-13011 : If location type is primary, do not restrict search to the phone
1028 // type id - we want the primary phone, regardless of what type it is.
1029 // Otherwise, restrict to the specified phone type for the given field.
1030 if ((!$cond) && ($elementName == 'phone')) {
1031 $cond = "phone_type_id = '$elementType'";
1033 elseif ((!$cond) && ($elementName == 'im')) {
1034 // IM service provider id, CRM-3140
1035 $cond = "provider_id = '$elementType'";
1037 $elementType = '-' . $elementType;
1040 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
1042 // hack for profile, add location id
1045 // fix for CRM-882( to handle phone types )
1046 !is_numeric($elementType)
1048 if (is_numeric($name)) {
1049 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1052 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1055 elseif (is_numeric($name)) {
1056 //this for phone type to work
1057 if (in_array($elementName, array('phone', 'phone_ext'))) {
1058 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1061 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1065 //this is for phone type to work for profile edit
1066 if (in_array($elementName, array('phone', 'phone_ext'))) {
1067 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1070 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1075 // Check if there is a value, if so also add to where Clause
1077 if ($this->_params
) {
1079 if (isset($locationTypeId)) {
1080 $nm .= "-$locationTypeId";
1082 if (!is_numeric($elementType)) {
1083 $nm .= "$elementType";
1086 foreach ($this->_params
as $id => $values) {
1087 if ((is_array($values) && $values[0] == $nm) ||
1088 (in_array($elementName, array('phone', 'im'))
1089 && (strpos($values[0], $nm) !== FALSE)
1099 if ($field && isset($field['where'])) {
1100 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1101 $pf = substr($tableName, 8);
1102 $tName = $name . '-' . $pf . $elementType;
1103 if (isset($tableName)) {
1104 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1105 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1108 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1111 $this->_element
["{$tName}_id"] = 1;
1112 if (substr($tName, -15) == '-state_province') {
1113 // FIXME: hack to fix CRM-1900
1114 $a = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1118 if (substr_count($a, 'state_province_name') > 0) {
1119 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1120 array('pseudoField' => "{$pf}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1121 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1124 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1125 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id");
1126 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1130 if (substr($elementFullName, 0, 2) == 'im') {
1131 $provider = "{$name}-{$elementFullName}-provider_id";
1132 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1133 $this->_element
[$provider] = 1;
1135 if ($pf == 'country' ||
$pf == 'county') {
1136 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1137 'pseudoField' => "{$pf}_id",
1138 'idCol' => "{$tName}_id",
1139 'bao' => 'CRM_Core_BAO_Address'
1141 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1144 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1148 if (in_array($pf, array('state_province', 'country', 'county'))) {
1149 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1152 $this->_element
["{$name}-{$elementFullName}"] = 1;
1155 if (empty($processed["`$tName`"])) {
1156 $processed["`$tName`"] = 1;
1157 $newName = $tableName . '_' . $index;
1158 switch ($tableName) {
1159 case 'civicrm_phone':
1160 case 'civicrm_email':
1162 case 'civicrm_openid':
1164 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1165 if ($tableName != 'civicrm_phone') {
1166 $this->_tables
[$tName] .= " AND `$tName`.$lCond";
1168 elseif (is_numeric($name)) {
1169 $this->_select
[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1172 // this special case to add phone type
1174 $phoneTypeCondition = " AND `$tName`.$cond ";
1175 //gross hack to pickup corrupted data also, CRM-7603
1176 if (strpos($cond, 'phone_type_id') !== FALSE) {
1177 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1179 $this->_tables
[$tName] .= $phoneTypeCondition;
1182 //build locationType join
1183 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1186 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1190 case 'civicrm_state_province':
1191 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1192 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1193 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1195 $this->_whereTables
["{$name}-address"] = $addressJoin;
1199 case 'civicrm_country':
1200 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1201 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1202 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1204 $this->_whereTables
["{$name}-address"] = $addressJoin;
1208 case 'civicrm_county':
1209 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1210 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1211 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1213 $this->_whereTables
["{$name}-address"] = $addressJoin;
1219 $this->_whereTables
["{$name}-address"] = $addressJoin;
1228 // add location type join
1229 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1230 $this->_tables
[$locationTypeName] = $ltypeJoin;
1232 // table should be present in $this->_whereTables,
1233 // to add its condition in location type join, CRM-3939.
1234 if ($addWhereCount) {
1235 $locClause = array();
1236 foreach ($this->_whereTables
as $tableName => $clause) {
1237 if (!empty($locationTypeJoin[$tableName])) {
1238 $locClause[] = $locationTypeJoin[$tableName];
1242 if (!empty($locClause)) {
1243 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1248 if (!empty($addressCustomFieldIds)) {
1249 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1250 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1251 foreach ($locTypeName as $name => $dnc) {
1252 $this->_locationSpecificCustomFields
[$cfID] = array($name, array_search($name, $locationTypes));
1253 $fieldName = "$name-custom_{$cfID}";
1254 $tName = "$name-address-custom-{$cfID}";
1255 $aName = "`$name-address-custom-{$cfID}`";
1256 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1257 $this->_element
["{$tName}_id"] = 1;
1258 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1259 $this->_element
[$fieldName] = 1;
1260 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1267 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
1272 public function addMultipleElements() {
1273 if (empty($this->_returnProperties
['website'])) {
1276 if (!is_array($this->_returnProperties
['website'])) {
1280 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1281 foreach ($elements as $elementFullName => $dontCare) {
1282 $tName = "website-{$key}-{$elementFullName}";
1283 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1284 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1285 $this->_element
["{$tName}_id"] = 1;
1286 $this->_element
["{$tName}"] = 1;
1288 $type = "website-{$key}-website_type_id";
1289 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1290 $this->_element
[$type] = 1;
1291 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1297 * Generate the query based on what type of query we need
1299 * @param bool $count
1300 * @param bool $sortByChar
1301 * @param bool $groupContacts
1302 * @param bool $onlyDeleted
1304 * @return array sql query parts as an array
1306 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1307 // build permission clause
1308 $this->generatePermissionClause($onlyDeleted, $count);
1311 if (isset($this->_rowCountClause
)) {
1312 $select = "SELECT {$this->_rowCountClause}";
1314 else if (isset($this->_distinctComponentClause
)) {
1315 // we add distinct to get the right count for components
1316 // for the more complex result set, we use GROUP BY the same id
1318 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1321 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1323 $from = $this->_simpleFromClause
;
1324 if ($this->_useDistinct
) {
1325 $this->_useGroupBy
= TRUE;
1328 elseif ($sortByChar) {
1329 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1330 $from = $this->_simpleFromClause
;
1332 elseif ($groupContacts) {
1333 $select = 'SELECT contact_a.id as id';
1334 if ($this->_useDistinct
) {
1335 $this->_useGroupBy
= TRUE;
1337 $from = $this->_simpleFromClause
;
1340 if (!empty($this->_paramLookup
['group'])) {
1341 // make sure there is only one element
1342 // this is used when we are running under smog and need to know
1343 // how the contact was added (CRM-1203)
1344 if ((count($this->_paramLookup
['group']) == 1) &&
1345 (count($this->_paramLookup
['group'][0][2]) == 1)
1347 $groups = array_keys($this->_paramLookup
['group'][0][2]);
1348 $groupId = $groups[0];
1350 //check if group is saved search
1351 $group = new CRM_Contact_BAO_Group();
1352 $group->id
= $groupId;
1355 if (!isset($group->saved_search_id
)) {
1356 $tbName = "`civicrm_group_contact-{$groupId}`";
1357 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1358 $this->_element
['group_contact_id'] = 1;
1359 $this->_select
['status'] = "$tbName.status as status";
1360 $this->_element
['status'] = 1;
1363 $this->_useGroupBy
= TRUE;
1365 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1366 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1368 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1369 $this->_useDistinct
= FALSE;
1370 $this->_useGroupBy
= TRUE;
1374 $select = "SELECT ";
1375 if (isset($this->_distinctComponentClause
)) {
1376 $select .= "{$this->_distinctComponentClause}, ";
1378 $select .= implode(', ', $this->_select
);
1379 $from = $this->_fromClause
;
1383 if (!empty($this->_whereClause
)) {
1384 $where = "WHERE {$this->_whereClause}";
1387 if (!empty($this->_permissionWhereClause
)) {
1388 if (empty($where)) {
1389 $where = "WHERE $this->_permissionWhereClause";
1392 $where = "$where AND $this->_permissionWhereClause";
1397 if (!empty($this->_having
)) {
1398 foreach ($this->_having
as $havingSets) {
1399 foreach ($havingSets as $havingSet) {
1400 $havingValue[] = $havingSet;
1403 $having = ' HAVING ' . implode(' AND ', $havingValue);
1406 // if we are doing a transform, do it here
1407 // use the $from, $where and $having to get the contact ID
1408 if ($this->_displayRelationshipType
) {
1409 $this->filterRelatedContacts($from, $where, $having);
1412 return array($select, $from, $where, $having);
1416 * @param string $name
1421 public function &getWhereValues($name, $grouping) {
1423 foreach ($this->_params
as $values) {
1424 if ($values[0] == $name && $values[3] == $grouping) {
1437 public static function fixDateValues($relative, &$from, &$to) {
1439 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1444 * @param $formValues
1445 * @param int $wildcard
1446 * @param bool $useEquals
1450 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE) {
1452 if (empty($formValues)) {
1456 foreach ($formValues as $id => $values) {
1457 if ($id == 'privacy') {
1458 if (is_array($formValues['privacy'])) {
1459 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1460 foreach ($formValues['privacy'] as $key => $value) {
1462 $params[] = array($key, $op, $value, 0, 0);
1467 elseif ($id == 'email_on_hold') {
1468 if ($formValues['email_on_hold']['on_hold']) {
1469 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1472 elseif (preg_match('/_date_relative$/', $id) ||
1473 $id == 'event_relative' ||
1474 $id == 'case_from_relative' ||
1475 $id == 'case_to_relative'
1477 if ($id == 'event_relative') {
1478 $fromRange = 'event_start_date_low';
1479 $toRange = 'event_end_date_high';
1481 else if ($id == 'case_from_relative') {
1482 $fromRange = 'case_from_start_date_low';
1483 $toRange = 'case_from_start_date_high';
1485 else if ($id == 'case_to_relative') {
1486 $fromRange = 'case_to_end_date_low';
1487 $toRange = 'case_to_end_date_high';
1490 $dateComponent = explode('_date_relative', $id);
1491 $fromRange = "{$dateComponent[0]}_date_low";
1492 $toRange = "{$dateComponent[0]}_date_high";
1495 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1496 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1501 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals);
1506 $params[] = $values;
1515 * @param int $wildcard
1516 * @param bool $useEquals
1518 * @return array|null
1520 public static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE) {
1521 // skip a few search variables
1522 static $skipWhere = NULL;
1523 static $likeNames = NULL;
1526 if (CRM_Utils_System
::isNull($values)) {
1538 'display_relationship_type',
1542 if (in_array($id, $skipWhere) ||
1543 substr($id, 0, 4) == '_qf_' ||
1544 substr($id, 0, 7) == 'hidden_'
1550 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1553 // email comes in via advanced search
1554 // so use wildcard always
1555 if ($id == 'email') {
1559 if (!$useEquals && in_array($id, $likeNames)) {
1560 $result = array($id, 'LIKE', $values, 0, 1);
1562 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1563 $result = array($id, 'LIKE', $values, 0, 0);
1565 elseif ($id == 'group') {
1566 if (is_array($values)) {
1567 foreach ($values as $groupIds => $val) {
1569 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1570 if (strlen($matches[1]) > 0) {
1571 $values[$matches[1]] = 1;
1572 unset($values[$groupIds]);
1578 $groupIds = explode(',', $values);
1580 foreach ($groupIds as $groupId) {
1581 $values[$groupId] = 1;
1585 $result = array($id, 'IN', $values, 0, 0);
1587 elseif ($id == 'contact_tags' ||
$id == 'tag') {
1588 if (!is_array($values)) {
1589 $tagIds = explode(',', $values);
1591 foreach ($tagIds as $tagId) {
1592 $values[$tagId] = 1;
1595 $result = array($id, 'IN', $values, 0, 0);
1597 elseif ($id == 'contact_type') {
1598 $result = array($id, 'IN', $values, 0, $wildcard);
1601 $result = array($id, '=', $values, 0, $wildcard);
1610 public function whereClauseSingle(&$values) {
1611 // do not process custom fields or prefixed contact ids or component params
1612 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1613 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1614 (substr($values[0], 0, 13) == 'contribution_') ||
1615 (substr($values[0], 0, 6) == 'event_') ||
1616 (substr($values[0], 0, 12) == 'participant_') ||
1617 (substr($values[0], 0, 7) == 'member_') ||
1618 (substr($values[0], 0, 6) == 'grant_') ||
1619 (substr($values[0], 0, 7) == 'pledge_') ||
1620 (substr($values[0], 0, 5) == 'case_') ||
1621 (substr($values[0], 0, 10) == 'financial_') ||
1622 (substr($values[0], 0, 11) == 'membership_')
1627 // skip for hook injected fields / params
1628 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1629 if (array_key_exists($values[0], $extFields)) {
1633 switch ($values[0]) {
1634 case 'deleted_contacts':
1635 $this->deletedContacts($values);
1638 case 'contact_type':
1639 $this->contactType($values);
1642 case 'contact_sub_type':
1643 $this->contactSubType($values);
1647 $this->group($values);
1651 // so we resolve this into a list of groups & proceed as if they had been
1653 list($name, $op, $value, $grouping, $wildcard) = $values;
1654 $values[0] = 'group';
1656 $this->_paramLookup
['group'][0][0] = 'group';
1657 $this->_paramLookup
['group'][0][1] = 'IN';
1658 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1659 $this->group($values);
1662 // case tag comes from find contacts
1664 $this->tagSearch($values);
1668 case 'contact_tags':
1669 $this->tag($values);
1674 case 'note_subject':
1675 $this->notes($values);
1679 $this->ufUser($values);
1683 case 'display_name':
1684 $this->sortName($values);
1688 $this->email($values);
1691 case 'phone_numeric':
1692 $this->phone_numeric($values);
1695 case 'phone_phone_type_id':
1696 case 'phone_location_type_id':
1697 $this->phone_option_group($values);
1700 case 'street_address':
1701 $this->street_address($values);
1704 case 'street_number':
1705 $this->street_number($values);
1708 case 'sortByCharacter':
1709 $this->sortByCharacter($values);
1712 case 'location_type':
1713 $this->locationType($values);
1717 $this->county($values);
1720 case 'state_province':
1721 $this->stateProvince($values);
1725 $this->country($values, FALSE);
1729 case 'postal_code_low':
1730 case 'postal_code_high':
1731 $this->postalCode($values);
1734 case 'activity_date':
1735 case 'activity_date_low':
1736 case 'activity_date_high':
1737 case 'activity_role':
1738 case 'activity_status':
1739 case 'followup_parent_id':
1741 case 'activity_subject':
1742 case 'test_activities':
1743 case 'activity_type_id':
1744 case 'activity_type':
1745 case 'activity_survey_id':
1746 case 'activity_tags':
1747 case 'activity_taglist':
1748 case 'activity_test':
1749 case 'activity_campaign_id':
1750 case 'activity_engagement_level':
1752 case 'activity_result':
1753 case 'source_contact':
1754 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1757 case 'birth_date_low':
1758 case 'birth_date_high':
1759 case 'deceased_date_low':
1760 case 'deceased_date_high':
1761 $this->demographics($values);
1764 case 'log_date_low':
1765 case 'log_date_high':
1766 $this->modifiedDates($values);
1770 $this->changeLog($values);
1773 case 'do_not_phone':
1774 case 'do_not_email':
1777 case 'do_not_trade':
1779 $this->privacy($values);
1782 case 'privacy_options':
1783 $this->privacyOptions($values);
1786 case 'privacy_operator':
1787 case 'privacy_toggle':
1788 // these are handled by privacy options
1791 case 'preferred_communication_method':
1792 $this->preferredCommunication($values);
1795 case 'relation_type_id':
1796 case 'relation_start_date_high':
1797 case 'relation_start_date_low':
1798 case 'relation_end_date_high':
1799 case 'relation_end_date_low':
1800 case 'relation_target_name':
1801 case 'relation_status':
1802 case 'relation_date_low':
1803 case 'relation_date_high':
1804 $this->relationship($values);
1805 $this->_relationshipValuesAdded
= TRUE;
1808 case 'task_status_id':
1809 $this->task($values);
1813 // since this case is handled with the above
1816 case 'prox_distance':
1817 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1820 case 'prox_street_address':
1822 case 'prox_postal_code':
1823 case 'prox_state_province_id':
1824 case 'prox_country_id':
1825 // handled by the proximity_distance clause
1829 $this->restWhere($values);
1835 * Given a list of conditions in params generate the required
1840 public function whereClause() {
1841 $this->_where
[0] = array();
1842 $this->_qill
[0] = array();
1844 $this->includeContactIds();
1845 if (!empty($this->_params
)) {
1846 foreach (array_keys($this->_params
) as $id) {
1847 if (empty($this->_params
[$id][0])) {
1850 // check for both id and contact_id
1851 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
1853 $this->_params
[$id][1] == 'IS NULL' ||
1854 $this->_params
[$id][1] == 'IS NOT NULL'
1856 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]}";
1858 elseif (is_array($this->_params
[$id][2])) {
1859 $idList = implode("','", $this->_params
[$id][2]);
1860 //why on earth do they put ' in the middle & not on the outside? We have to assume it's
1861 //to support 'something' so lets add them conditionally to support the api (which is a tested flow
1862 // so if you are looking to alter this check api test results
1863 if (strpos(trim($idList), "'") > 0) {
1864 $idList = "'" . $idList . "'";
1867 $this->_where
[0][] = "contact_a.id IN ({$idList})";
1870 $this->_where
[0][] = self
::buildClause("contact_a.id", "{$this->_params[$id][1]}", "{$this->_params[$id][2]}");
1874 $this->whereClauseSingle($this->_params
[$id]);
1878 CRM_Core_Component
::alterQuery($this, 'where');
1880 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
1883 if ($this->_customQuery
) {
1884 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1885 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1886 if (!empty($this->_customQuery
->_where
)) {
1887 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
1890 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
1894 $andClauses = array();
1897 if (!empty($this->_where
)) {
1898 foreach ($this->_where
as $grouping => $values) {
1899 if ($grouping > 0 && !empty($values)) {
1900 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1905 if (!empty($this->_where
[0])) {
1906 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
1908 if (!empty($clauses)) {
1909 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1912 if ($validClauses > 1) {
1913 $this->_useDistinct
= TRUE;
1917 return implode(' AND ', $andClauses);
1925 public function restWhere(&$values) {
1926 $name = CRM_Utils_Array
::value(0, $values);
1927 $op = CRM_Utils_Array
::value(1, $values);
1928 $value = CRM_Utils_Array
::value(2, $values);
1929 $grouping = CRM_Utils_Array
::value(3, $values);
1930 $wildcard = CRM_Utils_Array
::value(4, $values);
1932 if (isset($grouping) && empty($this->_where
[$grouping])) {
1933 $this->_where
[$grouping] = array();
1936 $multipleFields = array('url');
1938 //check if the location type exits for fields
1940 $locType = explode('-', $name);
1942 if (!in_array($locType[0], $multipleFields)) {
1943 //add phone type if exists
1944 if (isset($locType[2]) && $locType[2]) {
1945 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
1949 $field = CRM_Utils_Array
::value($name, $this->_fields
);
1952 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
1961 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
1962 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1964 if (substr($name, 0, 14) === 'state_province') {
1965 if (isset($locType[1]) && is_numeric($locType[1])) {
1967 $aName = "{$locationType[$locType[1]]}-address";
1968 $where = "`$aName`.state_province_id";
1971 $where = "civicrm_address.state_province_id";
1974 $states = CRM_Core_PseudoConstant
::stateProvince();
1975 if (is_numeric($value)) {
1976 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1977 $value = $states[(int ) $value];
1980 $intVal = CRM_Utils_Array
::key($value, $states);
1981 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1984 $this->_qill
[$grouping][] = ts('State') . " $op '$value'";
1987 $this->_qill
[$grouping][] = ts('State') . " ($lType) $op '$value'";
1990 elseif (!empty($field['pseudoconstant'])) {
1991 $this->optionValueQuery(
1992 $name, $op, $value, $grouping,
1993 CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', $field['name']),
1999 if ($name == 'gender_id') {
2000 self
::$_openedPanes[ts('Demographics')] = TRUE;
2003 elseif (substr($name, 0, 7) === 'country') {
2004 if (isset($locType[1]) && is_numeric($locType[1])) {
2006 $aName = "{$locationType[$locType[1]]}-address";
2007 $where = "`$aName`.country_id";
2010 $where = "civicrm_address.country_id";
2013 $countries = CRM_Core_PseudoConstant
::country();
2014 if (is_numeric($value)) {
2015 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2016 $value = $countries[(int ) $value];
2019 $intVal = CRM_Utils_Array
::key($value, $countries);
2020 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
2024 $this->_qill
[$grouping][] = ts('Country') . " $op '$value'";
2027 $this->_qill
[$grouping][] = ts('Country') . " ($lType) $op '$value'";
2030 elseif (substr($name, 0, 6) === 'county') {
2031 if (isset($locType[1]) && is_numeric($locType[1])) {
2033 $aName = "{$locationType[$locType[1]]}-address";
2034 $where = "`$aName`.county_id";
2037 $where = "civicrm_address.county_id";
2040 $counties = CRM_Core_PseudoConstant
::county();
2041 if (is_numeric($value)) {
2042 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2043 $value = $counties[(int ) $value];
2046 $intVal = CRM_Utils_Array
::key($value, $counties);
2047 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
2051 $this->_qill
[$grouping][] = ts('County') . " $op '$value'";
2054 $this->_qill
[$grouping][] = ts('County') . " ($lType) $op '$value'";
2057 elseif ($name === 'world_region') {
2058 $field['where'] = 'civicrm_worldregion.id';
2059 $this->optionValueQuery(
2060 $name, $op, $value, $grouping,
2061 CRM_Core_PseudoConstant
::worldRegion(),
2068 elseif ($name === 'birth_date') {
2069 $date = CRM_Utils_Date
::processDate($value);
2070 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
2073 $date = CRM_Utils_Date
::customFormat($date);
2074 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
2077 $this->_qill
[$grouping][] = "$field[title] $op";
2079 self
::$_openedPanes[ts('Demographics')] = TRUE;
2081 elseif ($name === 'deceased_date') {
2082 $date = CRM_Utils_Date
::processDate($value);
2083 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
2085 $date = CRM_Utils_Date
::customFormat($date);
2086 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
2089 $this->_qill
[$grouping][] = "$field[title] $op";
2091 self
::$_openedPanes[ts('Demographics')] = TRUE;
2093 elseif ($name === 'is_deceased') {
2094 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
2095 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2096 self
::$_openedPanes[ts('Demographics')] = TRUE;
2098 elseif ($name === 'contact_id') {
2099 if (is_int($value)) {
2100 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2101 $this->_qill
[$grouping][] = "$field[title] $op $value";
2104 elseif ($name === 'name') {
2105 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2107 $value = "%$value%";
2110 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2111 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2112 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2114 elseif ($name === 'current_employer') {
2115 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2117 $value = "%$value%";
2120 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
2121 $ceWhereClause = self
::buildClause($wc, $op,
2124 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2125 $this->_where
[$grouping][] = $ceWhereClause;
2126 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2128 elseif ($name === 'email_greeting') {
2129 $filterCondition = array('greeting_type' => 'email_greeting');
2130 $this->optionValueQuery(
2131 $name, $op, $value, $grouping,
2132 CRM_Core_PseudoConstant
::greeting($filterCondition),
2134 ts('Email Greeting')
2137 elseif ($name === 'postal_greeting') {
2138 $filterCondition = array('greeting_type' => 'postal_greeting');
2139 $this->optionValueQuery(
2140 $name, $op, $value, $grouping,
2141 CRM_Core_PseudoConstant
::greeting($filterCondition),
2143 ts('Postal Greeting')
2146 elseif ($name === 'addressee') {
2147 $filterCondition = array('greeting_type' => 'addressee');
2148 $this->optionValueQuery(
2149 $name, $op, $value, $grouping,
2150 CRM_Core_PseudoConstant
::greeting($filterCondition),
2155 elseif (substr($name, 0, 4) === 'url-') {
2156 $tName = 'civicrm_website';
2157 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2158 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2160 $value = "%$value%";
2164 $wc = 'civicrm_website.url';
2165 $this->_where
[$grouping][] = $d = self
::buildClause($wc, $op, $value);
2166 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2168 elseif ($name === 'contact_is_deleted') {
2169 $this->_where
[$grouping][] = self
::buildClause("contact_a.is_deleted", $op, $value);
2170 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2173 if (is_array($value)) {
2174 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2175 // for api style operators for functions that hit this point without worrying about regression
2176 // (the previous comments indicated the condition for hitting this point were unknown
2177 // per CRM-14743 we are adding modified_date & created_date operator support
2178 $operations = array_keys($value);
2179 foreach ($operations as $operator) {
2180 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2181 // we don't know when this might happen
2182 CRM_Core_Error
::fatal();
2185 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($name, $value, NULL);
2186 //since this is not currently being called by the form layer we can skip worrying about the 'qill' for now
2190 if (!empty($field['where'])) {
2192 $value = $strtolower($value);
2195 $value = "%$value%";
2199 if (isset($locType[1]) &&
2200 is_numeric($locType[1])
2204 //get the location name
2205 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2207 $where = "`$tName`.$fldName";
2209 $this->_where
[$grouping][] = self
::buildClause("LOWER($where)", $op, $value);
2210 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2211 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2212 $this->_qill
[$grouping][] = "$field[title] $op '$value'";
2215 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2216 if ($tableName == 'civicrm_contact') {
2217 $fieldName = "LOWER(contact_a.{$fieldName})";
2220 if ($op != 'IN' && !is_numeric($value)) {
2221 $fieldName = "LOWER({$field['where']})";
2224 $fieldName = "{$field['where']}";
2229 if (!empty($field['type'])) {
2230 $type = CRM_Utils_Type
::typeToString($field['type']);
2233 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2234 $this->_qill
[$grouping][] = "$field[title] $op $value";
2239 if ($setTables && isset($field['where'])) {
2240 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2241 if (isset($tableName)) {
2242 $this->_tables
[$tableName] = 1;
2243 $this->_whereTables
[$tableName] = 1;
2256 public static function getLocationTableName(&$where, &$locType) {
2257 if (isset($locType[1]) && is_numeric($locType[1])) {
2258 list($tbName, $fldName) = explode(".", $where);
2260 //get the location name
2261 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2262 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2263 if (in_array($locType[0], $specialFields)) {
2264 //hack to fix / special handing for phone_ext
2265 if ($locType[0] == 'phone_ext') {
2266 $locType[0] = 'phone';
2268 if (isset($locType[2]) && $locType[2]) {
2269 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2272 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2275 elseif (in_array($locType[0],
2279 'supplemental_address_1',
2280 'supplemental_address_2',
2283 'postal_code_suffix',
2288 //fix for search by profile with address fields.
2289 $tName = "{$locationType[$locType[1]]}-address";
2291 elseif ($locType[0] == 'on_hold') {
2292 $tName = "{$locationType[$locType[1]]}-email";
2295 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2297 $tName = str_replace(' ', '_', $tName);
2298 return array($tName, $fldName);
2300 CRM_Core_Error
::fatal();
2304 * Given a result dao, extract the values and return that array
2306 * @param CRM_Core_DAO $dao
2308 * @return array values for this query
2310 public function store($dao) {
2313 foreach ($this->_element
as $key => $dontCare) {
2314 if (property_exists($dao, $key)) {
2315 if (strpos($key, '-') !== FALSE) {
2316 $values = explode('-', $key);
2317 $lastElement = array_pop($values);
2319 $cnt = count($values);
2321 foreach ($values as $v) {
2322 if (!array_key_exists($v, $current)) {
2323 $current[$v] = array();
2325 //bad hack for im_provider
2326 if ($lastElement == 'provider_id') {
2327 if ($count < $cnt) {
2328 $current = &$current[$v];
2331 $lastElement = "{$v}_{$lastElement}";
2335 $current = &$current[$v];
2340 $current[$lastElement] = $dao->$key;
2343 $value[$key] = $dao->$key;
2351 * Getter for tables array
2355 public function tables() {
2356 return $this->_tables
;
2360 * Where tables is sometimes used to create the from clause, but, not reliably, set this AND set tables
2361 * It's unclear the intent - there is a 'simpleFrom' clause which takes whereTables into account & a fromClause which doesn't
2362 * logic may have eroded
2365 public function whereTables() {
2366 return $this->_whereTables
;
2370 * Generate the where clause (used in match contacts and permissions)
2372 * @param array $params
2373 * @param array $fields
2374 * @param array $tables
2375 * @param $whereTables
2376 * @param bool $strict
2381 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2382 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2386 $tables = array_merge($query->tables(), $tables);
2387 $whereTables = array_merge($query->whereTables(), $whereTables);
2389 return $query->_whereClause
;
2393 * Create the from clause
2395 * @param array $tables
2396 * Tables that need to be included in this from clause.
2397 * if null, return mimimal from clause (i.e. civicrm_contact)
2398 * @param array $inner
2399 * Tables that should be inner-joined.
2400 * @param array $right
2401 * Tables that should be right-joined.
2403 * @param bool $primaryLocation
2406 * @return string the from clause
2409 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2411 $from = ' FROM civicrm_contact contact_a';
2412 if (empty($tables)) {
2416 if (!empty($tables['civicrm_worldregion'])) {
2417 $tables = array_merge(array('civicrm_country' => 1), $tables);
2420 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2421 CRM_Utils_Array
::value('civicrm_county', $tables)
2422 ) && empty($tables['civicrm_address'])
2424 $tables = array_merge(array('civicrm_address' => 1),
2429 // add group_contact table if group table is present
2430 if (!empty($tables['civicrm_group']) && empty($tables['civicrm_group_contact'])) {
2431 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
2434 // add group_contact and group table is subscription history is present
2435 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2436 $tables = array_merge(array(
2437 'civicrm_group' => 1,
2438 'civicrm_group_contact' => 1,
2444 // to handle table dependencies of components
2445 CRM_Core_Component
::tableNames($tables);
2446 // to handle table dependencies of hook injected tables
2447 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2449 //format the table list according to the weight
2450 $info = CRM_Core_TableHierarchy
::info();
2452 foreach ($tables as $key => $value) {
2454 if (strpos($key, '-') !== FALSE) {
2455 $keyArray = explode('-', $key);
2456 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2458 elseif (strpos($key, '_') !== FALSE) {
2459 $keyArray = explode('_', $key);
2460 if (is_numeric(array_pop($keyArray))) {
2461 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2464 $k = CRM_Utils_Array
::value($key, $info, 99);
2468 $k = CRM_Utils_Array
::value($key, $info, 99);
2470 $tempTable[$k . ".$key"] = $key;
2473 $newTables = array();
2474 foreach ($tempTable as $key) {
2475 $newTables[$key] = $tables[$key];
2478 $tables = $newTables;
2480 foreach ($tables as $name => $value) {
2485 if (!empty($inner[$name])) {
2488 elseif (!empty($right[$name])) {
2496 // if there is already a join statement in value, use value itself
2497 if (strpos($value, 'JOIN')) {
2498 $from .= " $value ";
2501 $from .= " $side JOIN $name ON ( $value ) ";
2506 case 'civicrm_address':
2507 if ($primaryLocation) {
2508 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2511 //CRM-14263 further handling of address joins further down...
2512 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2516 case 'civicrm_phone':
2517 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2520 case 'civicrm_email':
2521 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2525 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2529 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2530 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2531 $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)";
2534 case 'civicrm_openid':
2535 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2538 case 'civicrm_worldregion':
2539 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2540 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2543 case 'civicrm_location_type':
2544 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2547 case 'civicrm_group':
2548 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2551 case 'civicrm_group_contact':
2552 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2555 case 'civicrm_activity':
2556 case 'civicrm_activity_tag':
2557 case 'activity_type':
2558 case 'activity_status':
2560 case 'civicrm_activity_contact':
2561 case 'source_contact':
2562 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2565 case 'civicrm_entity_tag':
2566 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2567 civicrm_entity_tag.entity_id = contact_a.id ) ";
2570 case 'civicrm_note':
2571 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2572 contact_a.id = civicrm_note.entity_id ) ";
2575 case 'civicrm_subscription_history':
2576 $from .= " $side JOIN civicrm_subscription_history
2577 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2578 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2581 case 'civicrm_relationship':
2582 if (self
::$_relType == 'reciprocal') {
2583 if (self
::$_relationshipTempTable) {
2584 // we have a temptable to join on
2585 $tbl = self
::$_relationshipTempTable;
2586 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2589 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2590 $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)";
2593 elseif (self
::$_relType == 'b') {
2594 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2595 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2598 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2599 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2604 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2605 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2609 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2612 case 'civicrm_grant':
2613 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2616 case 'civicrm_website':
2617 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2621 $locationTypeName = '';
2622 if (strpos($name, '-address') != 0) {
2623 $locationTypeName = 'address';
2625 elseif (strpos($name, '-phone') != 0) {
2626 $locationTypeName = 'phone';
2628 elseif (strpos($name, '-email') != 0) {
2629 $locationTypeName = 'email';
2631 if ($locationTypeName) {
2632 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2633 $parts = explode('-', $name);
2634 $locationID = array_search($parts[0], CRM_Core_BAO_Address
::buildOptions('location_type_id', 'get', array('name' => $parts[0])));
2635 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2638 $from .= CRM_Core_Component
::from($name, $mode, $side);
2640 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2649 * WHERE / QILL clause for deleted_contacts
2655 public function deletedContacts($values) {
2656 list($_, $_, $value, $grouping, $_) = $values;
2658 // *prepend* to the relevant grouping as this is quite an important factor
2659 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2664 * Where / qill clause for contact_type
2670 public function contactType(&$values) {
2671 list($name, $op, $value, $grouping, $wildcard) = $values;
2673 $subTypes = array();
2676 // account for search builder mapping multiple values
2677 if (!is_array($value)) {
2678 $values = self
::parseSearchBuilderString($value, 'String');
2679 if (is_array($values)) {
2680 $value = array_flip($values);
2684 if (is_array($value)) {
2685 foreach ($value as $k => $v) {
2690 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2691 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2694 if (!empty($subType)) {
2695 $subTypes[$subType] = 1;
2697 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2702 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2703 $contactType = $contactTypeANDSubType[0];
2704 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2705 if (!empty($subType)) {
2706 $subTypes[$subType] = 1;
2708 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2712 if (!empty($clause)) {
2714 if ($op == 'IN' ||
$op == 'NOT IN') {
2715 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2718 $type = array_pop($clause);
2719 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2722 $this->_qill
[$grouping][] = ts('Contact Type') . ' - ' . implode(' ' . ts('or') . ' ', $quill);
2724 if (!empty($subTypes)) {
2725 $this->includeContactSubTypes($subTypes, $grouping);
2731 * Where / qill clause for contact_sub_type
2737 public function contactSubType(&$values) {
2738 list($name, $op, $value, $grouping, $wildcard) = $values;
2739 $this->includeContactSubTypes($value, $grouping, $op);
2746 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2749 $alias = "contact_a.contact_sub_type";
2750 $qillOperators = array('NOT LIKE' => ts('Not Like')) + CRM_Core_SelectValues
::getSearchBuilderOperators();
2752 $op = str_replace('IN', 'LIKE', $op);
2753 $op = str_replace('=', 'LIKE', $op);
2754 $op = str_replace('!', 'NOT ', $op);
2756 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2757 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
2759 else if (is_array($value)) {
2760 foreach ($value as $k => $v) {
2762 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($k, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2767 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2770 if (!empty($clause)) {
2771 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2773 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', array(1 => $qillOperators[$op])) . implode(' ' . ts('or') . ' ', array_keys($clause));
2777 * Where / qill clause for groups
2783 public function group(&$values) {
2784 list($name, $op, $value, $grouping, $wildcard) = $values;
2786 if (count($value) > 1) {
2787 $this->_useDistinct
= TRUE;
2790 $groupNames = CRM_Core_PseudoConstant
::group();
2791 $groupIds = implode(',', array_keys($value));
2794 foreach ($value as $id => $dontCare) {
2795 if (array_key_exists($id, $groupNames) && $dontCare) {
2796 $names[] = $groupNames[$id];
2802 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2804 is_array($gcsValues[2])
2806 foreach ($gcsValues[2] as $k => $v) {
2808 if ($k == 'Added') {
2811 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2816 $statii[] = '"Added"';
2821 if (count($value) == 1 &&
2822 count($statii) == 1 &&
2823 $statii[0] == '"Added"'
2825 // check if smart group, if so we can get rid of that one additional
2827 $groupIDs = array_keys($value);
2829 if (!empty($groupIDs[0]) &&
2830 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
2840 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2841 $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 ) )";
2844 $qill = ts('Contacts %1', array(1 => $op));
2845 $qill .= ' ' . implode(' ' . ts('or') . ' ', $names);
2847 $groupClause = NULL;
2850 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2851 if (!empty($statii)) {
2852 $groupClause .= " AND {$gcTable}.status IN (" . implode(', ', $statii) . ")";
2853 $qill .= " " . ts('AND') . " " . ts('Group Status') . ' - ' . implode(' ' . ts('or') . ' ', $statii);
2858 $ssClause = $this->savedSearch($values);
2861 $groupClause = "( ( $groupClause ) OR ( $ssClause ) )";
2864 $groupClause = $ssClause;
2869 $this->_where
[$grouping][] = $groupClause;
2870 $this->_qill
[$grouping][] = $qill;
2873 * Function translates selection of group type into a list of groups
2880 public function getGroupsFromTypeCriteria($value) {
2881 $groupIds = array();
2882 foreach ($value as $groupTypeValue) {
2883 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2884 $groupIds = ($groupIds +
$groupList);
2890 * Where / qill clause for smart groups
2894 * @return string|NULL
2896 public function savedSearch(&$values) {
2897 list($name, $op, $value, $grouping, $wildcard) = $values;
2898 return $this->addGroupContactCache(array_keys($value));
2902 * @param array $groups
2903 * @param string $tableAlias
2904 * @param string $joinTable
2906 * @return null|string
2908 public function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
2909 $config = CRM_Core_Config
::singleton();
2911 // Find all the groups that are part of a saved search.
2912 $groupIDs = implode(',', $groups);
2913 if (empty($groupIDs)) {
2918 SELECT id, cache_date, saved_search_id, children
2920 WHERE id IN ( $groupIDs )
2921 AND ( saved_search_id != 0
2922 OR saved_search_id IS NOT NULL
2923 OR children IS NOT NULL )
2926 $group = CRM_Core_DAO
::executeQuery($sql);
2927 $groupsFiltered = array();
2929 while ($group->fetch()) {
2930 $groupsFiltered[] = $group->id
;
2932 $this->_useDistinct
= TRUE;
2934 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
2935 CRM_Contact_BAO_GroupContactCache
::load($group);
2939 if (count($groupsFiltered)) {
2940 $groupIDsFiltered = implode(',', $groupsFiltered);
2942 if ($tableAlias == NULL) {
2943 $tableAlias = "`civicrm_group_contact_cache_{$groupIDsFiltered}`";
2946 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.id = {$tableAlias}.contact_id ";
2948 return "{$tableAlias}.group_id IN (" . $groupIDsFiltered . ")";
2955 * Where / qill clause for cms users
2961 public function ufUser(&$values) {
2962 list($name, $op, $value, $grouping, $wildcard) = $values;
2965 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2967 $this->_qill
[$grouping][] = ts('CMS User');
2969 elseif ($value == 0) {
2970 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2972 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2973 $this->_qill
[$grouping][] = ts('Not a CMS User');
2978 * All tag search specific
2984 public function tagSearch(&$values) {
2985 list($name, $op, $value, $grouping, $wildcard) = $values;
2988 $value = "%{$value}%";
2991 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2992 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2994 $etTable = "`civicrm_entity_tag-" . $value . "`";
2995 $tTable = "`civicrm_tag-" . $value . "`";
2997 if ($useAllTagTypes[2]) {
2998 $this->_tables
[$etTable] =
2999 $this->_whereTables
[$etTable] =
3000 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3001 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3003 // search tag in cases
3004 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3005 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
3006 $this->_tables
[$etCaseTable] =
3007 $this->_whereTables
[$etCaseTable] =
3008 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3009 LEFT JOIN civicrm_case
3010 ON (civicrm_case_contact.case_id = civicrm_case.id
3011 AND civicrm_case.is_deleted = 0 )
3012 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3013 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3014 // search tag in activities
3015 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3016 $tActTable = "`civicrm_act_tag-" . $value . "`";
3017 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3018 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3020 $this->_tables
[$etActTable] =
3021 $this->_whereTables
[$etActTable] =
3022 " LEFT JOIN civicrm_activity_contact
3023 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3024 LEFT JOIN civicrm_activity
3025 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3026 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3027 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3028 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3030 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $value . "' OR {$tCaseTable}.name $op '" . $value . "' OR {$tActTable}.name $op '" . $value . "')";
3031 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
3034 $etTable = "`civicrm_entity_tag-" . $value . "`";
3035 $tTable = "`civicrm_tag-" . $value . "`";
3036 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3037 {$etTable}.entity_table = 'civicrm_contact' )
3038 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3040 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3041 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
3046 * Where / qill clause for tag
3052 public function tag(&$values) {
3053 list($name, $op, $value, $grouping, $wildcard) = $values;
3055 $tagNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
3056 if (is_array($value)) {
3057 if (count($value) > 1) {
3058 $this->_useDistinct
= TRUE;
3060 foreach ($value as $id => $dontCare) {
3061 $names[] = CRM_Utils_Array
::value($id, $tagNames);
3063 $names = implode(' ' . ts('or') . ' ', $names);
3064 $value = implode(',', array_keys($value));
3067 $names = CRM_Utils_Array
::value($value, $tagNames);
3071 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3072 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3074 $etTable = "`civicrm_entity_tag-" . $value . "`";
3076 if ($useAllTagTypes[2]) {
3077 $this->_tables
[$etTable] =
3078 $this->_whereTables
[$etTable] =
3079 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3081 // search tag in cases
3082 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3083 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3084 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3086 $this->_tables
[$etCaseTable] =
3087 $this->_whereTables
[$etCaseTable] =
3088 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3089 LEFT JOIN civicrm_case
3090 ON (civicrm_case_contact.case_id = civicrm_case.id
3091 AND civicrm_case.is_deleted = 0 )
3092 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3093 // search tag in activities
3094 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3095 $this->_tables
[$etActTable] =
3096 $this->_whereTables
[$etActTable] =
3097 " LEFT JOIN civicrm_activity_contact
3098 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3099 LEFT JOIN civicrm_activity
3100 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3101 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3102 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3105 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3106 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3109 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3111 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
3114 $this->_tables
[$etTable] =
3115 $this->_whereTables
[$etTable] =
3116 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3119 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3120 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3121 $op = str_replace('EMPTY', 'NULL', $op);
3122 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3125 $this->_where
[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
3127 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $names;
3133 * Where/qill clause for notes
3139 public function notes(&$values) {
3140 list($name, $op, $value, $grouping, $wildcard) = $values;
3142 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3143 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3144 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3146 $this->_useDistinct
= TRUE;
3148 $this->_tables
['civicrm_note'] =
3149 $this->_whereTables
['civicrm_note'] =
3150 " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3152 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3154 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3155 if ($wildcard ||
$op == 'LIKE') {
3156 if (strpos($value, '%') === FALSE) {
3157 $value = "%$value%";
3161 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3167 if ($noteOption %
2 == 0) {
3168 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3169 $label = ts('Note: Body Only');
3171 if ($noteOption %
3 == 0) {
3172 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3173 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3175 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3176 $this->_qill
[$grouping][] = $label . " $op - '$n'";
3180 * @param string $name
3186 public function nameNullOrEmptyOp($name, $op, $grouping) {
3190 $this->_where
[$grouping][] = "contact_a.$name $op";
3191 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3195 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3196 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3199 case 'IS NOT EMPTY':
3200 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3201 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3210 * Where / qill clause for sort_name
3216 public function sortName(&$values) {
3217 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3219 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3220 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3224 $input = $value = trim($value);
3226 if (!strlen($value)) {
3230 $config = CRM_Core_Config
::singleton();
3234 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3237 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3239 $firstChar = substr($value, 0, 1);
3240 $lastChar = substr($value, -1, 1);
3241 $quotes = array("'", '"');
3242 // If string is quoted, strip quotes and otherwise don't alter it
3243 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3244 $value = trim($value, implode('', $quotes));
3246 // Replace spaces with wildcards for a LIKE operation
3247 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3248 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3249 $value = str_replace(' ', '%', $value);
3251 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($value)));
3252 if (strlen($value)) {
3253 $fieldsub = array();
3254 if ($wildcard && $op == 'LIKE') {
3255 if ($config->includeWildCardInName
) {
3256 $value = "'%$value%'";
3259 $value = "'$value%'";
3264 $value = "'$value'";
3266 if ($fieldName == 'sort_name') {
3267 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3270 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3272 $fieldsub[] = " ( $wc $op $value )";
3273 if ($config->includeNickNameInName
) {
3274 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3275 $fieldsub[] = " ( $wc $op $value )";
3277 if ($config->includeEmailInName
) {
3278 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3280 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3283 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3285 $this->_where
[$grouping][] = $sub;
3286 if ($config->includeEmailInName
) {
3287 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3288 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3291 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3296 * Where / qill clause for email
3302 public function email(&$values) {
3303 list($name, $op, $value, $grouping, $wildcard) = $values;
3307 $config = CRM_Core_Config
::singleton();
3309 if (substr($n, 0, 1) == '"' &&
3310 substr($n, -1, 1) == '"'
3312 $n = substr($n, 1, -1);
3313 $value = strtolower(CRM_Core_DAO
::escapeString($n));
3314 $value = "'$value'";
3318 $value = strtolower($n);
3320 if (strpos($value, '%') === FALSE) {
3321 $value = "%{$value}%";
3326 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3327 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3330 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3331 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3334 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3338 * Where / qill clause for phone number
3344 public function phone_numeric(&$values) {
3345 list($name, $op, $value, $grouping, $wildcard) = $values;
3346 // Strip non-numeric characters; allow wildcards
3347 $number = preg_replace('/[^\d%]/', '', $value);
3349 if (strpos($number, '%') === FALSE) {
3350 $number = "%$number%";
3353 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3354 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3355 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3360 * Where / qill clause for phone type/location
3366 public function phone_option_group($values) {
3367 list($name, $op, $value, $grouping, $wildcard) = $values;
3368 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3369 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3370 $optionName = $options[$value];
3371 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3372 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3373 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3377 * Where / qill clause for street_address
3383 public function street_address(&$values) {
3384 list($name, $op, $value, $grouping, $wildcard) = $values;
3393 $value = strtolower($n);
3394 if (strpos($value, '%') === FALSE) {
3395 // only add wild card if not there
3396 $value = "%{$value}%";
3399 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3400 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3403 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3404 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3407 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3411 * Where / qill clause for street_unit
3417 public function street_number(&$values) {
3418 list($name, $op, $value, $grouping, $wildcard) = $values;
3426 if (strtolower($n) == 'odd') {
3427 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3428 $this->_qill
[$grouping][] = ts('Street Number is odd');
3430 elseif (strtolower($n) == 'even') {
3431 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3432 $this->_qill
[$grouping][] = ts('Street Number is even');
3435 $value = strtolower($n);
3437 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3438 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3441 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3445 * Where / qill clause for sorting by character
3451 public function sortByCharacter(&$values) {
3452 list($name, $op, $value, $grouping, $wildcard) = $values;
3454 $name = trim($value);
3455 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3456 $this->_where
[$grouping][] = $cond;
3457 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3461 * Where / qill clause for including contact ids
3465 public function includeContactIDs() {
3466 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3470 $contactIds = array();
3471 foreach ($this->_params
as $id => $values) {
3472 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3473 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3476 if (!empty($contactIds)) {
3477 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3482 * Where / qill clause for postal code
3488 public function postalCode(&$values) {
3489 // skip if the fields dont have anything to do with postal_code
3490 if (empty($this->_fields
['postal_code'])) {
3494 list($name, $op, $value, $grouping, $wildcard) = $values;
3496 // Handle numeric postal code range searches properly by casting the column as numeric
3497 if (is_numeric($value)) {
3498 $field = 'ROUND(civicrm_address.postal_code)';
3499 $val = CRM_Utils_Type
::escape($value, 'Integer');
3502 $field = 'civicrm_address.postal_code';
3503 $val = CRM_Utils_Type
::escape($value, 'String');
3506 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3508 if ($name == 'postal_code') {
3509 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3510 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3512 elseif ($name == 'postal_code_low') {
3513 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3514 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3516 elseif ($name == 'postal_code_high') {
3517 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3518 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3523 * Where / qill clause for location type
3526 * @param null $status
3530 public function locationType(&$values, $status = NULL) {
3531 list($name, $op, $value, $grouping, $wildcard) = $values;
3533 if (is_array($value)) {
3534 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3535 $this->_tables
['civicrm_address'] = 1;
3536 $this->_whereTables
['civicrm_address'] = 1;
3538 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3540 foreach ($value as $id) {
3541 $names[] = $locationType[$id];
3544 $this->_primaryLocation
= FALSE;
3547 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3550 return implode(' ' . ts('or') . ' ', $names);
3557 * @param bool $fromStateProvince
3561 public function country(&$values, $fromStateProvince = TRUE) {
3562 list($name, $op, $value, $grouping, $wildcard) = $values;
3564 if (!$fromStateProvince) {
3565 $stateValues = $this->getWhereValues('state_province', $grouping);
3566 if (!empty($stateValues)) {
3567 // return back to caller if there are state province values
3568 // since that handles this case
3573 $countryClause = $countryQill = NULL;
3579 $this->_tables
['civicrm_address'] = 1;
3580 $this->_whereTables
['civicrm_address'] = 1;
3582 $countries = CRM_Core_PseudoConstant
::country();
3583 if (is_numeric($value)) {
3584 $countryClause = self
::buildClause(
3585 'civicrm_address.country_id',
3590 $countryName = $countries[(int ) $value];
3594 $intValues = self
::parseSearchBuilderString($value);
3595 if ($intValues && ($op == 'IN' ||
$op == 'NOT IN')) {
3596 $countryClause = self
::buildClause(
3597 'civicrm_address.country_id',
3602 $countryNames = array();
3603 foreach ($intValues as $v) {
3604 $countryNames[] = $countries[$v];
3606 $countryName = implode(',', $countryNames);
3609 $countries = CRM_Core_PseudoConstant
::country();
3610 $intVal = CRM_Utils_Array
::key($value, $countries);
3611 $countryClause = self
::buildClause(
3612 'civicrm_address.country_id',
3617 $countryName = $value;
3620 $countryQill = ts('Country') . " {$op} '$countryName'";
3622 if (!$fromStateProvince) {
3623 $this->_where
[$grouping][] = $countryClause;
3624 $this->_qill
[$grouping][] = $countryQill;
3628 if ($fromStateProvince) {
3629 if (!empty($countryClause)) {
3632 " ...AND... " . $countryQill,
3636 return array(NULL, NULL);
3642 * Where / qill clause for county (if present)
3645 * @param null $status
3649 public function county(&$values, $status = NULL) {
3650 list($name, $op, $value, $grouping, $wildcard) = $values;
3652 if (!is_array($value)) {
3653 // force the county to be an array
3654 $value = array($value);
3657 // check if the values are ids OR names of the counties
3658 $inputFormat = 'id';
3659 foreach ($value as $v) {
3660 if (!is_numeric($v)) {
3661 $inputFormat = 'name';
3669 else if ($op == '!=') {
3673 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3674 $op = str_replace('EMPTY', 'NULL', $op);
3677 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3678 $clause = "civicrm_address.county_id $op";
3680 elseif ($inputFormat == 'id') {
3681 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3683 $county = CRM_Core_PseudoConstant
::county();
3684 foreach ($value as $id) {
3685 $names[] = CRM_Utils_Array
::value($id, $county);
3689 $inputClause = array();
3690 $county = CRM_Core_PseudoConstant
::county();
3691 foreach ($value as $name) {
3692 $name = trim($name);
3693 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3695 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3698 $this->_tables
['civicrm_address'] = 1;
3699 $this->_whereTables
['civicrm_address'] = 1;
3701 $this->_where
[$grouping][] = $clause;
3703 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3706 return implode(' ' . ts('or') . ' ', $names);
3711 * Where / qill clause for state/province AND country (if present)
3714 * @param null $status
3718 public function stateProvince(&$values, $status = NULL) {
3719 list($name, $op, $value, $grouping, $wildcard) = $values;
3721 // quick escape for IS NULL
3722 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3725 else if (!is_array($value)) {
3726 // force the state to be an array
3727 // check if its in the mapper format!
3728 $values = self
::parseSearchBuilderString($value);
3729 if (is_array($values)) {
3733 $value = array($value);
3737 // check if the values are ids OR names of the states
3738 $inputFormat = 'id';
3740 foreach ($value as $v) {
3741 if (!is_numeric($v)) {
3742 $inputFormat = 'name';
3752 else if ($op == '!=') {
3756 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3757 $op = str_replace('EMPTY', 'NULL', $op);
3759 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3760 $stateClause = "civicrm_address.state_province_id $op";
3762 else if ($inputFormat == 'id') {
3763 if ($op != 'NOT IN') {
3766 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
3768 foreach ($value as $id) {
3769 $names[] = CRM_Core_PseudoConstant
::stateProvince($id, FALSE);
3773 $inputClause = array();
3774 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3775 foreach ($value as $name) {
3776 $name = trim($name);
3777 $inputClause[] = CRM_Utils_Array
::key($name, $stateProvince);
3779 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
3782 $this->_tables
['civicrm_address'] = 1;
3783 $this->_whereTables
['civicrm_address'] = 1;
3785 $countryValues = $this->getWhereValues('country', $grouping);
3786 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3788 if ($countryClause) {
3789 $clause = "( $stateClause AND $countryClause )";
3792 $clause = $stateClause;
3795 $this->_where
[$grouping][] = $clause;
3797 $this->_qill
[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3800 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
3805 * Where / qill clause for change log
3811 public function changeLog(&$values) {
3812 list($name, $op, $value, $grouping, $wildcard) = $values;
3814 $targetName = $this->getWhereValues('changed_by', $grouping);
3819 $name = trim($targetName[2]);
3820 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3821 $name = $targetName[4] ?
"%$name%" : $name;
3822 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3823 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3824 $this->_qill
[$grouping][] = ts('Modified By') . " $name";
3830 public function modifiedDates($values) {
3831 $this->_useDistinct
= TRUE;
3833 // CRM-11281, default to added date if not set
3834 $fieldTitle = ts('Added Date');
3835 $fieldName = 'created_date';
3836 foreach (array_keys($this->_params
) as $id) {
3837 if ($this->_params
[$id][0] == 'log_date') {
3838 if ($this->_params
[$id][2] == 2) {
3839 $fieldTitle = ts('Modified Date');
3840 $fieldName = 'modified_date';
3846 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3848 self
::$_openedPanes[ts('Change Log')] = TRUE;
3854 public function demographics(&$values) {
3855 list($name, $op, $value, $grouping, $wildcard) = $values;
3857 if (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3859 $this->dateQueryBuilder($values,
3860 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3863 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3865 $this->dateQueryBuilder($values,
3866 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3870 self
::$_openedPanes[ts('Demographics')] = TRUE;
3876 public function privacy(&$values) {
3877 list($name, $op, $value, $grouping, $wildcard) = $values;
3878 //fixed for profile search listing CRM-4633
3879 if (strpbrk($value, "[")) {
3880 $value = "'{$value}'";
3882 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3885 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3887 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3888 $title = $field ?
$field['title'] : $name;
3889 $this->_qill
[$grouping][] = "$title $op $value";
3895 public function privacyOptions($values) {
3896 list($name, $op, $value, $grouping, $wildcard) = $values;
3898 if (empty($value) ||
!is_array($value)) {
3902 // get the operator and toggle values
3903 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3906 strtolower($opValues[2] == 'AND')
3911 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3913 if ($toggleValues &&
3914 $toggleValues[2] == 2
3921 foreach ($value as $dontCare => $pOption) {
3922 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
3923 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3924 $title = $field ?
$field['title'] : $pOption;
3925 $qill[] = " $title = 1 ";
3928 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
3929 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
3935 public function preferredCommunication(&$values) {
3936 list($name, $op, $value, $grouping, $wildcard) = $values;
3939 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3942 elseif (!is_array($value)) {
3944 $value = trim($value, ' ()');
3945 if (strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
3946 $v = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
3949 $v = explode(",", $value);
3952 foreach ($v as $item) {
3959 foreach ($value as $key => $checked) {
3966 $commPref = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
3968 $sqlValue = array();
3969 $showValue = array();
3970 $sql = "contact_a.preferred_communication_method";
3971 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3972 $sqlValue[] = "{$sql} {$op}";
3975 foreach ($pref as $val) {
3976 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $val . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' ) ";
3977 $showValue[] = $commPref[$val];
3980 $this->_where
[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
3981 $this->_qill
[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
3985 * Where / qill clause for relationship
3991 public function relationship(&$values) {
3992 list($name, $op, $value, $grouping, $wildcard) = $values;
3993 if ($this->_relationshipValuesAdded
) {
3996 // also get values array for relation_target_name
3997 // for relationship search we always do wildcard
3998 $relationType = $this->getWhereValues('relation_type_id', $grouping);
3999 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4000 $relStatus = $this->getWhereValues('relation_status', $grouping);
4001 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4002 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4004 $nameClause = $name = NULL;
4006 $name = trim($targetName[2]);
4007 if (substr($name, 0, 1) == '"' &&
4008 substr($name, -1, 1) == '"'
4010 $name = substr($name, 1, -1);
4011 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4012 $nameClause = "= '$name'";
4015 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4016 $nameClause = "LIKE '%{$name}%'";
4020 $rTypeValues = array();
4021 if (!empty($relationType)) {
4022 $rel = explode('_', $relationType[2]);
4023 self
::$_relType = $rel[1];
4024 $params = array('id' => $rel[0]);
4025 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
4027 if (!empty($rTypeValues) && $rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
4028 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4029 //@todo unless we are dealing with a target group
4030 self
::$_relType = 'reciprocal';
4032 // if we are creating a temp table we build our own where for the relationship table
4033 $relationshipTempTable = NULL;
4034 if (self
::$_relType == 'reciprocal' && empty($targetGroup)) {
4036 self
::$_relationshipTempTable =
4037 $relationshipTempTable =
4038 CRM_Core_DAO
::createTempTableName('civicrm_rel');
4040 $where[$grouping][] = " sort_name $nameClause ";
4044 $where = &$this->_where
;
4046 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4051 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
4052 $relTypeOrg = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
4053 $relTypeHou = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Household');
4054 $allRelationshipType = array();
4055 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
4056 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
4058 if ($nameClause ||
!$targetGroup) {
4059 if (!empty($relationType)) {
4060 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " $name";
4063 $this->_qill
[$grouping][] = $name;
4068 //check to see if the target contact is in specified group
4070 //add contacts from static groups
4071 $this->_tables
['civicrm_relationship_group_contact'] =
4072 $this->_whereTables
['civicrm_relationship_group_contact'] =
4073 " 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'";
4075 "( civicrm_relationship_group_contact.group_id IN (" .
4076 implode(",", $targetGroup[2]) . ") ) ";
4078 //add contacts from saved searches
4079 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
4081 //set the group where clause
4083 $groupWhere[] = "( " . $ssWhere . " )";
4085 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4087 //Get the names of the target groups for the qill
4088 $groupNames = CRM_Core_PseudoConstant
::group();
4089 $qillNames = array();
4090 foreach ($targetGroup[2] as $groupId) {
4091 if (array_key_exists($groupId, $groupNames)) {
4092 $qillNames[] = $groupNames[$groupId];
4095 if (!empty($relationType)) {
4096 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " ( " . implode(", ", $qillNames) . " )";
4099 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4103 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4104 $today = date('Ymd');
4105 //check for active, inactive and all relation status
4106 if ($relStatus[2] == 0) {
4107 $where[$grouping][] = "(
4108 civicrm_relationship.is_active = 1 AND
4109 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4110 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4112 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4114 elseif ($relStatus[2] == 1) {
4115 $where[$grouping][] = "(
4116 civicrm_relationship.is_active = 0 OR
4117 civicrm_relationship.end_date < {$today} OR
4118 civicrm_relationship.start_date > {$today}
4120 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4124 if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
)) {
4127 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4129 //check for permissioned, non-permissioned and all permissioned relations
4130 if ($relPermission[2] == 1) {
4131 $where[$grouping][] = "(
4132 civicrm_relationship.is_permission_a_b = 1
4134 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4136 elseif ($relPermission[2] == 2) {
4137 //non-allowed permission relationship.
4138 $where[$grouping][] = "(
4139 civicrm_relationship.is_permission_a_b = 0
4141 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4144 $this->addRelationshipDateClauses($grouping, $where);
4145 if (!empty($relationType) && !empty($rType) && isset($rType->id
)) {
4146 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
4148 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4149 $this->_useDistinct
= TRUE;
4150 $this->_relationshipValuesAdded
= TRUE;
4151 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4153 // @todo creating a temp table could be expanded to group filter
4154 // as even creating a temp table of all relationships is much much more efficient than
4155 // an OR in the join
4156 if ($relationshipTempTable) {
4158 if (!empty($where[$grouping])) {
4159 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4162 CREATE TEMPORARY TABLE {$relationshipTempTable}
4163 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4164 FROM civicrm_relationship
4165 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4168 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4169 FROM civicrm_relationship
4170 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4173 CRM_Core_DAO
::executeQuery($sql);
4179 * Add start & end date criteria in
4180 * @param string $grouping
4181 * @param array $where
4182 * = array to add where clauses to, in case you are generating a temp table.
4183 * not the main query.
4185 public function addRelationshipDateClauses($grouping, &$where) {
4186 $dateValues = array();
4192 foreach ($dateTypes as $dateField) {
4193 $dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping);
4194 $dateValueHigh = $this->getWhereValues('relation_' . $dateField . '_high', $grouping);
4195 if (!empty($dateValueLow)) {
4196 $date = date('Ymd', strtotime($dateValueLow[2]));
4197 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4198 $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);
4200 if (!empty($dateValueHigh)) {
4201 $date = date('Ymd', strtotime($dateValueHigh[2]));
4202 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4203 $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);
4209 * Default set of return properties
4213 * @return array derault return properties
4215 public static function &defaultReturnProperties($mode = 1) {
4216 if (!isset(self
::$_defaultReturnProperties)) {
4217 self
::$_defaultReturnProperties = array();
4220 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4221 // add activity return properties
4222 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4223 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4226 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4229 if (empty(self
::$_defaultReturnProperties[$mode])) {
4230 self
::$_defaultReturnProperties[$mode] = array(
4233 'legal_identifier' => 1,
4234 'external_identifier' => 1,
4235 'contact_type' => 1,
4236 'contact_sub_type' => 1,
4238 'display_name' => 1,
4239 'preferred_mail_format' => 1,
4246 'formal_title' => 1,
4247 'communication_style_id' => 1,
4250 'street_address' => 1,
4251 'supplemental_address_1' => 1,
4252 'supplemental_address_2' => 1,
4255 'postal_code_suffix' => 1,
4256 'state_province' => 1,
4258 'world_region' => 1,
4265 'household_name' => 1,
4266 'organization_name' => 1,
4267 'deceased_date' => 1,
4272 'current_employer' => 1,
4273 // FIXME: should we use defaultHierReturnProperties() for the below?
4274 'do_not_email' => 1,
4277 'do_not_phone' => 1,
4278 'do_not_trade' => 1,
4280 'contact_is_deleted' => 1,
4281 'preferred_communication_method' => 1,
4282 'preferred_language' => 1,
4286 return self
::$_defaultReturnProperties[$mode];
4290 * Get primary condition for a sql clause
4294 * @return string|NULL
4296 public static function getPrimaryCondition($value) {
4297 if (is_numeric($value)) {
4298 $value = (int ) $value;
4299 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4305 * Wrapper for a simple search query
4307 * @param array $params
4308 * @param array $returnProperties
4309 * @param bool $count
4313 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4314 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4315 list($select, $from, $where, $having) = $query->query();
4317 return "$select $from $where $having";
4321 * These are stub comments as this function needs more explanation - particularly in terms of how it
4322 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4324 * This function was originally written as a wrapper for the api query but is called from multiple places
4325 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4326 * but it is unclear as to whehter that is historical or there is a reason
4327 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4329 * @param array $params
4330 * @param array $returnProperties
4331 * @param null $fields
4332 * @param string $sort
4333 * @param int $offset
4334 * @param int $row_count
4335 * @param bool $smartGroupCache
4336 * ?? update smart group cache?.
4337 * @param bool $count
4338 * Return count obnly.
4339 * @param bool $skipPermissions
4340 * Should permissions be ignored or should the logged in user's permissions be applied.
4345 static function apiQuery(
4347 $returnProperties = NULL,
4352 $smartGroupCache = TRUE,
4354 $skipPermissions = TRUE
4357 $query = new CRM_Contact_BAO_Query(
4358 $params, $returnProperties,
4359 NULL, TRUE, FALSE, 1,
4361 TRUE, $smartGroupCache
4364 //this should add a check for view deleted if permissions are enabled
4365 if ($skipPermissions) {
4366 $query->_skipDeleteClause
= TRUE;
4368 $query->generatePermissionClause(FALSE, $count);
4370 // note : this modifies _fromClause and _simpleFromClause
4371 $query->includePseudoFieldsJoin($sort);
4373 list($select, $from, $where, $having) = $query->query($count);
4375 $options = $query->_options
;
4376 if (!empty($query->_permissionWhereClause
)) {
4377 if (empty($where)) {
4378 $where = "WHERE $query->_permissionWhereClause";
4381 $where = "$where AND $query->_permissionWhereClause";
4385 $sql = "$select $from $where $having";
4388 if ($query->_useGroupBy
) {
4389 $sql .= ' GROUP BY contact_a.id';
4391 if (!empty($sort)) {
4392 $sort = CRM_Utils_Type
::escape($sort, 'String');
4393 $sql .= " ORDER BY $sort ";
4395 if ($row_count > 0 && $offset >= 0) {
4396 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4397 $rowCount = CRM_Utils_Type
::escape($row_count, 'Int');
4398 $sql .= " LIMIT $offset, $row_count ";
4401 $dao = CRM_Core_DAO
::executeQuery($sql);
4404 while ($dao->fetch()) {
4406 $noRows = $dao->rowCount
;
4408 return array($noRows, NULL);
4410 $val = $query->store($dao);
4411 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4413 if (!empty($convertedVals)) {
4414 $val = array_replace_recursive($val, $convertedVals);
4416 $values[$dao->contact_id
] = $val;
4419 return array($values, $options);
4423 * Create and query the db for an contact search
4425 * @param int $offset
4426 * The offset for the query.
4427 * @param int $rowCount
4428 * The number of rows to return.
4429 * @param string $sort
4430 * The order by string.
4431 * @param bool $count
4432 * Is this a count only query ?.
4433 * @param bool $includeContactIds
4434 * Should we include contact ids?.
4435 * @param bool $sortByChar
4436 * If true returns the distinct array of first characters for search results.
4437 * @param bool $groupContacts
4438 * If true, return only the contact ids.
4439 * @param bool $returnQuery
4440 * Should we return the query as a string.
4441 * @param string $additionalWhereClause
4442 * If the caller wants to further restrict the search (used for components).
4443 * @param null $sortOrder
4444 * @param string $additionalFromClause
4445 * Should be clause with proper joins, effective to reduce where clause load.
4447 * @param bool $skipOrderAndLimit
4449 * @return CRM_Core_DAO
4451 function searchQuery(
4452 $offset = 0, $rowCount = 0, $sort = NULL,
4453 $count = FALSE, $includeContactIds = FALSE,
4454 $sortByChar = FALSE, $groupContacts = FALSE,
4455 $returnQuery = FALSE,
4456 $additionalWhereClause = NULL, $sortOrder = NULL,
4457 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4460 if ($includeContactIds) {
4461 $this->_includeContactIds
= TRUE;
4462 $this->_whereClause
= $this->whereClause();
4465 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4467 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4468 // and that contact happens to be deleted, set $onlyDeleted to true
4469 foreach ($this->_params
as $values) {
4470 $name = CRM_Utils_Array
::value(0, $values);
4471 $op = CRM_Utils_Array
::value(1, $values);
4472 $value = CRM_Utils_Array
::value(2, $values);
4473 if ($name == 'contact_id' and $op == '=') {
4474 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4475 $onlyDeleted = TRUE;
4481 // building the query string
4484 if (isset($this->_groupByComponentClause
)) {
4485 $groupBy = $this->_groupByComponentClause
;
4487 elseif ($this->_useGroupBy
) {
4488 $groupBy = ' GROUP BY contact_a.id';
4491 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4492 $groupBy = 'GROUP BY civicrm_activity.id ';
4495 $order = $orderBy = $limit = '';
4497 $config = CRM_Core_Config
::singleton();
4498 if ($config->includeOrderByClause ||
4499 isset($this->_distinctComponentClause
)
4502 if (is_string($sort)) {
4506 $orderBy = trim($sort->orderBy());
4508 if (!empty($orderBy)) {
4509 // this is special case while searching for
4510 // change log CRM-1718
4511 if (preg_match('/sort_name/i', $orderBy)) {
4512 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4515 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
4516 $order = " ORDER BY $orderBy";
4519 $sortOrder = CRM_Utils_Type
::escape($sortOrder, 'String');
4520 $order .= " $sortOrder";
4523 // always add contact_a.id to the ORDER clause
4524 // so the order is deterministic
4525 if (strpos('contact_a.id', $order) === FALSE) {
4526 $order .= ", contact_a.id";
4530 elseif ($sortByChar) {
4531 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4534 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4538 // hack for order clause
4540 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4541 $fieldOrder = explode(' ', $fieldStr);
4542 $field = $fieldOrder[0];
4548 $this->_whereTables
["civicrm_address"] = 1;
4549 $order = str_replace($field, "civicrm_address.{$field}", $order);
4553 case 'state_province':
4554 $this->_whereTables
["civicrm_{$field}"] = 1;
4555 $order = str_replace($field, "civicrm_{$field}.name", $order);
4559 $this->_whereTables
["civicrm_email"] = 1;
4560 $order = str_replace($field, "civicrm_email.{$field}", $order);
4564 //CRM-12565 add "`" around $field if it is a pseudo constant
4565 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
4566 if (!empty($value['element']) && $value['element'] == $field) {
4567 $order = str_replace($field, "`{$field}`", $order);
4571 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4572 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4576 if ($rowCount > 0 && $offset >= 0) {
4577 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4578 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4579 $limit = " LIMIT $offset, $rowCount ";
4584 $this->_sort
= $sort;
4586 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4588 if ($additionalWhereClause) {
4589 $where = $where . ' AND ' . $additionalWhereClause;
4592 //additional from clause should be w/ proper joins.
4593 if ($additionalFromClause) {
4594 $from .= "\n" . $additionalFromClause;
4597 // if we are doing a transform, do it here
4598 // use the $from, $where and $having to get the contact ID
4599 if ($this->_displayRelationshipType
) {
4600 $this->filterRelatedContacts($from, $where, $having);
4603 if ($skipOrderAndLimit) {
4604 $query = "$select $from $where $having $groupBy";
4607 $query = "$select $from $where $having $groupBy $order $limit";
4614 return CRM_Core_DAO
::singleValueQuery($query);
4617 $dao = CRM_Core_DAO
::executeQuery($query);
4618 if ($groupContacts) {
4620 while ($dao->fetch()) {
4623 return implode(',', $ids);
4630 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4632 * @param string $cacheKey
4633 * @param int $offset
4634 * @param int $rowCount
4635 * @param bool $includeContactIds
4636 * @return CRM_Core_DAO
4638 public function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4639 $this->_includeContactIds
= $includeContactIds;
4640 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4641 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
4642 $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);
4643 $order = " ORDER BY pnc.id";
4644 $groupBy = " GROUP BY contact_a.id";
4645 $limit = " LIMIT $offset, $rowCount";
4646 $query = "$select $from $where $groupBy $order $limit";
4648 return CRM_Core_DAO
::executeQuery($query);
4652 * Populate $this->_permissionWhereClause with permission related clause and update other
4653 * query related properties.
4655 * Function calls ACL permission class and hooks to filter the query appropriately
4657 * Note that these 2 params were in the code when extracted from another function
4658 * and a second round extraction would be to make them properties of the class
4660 * @param bool $onlyDeleted
4661 * Only get deleted contacts.
4662 * @param bool $count
4663 * Return Count only.
4667 public 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 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4686 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4687 // note : this modifies _fromClause and _simpleFromClause
4688 $this->includePseudoFieldsJoin($this->_sort
);
4692 // add delete clause if needed even if we are skipping permission
4694 if (!$this->_skipDeleteClause
) {
4695 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4696 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4700 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4709 public function setSkipPermission($val) {
4710 $this->_skipPermission
= $val;
4714 * @param null $context
4718 public function &summaryContribution($context = NULL) {
4719 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4723 SELECT COUNT( conts.total_amount ) as total_count,
4724 SUM( conts.total_amount ) as total_amount,
4725 AVG( conts.total_amount ) as total_avg,
4726 conts.currency as currency";
4727 if ($this->_permissionWhereClause
) {
4728 $where .= " AND " . $this->_permissionWhereClause
;
4730 if ($context == 'search') {
4731 $where .= " AND contact_a.is_deleted = 0 ";
4734 // make sure contribution is completed - CRM-4989
4735 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4739 $summary['total'] = array();
4740 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4742 $query = "$select FROM (
4743 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $completedWhere
4744 GROUP BY civicrm_contribution.id
4748 $dao = CRM_Core_DAO
::executeQuery($query);
4750 $summary['total']['count'] = 0;
4751 $summary['total']['amount'] = $summary['total']['avg'] = array();
4752 while ($dao->fetch()) {
4753 $summary['total']['count'] +
= $dao->total_count
;
4754 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4755 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4757 if (!empty($summary['total']['amount'])) {
4758 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4759 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4762 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4765 // soft credit summary
4766 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
4767 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
4770 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
4771 GROUP BY civicrm_contribution_soft.id
4774 $dao = CRM_Core_DAO
::executeQuery($query);
4775 $summary['soft_credit']['count'] = 0;
4776 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
4777 while ($dao->fetch()) {
4778 $summary['soft_credit']['count'] +
= $dao->total_count
;
4779 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4780 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4782 if (!empty($summary['soft_credit']['amount'])) {
4783 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
4784 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
4787 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
4792 //@todo - this could be one query using the IF in mysql - eg
4793 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
4794 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
4795 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
4796 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
4797 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
4798 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
4799 // FROM civicrm_contact contact_a
4800 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
4801 // WHERE ( ... where clause....
4802 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
4806 SELECT COUNT( conts.total_amount ) as cancel_count,
4807 SUM( conts.total_amount ) as cancel_amount,
4808 AVG( conts.total_amount ) as cancel_avg,
4809 conts.currency as currency";
4811 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4812 if ($context == 'search') {
4813 $where .= " AND contact_a.is_deleted = 0 ";
4816 $query = "$select FROM (
4817 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
4818 GROUP BY civicrm_contribution.id
4822 $dao = CRM_Core_DAO
::executeQuery($query);
4825 if ($dao->fetch()) {
4826 $summary['cancel']['count'] = $dao->cancel_count
;
4827 $summary['cancel']['amount'] = $dao->cancel_amount
;
4828 $summary['cancel']['avg'] = $dao->cancel_avg
;
4832 $summary['cancel']['count'] = 0;
4833 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4834 while ($dao->fetch()) {
4835 $summary['cancel']['count'] +
= $dao->cancel_count
;
4836 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4837 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4839 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4840 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
4847 * Getter for the qill object
4851 public function qill() {
4852 return $this->_qill
;
4856 * Default set of return default hier return properties
4860 public static function &defaultHierReturnProperties() {
4861 if (!isset(self
::$_defaultHierReturnProperties)) {
4862 self
::$_defaultHierReturnProperties = array(
4865 'legal_identifier' => 1,
4866 'external_identifier' => 1,
4867 'contact_type' => 1,
4868 'contact_sub_type' => 1,
4870 'display_name' => 1,
4877 'formal_title' => 1,
4878 'communication_style_id' => 1,
4879 'email_greeting' => 1,
4880 'postal_greeting' => 1,
4884 'preferred_communication_method' => 1,
4885 'do_not_phone' => 1,
4886 'do_not_email' => 1,
4889 'do_not_trade' => 1,
4893 'location_type' => 1,
4894 'street_address' => 1,
4896 'state_province' => 1,
4898 'postal_code_suffix' => 1,
4901 'phone-Mobile' => 1,
4914 'location_type' => 1,
4915 'street_address' => 1,
4917 'state_province' => 1,
4919 'postal_code_suffix' => 1,
4922 'phone-Mobile' => 1,
4936 return self
::$_defaultHierReturnProperties;
4941 * @param string $tableName
4942 * @param string $fieldName
4943 * @param string $dbFieldName
4944 * @param $fieldTitle
4945 * @param bool $appendTimeStamp
4947 function dateQueryBuilder(
4948 &$values, $tableName, $fieldName,
4949 $dbFieldName, $fieldTitle,
4950 $appendTimeStamp = TRUE
4952 list($name, $op, $value, $grouping, $wildcard) = $values;
4958 if ($name == "{$fieldName}_low" ||
4959 $name == "{$fieldName}_high"
4961 if (isset($this->_rangeCache
[$fieldName])) {
4964 $this->_rangeCache
[$fieldName] = 1;
4966 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4968 if ($name == $fieldName . '_low') {
4970 $firstPhrase = ts('greater than or equal to');
4971 $firstDate = CRM_Utils_Date
::processDate($value);
4973 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4974 if (!empty($secondValues) && $secondValues[2]) {
4976 $secondPhrase = ts('less than or equal to');
4977 $secondValue = $secondValues[2];
4979 if ($appendTimeStamp && strlen($secondValue) == 10) {
4980 $secondValue .= ' 23:59:59';
4982 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4985 elseif ($name == $fieldName . '_high') {
4987 $firstPhrase = ts('less than or equal to');
4989 if ($appendTimeStamp && strlen($value) == 10) {
4990 $value .= ' 23:59:59';
4992 $firstDate = CRM_Utils_Date
::processDate($value);
4994 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4995 if (!empty($secondValues) && $secondValues[2]) {
4997 $secondPhrase = ts('greater than or equal to');
4998 $secondValue = $secondValues[2];
4999 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5003 if (!$appendTimeStamp) {
5004 $firstDate = substr($firstDate, 0, 8);
5006 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5009 if (!$appendTimeStamp) {
5010 $secondDate = substr($secondDate, 0, 8);
5012 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5015 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5017 $this->_where
[$grouping][] = "
5018 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5019 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5021 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5024 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5025 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5029 if ($name == $fieldName) {
5033 $date = CRM_Utils_Date
::processDate($value);
5035 if (!$appendTimeStamp) {
5036 $date = substr($date, 0, 8);
5039 $format = CRM_Utils_Date
::customFormat($date);
5042 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'";
5045 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op";
5047 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5048 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$format\"";
5054 * @param string $tableName
5055 * @param string $fieldName
5056 * @param string $dbFieldName
5057 * @param $fieldTitle
5058 * @param null $options
5060 function numberRangeBuilder(
5062 $tableName, $fieldName,
5063 $dbFieldName, $fieldTitle,
5066 list($name, $op, $value, $grouping, $wildcard) = $values;
5068 if ($name == "{$fieldName}_low" ||
5069 $name == "{$fieldName}_high"
5071 if (isset($this->_rangeCache
[$fieldName])) {
5074 $this->_rangeCache
[$fieldName] = 1;
5076 $secondOP = $secondPhrase = $secondValue = NULL;
5078 if ($name == "{$fieldName}_low") {
5080 $firstPhrase = ts('greater than');
5082 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5083 if (!empty($secondValues)) {
5085 $secondPhrase = ts('less than');
5086 $secondValue = $secondValues[2];
5091 $firstPhrase = ts('less than');
5093 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5094 if (!empty($secondValues)) {
5096 $secondPhrase = ts('greater than');
5097 $secondValue = $secondValues[2];
5102 $this->_where
[$grouping][] = "
5103 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5104 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5106 $displayValue = $options ?
$options[$value] : $value;
5107 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5109 $this->_qill
[$grouping][] =
5110 "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5113 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5114 $displayValue = $options ?
$options[$value] : $value;
5115 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5117 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5122 if ($name == $fieldName) {
5126 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5128 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5129 $displayValue = $options ?
$options[$value] : $value;
5130 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5137 * Given the field name, operator, value & its data type
5138 * builds the where Clause for the query
5139 * used for handling 'IS NULL'/'IS NOT NULL' operators
5141 * @param string $field
5145 * @param string $value
5147 * @param string $dataType
5148 * Data type of the field.
5150 * @return string where clause for the query
5152 public 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';
5193 if (is_array($value)) {
5194 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5195 // widely used and consistent across the codebase
5196 // adding this here won't accept the search functions which don't submit an array
5197 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, $value, $dataType)) != FALSE) {
5198 return $queryString;
5201 $value = CRM_Utils_Type
::escape($value, $dataType);
5202 // if we don't have a dataType we should assume
5203 if ($dataType == 'String' ||
$dataType == 'Text') {
5204 $value = "'" . strtolower($value) . "'";
5206 return "$clause $value";
5211 * @param bool $reset
5215 public function openedSearchPanes($reset = FALSE) {
5216 if (!$reset ||
empty($this->_whereTables
)) {
5217 return self
::$_openedPanes;
5220 // pane name to table mapper
5221 $panesMapper = array(
5222 ts('Contributions') => 'civicrm_contribution',
5223 ts('Memberships') => 'civicrm_membership',
5224 ts('Events') => 'civicrm_participant',
5225 ts('Relationships') => 'civicrm_relationship',
5226 ts('Activities') => 'civicrm_activity',
5227 ts('Pledges') => 'civicrm_pledge',
5228 ts('Cases') => 'civicrm_case',
5229 ts('Grants') => 'civicrm_grant',
5230 ts('Address Fields') => 'civicrm_address',
5231 ts('Notes') => 'civicrm_note',
5232 ts('Change Log') => 'civicrm_log',
5233 ts('Mailings') => 'civicrm_mailing_event_queue',
5235 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5237 foreach (array_keys($this->_whereTables
) as $table) {
5238 if ($panName = array_search($table, $panesMapper)) {
5239 self
::$_openedPanes[$panName] = TRUE;
5243 return self
::$_openedPanes;
5249 public function setOperator($operator) {
5250 $validOperators = array('AND', 'OR');
5251 if (!in_array($operator, $validOperators)) {
5254 $this->_operator
= $operator;
5260 public function getOperator() {
5261 return $this->_operator
;
5269 public function filterRelatedContacts(&$from, &$where, &$having) {
5270 static $_rTypeProcessed = NULL;
5271 static $_rTypeFrom = NULL;
5272 static $_rTypeWhere = NULL;
5274 if (!$_rTypeProcessed) {
5275 $_rTypeProcessed = TRUE;
5277 // create temp table with contact ids
5278 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5279 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5280 CRM_Core_DAO
::executeQuery($sql);
5283 REPLACE INTO $tableName ( contact_id )
5289 CRM_Core_DAO
::executeQuery($sql);
5291 $qillMessage = ts('Contacts with a Relationship Type of: ');
5292 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5294 if (is_numeric($this->_displayRelationshipType
)) {
5295 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5297 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5298 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5301 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5302 AND displayRelType.is_active = 1
5306 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5307 if ($dirOne == 'a') {
5308 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5310 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5311 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5315 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5317 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5318 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5322 WHERE displayRelType.relationship_type_id = $relType
5323 AND displayRelType.is_active = 1
5326 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5329 if (strpos($from, $_rTypeFrom) === FALSE) {
5330 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5331 // this happens when we have an event_type in the quert (CRM-7969)
5332 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5333 $from .= $_rTypeFrom;
5334 $where = $_rTypeWhere;
5345 public static function caseImportant($op) {
5347 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5351 * @param $returnProperties
5356 public static function componentPresent(&$returnProperties, $prefix) {
5357 foreach ($returnProperties as $name => $dontCare) {
5358 if (substr($name, 0, strlen($prefix)) == $prefix) {
5366 * Builds the necessary structures for all fields that are similar to option value lookups
5369 * String the name of the field.
5371 * String the sql operator, this function should handle ALL SQL operators.
5373 * String|integer|array depends on the operator and who's calling the query builder.
5375 * Int the index where to place the where clause.
5376 * @param $selectValues
5377 * The key value pairs for this element. This allows us to use this function for things besides option-value pairs.
5379 * Array an array that contains various properties of the field identified by $name.
5381 * String The label for this field element.
5383 * String The data type for this element.
5384 * @param bool $useIDsOnly
5386 * @return void adds the where clause and qill to the query object
5388 function optionValueQuery(
5396 $dataType = 'String',
5400 if (!empty($selectValues) && !is_array($value) && !empty($selectValues[$value])) {
5401 $qill = $selectValues[$value];
5407 $pseudoFields = array(
5414 'communication_style_id'
5417 if (is_numeric($value)) {
5418 $qill = $selectValues[(int ) $value];
5420 elseif ($op == 'IN' ||
$op == 'NOT IN') {
5421 if (is_array($value)) {
5423 $newValues = array();
5424 foreach ($value as $k => $v) {
5425 $intVals[$k] = (int) $k;
5426 $newValues[] = $selectValues[(int) $k];
5429 $value = (in_array($name, $pseudoFields)) ?
$intVals : $newValues;
5430 $qill = implode(', ', $newValues);
5433 elseif (!array_key_exists($value, $selectValues)) {
5434 // its a string, lets get the int value
5435 $value = array_search($value, $selectValues);
5438 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5439 if ($tableName == 'civicrm_contact') {
5440 $wc = "contact_a.$fieldName";
5443 $wc = "$tableName.id";
5447 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5450 if (in_array($name, $pseudoFields)) {
5451 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5452 $wc = "contact_a.{$name}_id";
5454 $dataType = 'Positive';
5455 $value = (!$value) ?
0 : $value;
5458 $this->_qill
[$grouping][] = $label . " $op '$qill'";
5459 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' ||
$op == 'RLIKE')) ?
'=' : $op;
5460 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5464 * Check and explode a user defined numeric string into an array
5465 * this was the protocol used by search builder in the old old days before we had
5466 * super nice js widgets to do the hard work
5468 * @param string $string
5469 * @param string $dataType
5470 * The dataType we should check for the values, default integer.
5472 * @return bool|array if string does not match the patter
5473 * array of numeric values if string does match the pattern
5476 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5477 $string = trim($string);
5478 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5482 $string = substr($string, 1, -1);
5483 $values = explode(',', $string);
5484 if (empty($values)) {
5488 $returnValues = array();
5489 foreach ($values as $v) {
5490 if ($dataType == 'Integer' && !is_numeric($v)) {
5493 else if ($dataType == 'String' && !is_string($v)) {
5496 $returnValues[] = trim($v);
5499 if (empty($returnValues)) {
5503 return $returnValues;
5507 * Convert the pseudo constants id's to their names
5509 * @param CRM_Core_DAO dao
5510 * @param bool $return
5514 public function convertToPseudoNames(&$dao, $return = FALSE) {
5515 if (empty($this->_pseudoConstantsSelect
)) {
5519 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5520 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5524 if (property_exists($dao, $value['idCol'])) {
5525 $val = $dao->$value['idCol'];
5527 if (CRM_Utils_System
::isNull($val)) {
5530 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5532 $idColumn = "{$key}_id";
5533 $dao->$idColumn = $val;
5535 if ($key == 'state_province_name') {
5536 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5539 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5542 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5543 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5545 // FIX ME: we should potentially move this to component Query and write a wrapper function that
5546 // handles pseudoconstant fixes for all component
5547 elseif ($value['pseudoField'] == 'participant_role') {
5548 $viewRoles = array();
5549 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val) as $k => $v) {
5550 $viewRoles[] = CRM_Event_PseudoConstant
::participantRole($v);
5552 $dao->$key = implode(', ', $viewRoles);
5555 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5556 $dao->$key = $labels[$val];
5559 // return converted values in array format
5561 if (strpos($key, '-') !== FALSE) {
5562 $keyVal = explode('-', $key);
5563 $current = &$values;
5564 $lastElement = array_pop($keyVal);
5565 foreach ($keyVal as $v) {
5566 if (!array_key_exists($v, $current)) {
5567 $current[$v] = array();
5569 $current = &$current[$v];
5571 $current[$lastElement] = $dao->$key;
5574 $values[$key] = $dao->$key;
5583 * Include pseudo fields LEFT JOIN
5584 * @param string|array $sort can be a object or string
5588 public function includePseudoFieldsJoin($sort) {
5589 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5592 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5595 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5596 if (!empty($value['table'])) {
5597 $regex = "/({$value['table']}\.|{$name})/";
5598 if (preg_match($regex, $sort)) {
5599 $this->_elemnt
[$value['element']] = 1;
5600 $this->_select
[$value['element']] = $value['select'];
5601 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5602 $present[$value['table']] = $value['join'];
5606 $presentSimpleFrom = $present;
5608 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5609 array_key_exists('civicrm_country', $presentSimpleFrom)
5611 unset($presentSimpleFrom['civicrm_country']);
5613 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5614 array_key_exists('civicrm_country', $present)
5616 unset($present['civicrm_country']);
5619 $presentClause = $presentSimpleFromClause = NULL;
5620 if (!empty($present)) {
5621 $presentClause = implode(' ', $present);
5623 if (!empty($presentSimpleFrom)) {
5624 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5627 $this->_fromClause
= $this->_fromClause
. $presentClause;
5628 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5630 return array($presentClause, $presentSimpleFromClause);