3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
35 * This is the heart of the search query building mechanism.
37 class CRM_Contact_BAO_Query
{
40 * The various search modes.
42 * As of February 2017, entries not present for 4, 32, 64, 1024.
44 * MODE_ALL seems to be out of sync with the available constants;
45 * if this is intentionally excluding MODE_MAILING then that may
48 * Likewise if there's reason for the missing modes (4, 32, 64 etc).
53 NO_RETURN_PROPERTIES
= 'CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES',
59 MODE_CONTACTSRELATED
= 32,
62 MODE_PLEDGEBANK
= 256,
72 * Constants for search operators
75 SEARCH_OPERATOR_AND
= 'AND',
76 SEARCH_OPERATOR_OR
= 'OR';
79 * The default set of return properties.
83 static $_defaultReturnProperties = NULL;
86 * The default set of hier return properties.
90 static $_defaultHierReturnProperties;
93 * The set of input params.
101 public $_paramLookup;
106 * The set of output params
110 public $_returnProperties;
120 * The name of the elements that are in the select clause
121 * used to extract the values.
128 * The tables involved in the query.
135 * The table involved in the where clause.
139 public $_whereTables;
142 * Array of WHERE clause components.
149 * The WHERE clause as a string.
153 public $_whereClause;
156 * Additional WHERE clause for permissions.
160 public $_permissionWhereClause;
170 * Additional permission from clause
174 public $_permissionFromClause;
177 * The from clause for the simple select and alphabetical
182 public $_simpleFromClause;
192 * The english language version of the query
199 * All the fields that could potentially be involved in
207 * The cache to translate the option values into labels.
214 * Are we in search mode.
218 public $_search = TRUE;
221 * Should we skip permission checking.
225 public $_skipPermission = FALSE;
228 * Should we skip adding of delete clause.
232 public $_skipDeleteClause = FALSE;
235 * Are we in strict mode (use equality over LIKE)
239 public $_strict = FALSE;
242 * What operator to use to group the clauses.
246 public $_operator = 'AND';
251 * Should we only search on primary location.
255 public $_primaryLocation = TRUE;
258 * Are contact ids part of the query.
262 public $_includeContactIds = FALSE;
265 * Should we use the smart group cache.
269 public $_smartGroupCache = TRUE;
272 * Should we display contacts with a specific relationship type.
276 public $_displayRelationshipType = NULL;
279 * Reference to the query object for custom values.
283 public $_customQuery;
286 * Should we enable the distinct clause, used if we are including
287 * more than one group
291 public $_useDistinct = FALSE;
294 * Should we just display one contact record
296 public $_useGroupBy = FALSE;
299 * The relationship type direction
310 static $_activityRole;
313 * Consider the component activity type
314 * during activity search.
318 static $_considerCompActivities;
321 * Consider with contact activities only,
322 * during activity search.
326 static $_withContactActivitiesOnly;
329 * Use distinct component clause for component searches
333 public $_distinctComponentClause;
335 public $_rowCountClause;
338 * Use groupBy component clause for component searches
342 public $_groupByComponentClause;
345 * Track open panes, useful in advance search
349 public static $_openedPanes = array();
352 * For search builder - which custom fields are location-dependent
355 public $_locationSpecificCustomFields = array();
358 * The tables which have a dependency on location and/or address
362 static $_dependencies = array(
363 'civicrm_state_province' => 1,
364 'civicrm_country' => 1,
365 'civicrm_county' => 1,
366 'civicrm_address' => 1,
367 'civicrm_location_type' => 1,
371 * List of location specific fields.
373 static $_locationSpecificFields = array(
378 'supplemental_address_1',
379 'supplemental_address_2',
380 'supplemental_address_3',
383 'postal_code_suffix',
397 * Remember if we handle either end of a number or date range
398 * so we can skip the other
400 protected $_rangeCache = array();
402 * Set to true when $this->relationship is run to avoid adding twice
405 protected $_relationshipValuesAdded = FALSE;
408 * Set to the name of the temp table if one has been created
411 static $_relationshipTempTable = NULL;
413 public $_pseudoConstantsSelect = array();
416 * Class constructor which also does all the work.
418 * @param array $params
419 * @param array $returnProperties
420 * @param array $fields
421 * @param bool $includeContactIds
422 * @param bool $strict
423 * @param bool|int $mode - mode the search is operating on
425 * @param bool $skipPermission
426 * @param bool $searchDescendentGroups
427 * @param bool $smartGroupCache
428 * @param null $displayRelationshipType
429 * @param string $operator
430 * @param string $apiEntity
431 * @param bool|NULL $primaryLocationOnly
433 public function __construct(
434 $params = NULL, $returnProperties = NULL, $fields = NULL,
435 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
436 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
437 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
440 $primaryLocationOnly = NULL
442 if ($primaryLocationOnly === NULL) {
443 $primaryLocationOnly = Civi
::settings()->get('searchPrimaryDetailsOnly');
445 $this->_primaryLocation
= $primaryLocationOnly;
446 $this->_params
= &$params;
447 if ($this->_params
== NULL) {
448 $this->_params
= array();
451 if ($returnProperties === self
::NO_RETURN_PROPERTIES
) {
452 $this->_returnProperties
= array();
454 elseif (empty($returnProperties)) {
455 $this->_returnProperties
= self
::defaultReturnProperties($mode);
458 $this->_returnProperties
= &$returnProperties;
461 $this->_includeContactIds
= $includeContactIds;
462 $this->_strict
= $strict;
463 $this->_mode
= $mode;
464 $this->_skipPermission
= $skipPermission;
465 $this->_smartGroupCache
= $smartGroupCache;
466 $this->_displayRelationshipType
= $displayRelationshipType;
467 $this->setOperator($operator);
470 $this->_fields
= &$fields;
471 $this->_search
= FALSE;
472 $this->_skipPermission
= TRUE;
475 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE, FALSE, !$skipPermission);
477 $fields = CRM_Core_Component
::getQueryFields(!$this->_skipPermission
);
478 unset($fields['note']);
479 $this->_fields
= array_merge($this->_fields
, $fields);
481 // add activity fields
482 $fields = CRM_Activity_BAO_Activity
::exportableFields();
483 $this->_fields
= array_merge($this->_fields
, $fields);
485 // add any fields provided by hook implementers
486 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
487 $this->_fields
= array_merge($this->_fields
, $extFields);
490 // basically do all the work once, and then reuse it
491 $this->initialize($apiEntity);
495 * Function which actually does all the work for the constructor.
497 * @param string $apiEntity
498 * The api entity being called.
499 * This sort-of duplicates $mode in a confusing way. Probably not by design.
501 public function initialize($apiEntity = NULL) {
502 $this->_select
= array();
503 $this->_element
= array();
504 $this->_tables
= array();
505 $this->_whereTables
= array();
506 $this->_where
= array();
507 $this->_qill
= array();
508 $this->_options
= array();
509 $this->_cfIDs
= array();
510 $this->_paramLookup
= array();
511 $this->_having
= array();
513 $this->_customQuery
= NULL;
515 // reset cached static variables - CRM-5803
516 self
::$_activityRole = NULL;
517 self
::$_considerCompActivities = NULL;
518 self
::$_withContactActivitiesOnly = NULL;
520 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
521 $this->_element
['contact_id'] = 1;
522 $this->_tables
['civicrm_contact'] = 1;
524 if (!empty($this->_params
)) {
525 $this->buildParamsLookup();
528 $this->_whereTables
= $this->_tables
;
530 $this->selectClause($apiEntity);
531 $this->_whereClause
= $this->whereClause($apiEntity);
532 if (array_key_exists('civicrm_contribution', $this->_whereTables
)) {
533 $component = 'contribution';
535 if (array_key_exists('civicrm_membership', $this->_whereTables
)) {
536 $component = 'membership';
538 if (isset($component)) {
539 CRM_Financial_BAO_FinancialType
::buildPermissionedClause($this->_whereClause
, $component);
542 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
, $apiEntity);
543 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
545 $this->openedSearchPanes(TRUE);
549 * Function for same purpose as convertFormValues.
551 * Like convert form values this function exists to pre-Process parameters from the form.
553 * It is unclear why they are different functions & likely relates to advances search
554 * versus search builder.
556 * The direction we are going is having the form convert values to a standardised format &
557 * moving away from weird & wonderful where clause switches.
559 * Fix and handle contact deletion nicely.
561 * this code is primarily for search builder use case where different clauses can specify if they want deleted.
565 public function buildParamsLookup() {
566 $trashParamExists = FALSE;
567 $paramByGroup = array();
568 foreach ($this->_params
as $k => $param) {
569 if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
570 $trashParamExists = TRUE;
572 if (!empty($param[3])) {
573 $paramByGroup[$param[3]][$k] = $param;
577 if ($trashParamExists) {
578 $this->_skipDeleteClause
= TRUE;
580 //cycle through group sets and explicitly add trash param if not set
581 foreach ($paramByGroup as $setID => $set) {
583 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params
) &&
584 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params
)
586 $this->_params
[] = array(
587 'contact_is_deleted',
597 foreach ($this->_params
as $value) {
598 if (empty($value[0])) {
601 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
603 if (!array_key_exists($cfID, $this->_cfIDs
)) {
604 $this->_cfIDs
[$cfID] = array();
606 // Set wildcard value based on "and/or" selection
607 foreach ($this->_params
as $key => $param) {
608 if ($param[0] == $value[0] . '_operator') {
609 $value[4] = $param[2] == 'or';
613 $this->_cfIDs
[$cfID][] = $value;
616 if (!array_key_exists($value[0], $this->_paramLookup
)) {
617 $this->_paramLookup
[$value[0]] = array();
619 if ($value[0] !== 'group') {
620 // Just trying to unravel how group interacts here! This whole function is weird.
621 $this->_paramLookup
[$value[0]][] = $value;
627 * Some composite fields do not appear in the fields array hack to make them part of the query.
630 * The api entity being called.
631 * This sort-of duplicates $mode in a confusing way. Probably not by design.
633 public function addSpecialFields($apiEntity) {
634 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
635 // if get called via Contact.get API having address_id as return parameter
636 if ($apiEntity == 'Contact') {
637 $special[] = 'address_id';
639 foreach ($special as $name) {
640 if (!empty($this->_returnProperties
[$name])) {
641 if ($name == 'address_id') {
642 $this->_tables
['civicrm_address'] = 1;
643 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
644 $this->_element
['address_id'] = 1;
647 $this->_select
[$name] = "contact_a.{$name} as $name";
648 $this->_element
[$name] = 1;
655 * Given a list of conditions in params and a list of desired
656 * return Properties generate the required select and from
657 * clauses. Note that since the where clause introduces new
658 * tables, the initial attempt also retrieves all variables used
661 * @param string $apiEntity
662 * The api entity being called.
663 * This sort-of duplicates $mode in a confusing way. Probably not by design.
665 public function selectClause($apiEntity = NULL) {
667 // @todo Tidy up this. This arises because 1) we are ignoring the $mode & adding a new
668 // param ($apiEntity) instead - presumably an oversight & 2 because
669 // contact is not implemented as a component.
670 $this->addSpecialFields($apiEntity);
672 foreach ($this->_fields
as $name => $field) {
673 // skip component fields
674 // there are done by the alter query below
675 // and need not be done on every field
676 // @todo remove these & handle using metadata - only obscure fields
677 // that are hack-added should need to be excluded from the main loop.
679 (substr($name, 0, 12) == 'participant_') ||
680 (substr($name, 0, 7) == 'pledge_') ||
681 (substr($name, 0, 5) == 'case_')
686 // redirect to activity select clause
688 (substr($name, 0, 9) == 'activity_') ||
689 ($name == 'parent_id')
691 CRM_Activity_BAO_Query
::select($this);
694 // if this is a hierarchical name, we ignore it
695 $names = explode('-', $name);
696 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
700 // make an exception for special cases, to add the field in select clause
701 $makeException = FALSE;
703 //special handling for groups/tags
704 if (in_array($name, array('groups', 'tags', 'notes'))
705 && isset($this->_returnProperties
[substr($name, 0, -1)])
707 // @todo instead of setting make exception to get us into
708 // an if clause that has handling for these fields buried with in it
709 // move the handling to here.
710 $makeException = TRUE;
713 // since note has 3 different options we need special handling
714 // note / note_subject / note_body
715 if ($name == 'notes') {
716 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
717 if (isset($this->_returnProperties
[$noteField])) {
718 $makeException = TRUE;
724 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
726 !empty($this->_paramLookup
[$name])
727 ||
!empty($this->_returnProperties
[$name])
728 ||
$this->pseudoConstantNameIsInReturnProperties($field)
732 // add to cfIDs array if not present
733 if (!array_key_exists($cfID, $this->_cfIDs
)) {
734 $this->_cfIDs
[$cfID] = array();
737 elseif (isset($field['where'])) {
738 list($tableName, $fieldName) = explode('.', $field['where'], 2);
739 if (isset($tableName)) {
740 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
741 $this->_tables
['civicrm_address'] = 1;
742 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
743 $this->_element
['address_id'] = 1;
746 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
747 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
749 if ($tableName == 'im_provider') {
750 CRM_Core_OptionValue
::select($this);
753 if (in_array($tableName,
754 array('email_greeting', 'postal_greeting', 'addressee'))) {
755 $this->_element
["{$name}_id"] = 1;
756 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
757 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
758 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
759 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
761 if ($tableName == 'email_greeting') {
763 $this->_pseudoConstantsSelect
[$name]['join']
764 = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
765 $this->_pseudoConstantsSelect
[$name]['join'] .=
766 " 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 ) ";
768 elseif ($tableName == 'postal_greeting') {
770 $this->_pseudoConstantsSelect
[$name]['join']
771 = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
772 $this->_pseudoConstantsSelect
[$name]['join'] .=
773 " 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 ) ";
775 elseif ($tableName == 'addressee') {
777 $this->_pseudoConstantsSelect
[$name]['join']
778 = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
779 $this->_pseudoConstantsSelect
[$name]['join'] .=
780 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
782 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
785 $greetField = "{$name}_display";
786 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
787 $this->_element
[$greetField] = 1;
789 $greetField = "{$name}_custom";
790 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
791 $this->_element
[$greetField] = 1;
795 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
796 $this->_tables
[$tableName] = 1;
799 // also get the id of the tableName
800 $tName = substr($tableName, 8);
801 if (in_array($tName, array('country', 'state_province', 'county'))) {
802 if ($tName == 'state_province') {
803 $this->_pseudoConstantsSelect
['state_province_name'] = array(
804 'pseudoField' => "{$tName}",
805 'idCol' => "{$tName}_id",
806 'bao' => 'CRM_Core_BAO_Address',
807 'table' => "civicrm_{$tName}",
808 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
811 $this->_pseudoConstantsSelect
[$tName] = array(
812 'pseudoField' => 'state_province_abbreviation',
813 'idCol' => "{$tName}_id",
814 'table' => "civicrm_{$tName}",
815 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
819 $this->_pseudoConstantsSelect
[$name] = array(
820 'pseudoField' => "{$tName}_id",
821 'idCol' => "{$tName}_id",
822 'bao' => 'CRM_Core_BAO_Address',
823 'table' => "civicrm_{$tName}",
824 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
828 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
829 $this->_element
["{$tName}_id"] = 1;
831 elseif ($tName != 'contact') {
832 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
833 $this->_element
["{$tName}_id"] = 1;
836 //special case for phone
837 if ($name == 'phone') {
838 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
839 $this->_element
['phone_type_id'] = 1;
842 // if IM then select provider_id also
843 // to get "IM Service Provider" in a file to be exported, CRM-3140
845 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
846 $this->_element
['provider_id'] = 1;
849 if ($tName == 'contact' && $fieldName == 'organization_name') {
850 // special case, when current employer is set for Individual contact
851 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
853 elseif ($tName == 'contact' && $fieldName === 'id') {
854 // Handled elsewhere, explicitly ignore. Possibly for all tables...
856 elseif (in_array($tName, array('country', 'county'))) {
857 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
858 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
860 elseif ($tName == 'state_province') {
861 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
862 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
864 elseif (strpos($name, 'contribution_soft_credit') !== FALSE) {
865 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled($this->_params
)) {
866 $this->_select
[$name] = "{$field['where']} as `$name`";
870 // If we have an option group defined then rather than joining the option value table in
871 // (which is an unindexed join) we render the option value on output.
872 // @todo - extend this to other pseudoconstants.
873 if ($this->pseudoConstantNameIsInReturnProperties($field, $name)) {
874 $pseudoFieldName = $field['pseudoconstant']['optionGroupName'];
875 $this->_pseudoConstantsSelect
[$pseudoFieldName] = array(
876 'pseudoField' => $field['name'],
878 'field_name' => $field['name'],
879 'bao' => $field['bao'],
880 'pseudoconstant' => $field['pseudoconstant'],
882 $this->_tables
[$tableName] = 1;
883 $this->_element
[$pseudoFieldName] = 1;
885 $this->_select
[$name] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$name`");
887 if (!in_array($tName, array('state_province', 'country', 'county'))) {
888 $this->_element
[$name] = 1;
893 elseif ($name === 'tags') {
894 //@todo move this handling outside the big IF & ditch $makeException
895 $this->_useGroupBy
= TRUE;
896 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
897 $this->_element
[$name] = 1;
898 $this->_tables
['civicrm_tag'] = 1;
899 $this->_tables
['civicrm_entity_tag'] = 1;
901 elseif ($name === 'groups') {
902 //@todo move this handling outside the big IF & ditch $makeException
903 $this->_useGroupBy
= TRUE;
904 // Duplicates will be created here but better to sort them out in php land.
905 $this->_select
[$name] = "
907 GROUP_CONCAT(DISTINCT IF(civicrm_group_contact.status = 'Added', civicrm_group_contact.group_id, '')),
908 GROUP_CONCAT(DISTINCT civicrm_group_contact_cache.group_id)
911 $this->_element
[$name] = 1;
912 $this->_tables
['civicrm_group_contact'] = 1;
913 $this->_tables
['civicrm_group_contact_cache'] = 1;
914 $this->_pseudoConstantsSelect
["{$name}"] = array(
915 'pseudoField' => "groups",
919 elseif ($name === 'notes') {
920 //@todo move this handling outside the big IF & ditch $makeException
921 // if note field is subject then return subject else body of the note
922 $noteColumn = 'note';
923 if (isset($noteField) && $noteField == 'note_subject') {
924 $noteColumn = 'subject';
927 $this->_useGroupBy
= TRUE;
928 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
929 $this->_element
[$name] = 1;
930 $this->_tables
['civicrm_note'] = 1;
932 elseif ($name === 'current_employer') {
933 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
934 $this->_element
[$name] = 1;
938 if ($cfID && !empty($field['is_search_range'])) {
939 // this is a custom field with range search enabled, so we better check for two/from values
940 if (!empty($this->_paramLookup
[$name . '_from'])) {
941 if (!array_key_exists($cfID, $this->_cfIDs
)) {
942 $this->_cfIDs
[$cfID] = array();
944 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
945 // search in the cdID array for the same grouping
947 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
948 if ($c[3] == $p[3]) {
949 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
954 $p[2] = array('from' => $p[2]);
955 $this->_cfIDs
[$cfID][] = $p;
959 if (!empty($this->_paramLookup
[$name . '_to'])) {
960 if (!array_key_exists($cfID, $this->_cfIDs
)) {
961 $this->_cfIDs
[$cfID] = array();
963 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
964 // search in the cdID array for the same grouping
966 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
967 if ($c[4] == $p[4]) {
968 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
973 $p[2] = array('to' => $p[2]);
974 $this->_cfIDs
[$cfID][] = $p;
981 // add location as hierarchical elements
982 $this->addHierarchicalElements();
984 // add multiple field like website
985 $this->addMultipleElements();
988 CRM_Core_Component
::alterQuery($this, 'select');
990 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
992 if (!empty($this->_cfIDs
)) {
993 // @todo This function is the select function but instead of running 'select' it
994 // is running the whole query.
995 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
996 $this->_customQuery
->query();
997 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
998 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
999 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
1000 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
1001 $this->_options
= $this->_customQuery
->_options
;
1006 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1008 public function addHierarchicalElements() {
1009 if (empty($this->_returnProperties
['location'])) {
1012 if (!is_array($this->_returnProperties
['location'])) {
1016 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1017 $processed = array();
1020 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
1021 $addressCustomFieldIds = array();
1023 foreach ($this->_returnProperties
['location'] as $name => $elements) {
1024 $lCond = self
::getPrimaryCondition($name);
1027 $locationTypeId = array_search($name, $locationTypes);
1028 if ($locationTypeId === FALSE) {
1031 $lCond = "location_type_id = $locationTypeId";
1032 $this->_useDistinct
= TRUE;
1034 //commented for CRM-3256
1035 $this->_useGroupBy
= TRUE;
1038 $name = str_replace(' ', '_', $name);
1040 $tName = "$name-location_type";
1041 $ltName = "`$name-location_type`";
1042 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1043 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
1044 $this->_element
["{$tName}_id"] = 1;
1045 $this->_element
["{$tName}"] = 1;
1047 $locationTypeName = $tName;
1048 $locationTypeJoin = array();
1050 $addAddress = FALSE;
1052 foreach ($elements as $elementFullName => $dontCare) {
1054 $elementName = $elementCmpName = $elementFullName;
1056 if (substr($elementCmpName, 0, 5) == 'phone') {
1057 $elementCmpName = 'phone';
1060 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
1061 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
1062 $addressCustomFieldIds[$cfID][$name] = 1;
1065 //add address table only once
1066 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
1068 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
1070 $tName = "$name-address";
1071 $aName = "`$name-address`";
1072 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1073 $this->_element
["{$tName}_id"] = 1;
1074 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
1075 $this->_tables
[$tName] = $addressJoin;
1076 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1077 $processed[$aName] = 1;
1081 $cond = $elementType = '';
1082 if (strpos($elementName, '-') !== FALSE) {
1083 // this is either phone, email or IM
1084 list($elementName, $elementType) = explode('-', $elementName);
1086 if (($elementName != 'phone') && ($elementName != 'im')) {
1087 $cond = self
::getPrimaryCondition($elementType);
1089 // CRM-13011 : If location type is primary, do not restrict search to the phone
1090 // type id - we want the primary phone, regardless of what type it is.
1091 // Otherwise, restrict to the specified phone type for the given field.
1092 if ((!$cond) && ($elementName == 'phone')) {
1093 $cond = "phone_type_id = '$elementType'";
1095 elseif ((!$cond) && ($elementName == 'im')) {
1096 // IM service provider id, CRM-3140
1097 $cond = "provider_id = '$elementType'";
1099 $elementType = '-' . $elementType;
1102 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
1104 // hack for profile, add location id
1107 // fix for CRM-882( to handle phone types )
1108 !is_numeric($elementType)
1110 if (is_numeric($name)) {
1111 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1114 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1117 elseif (is_numeric($name)) {
1118 //this for phone type to work
1119 if (in_array($elementName, array('phone', 'phone_ext'))) {
1120 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1123 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1127 //this is for phone type to work for profile edit
1128 if (in_array($elementName, array('phone', 'phone_ext'))) {
1129 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1132 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1137 // Check if there is a value, if so also add to where Clause
1139 if ($this->_params
) {
1141 if (isset($locationTypeId)) {
1142 $nm .= "-$locationTypeId";
1144 if (!is_numeric($elementType)) {
1145 $nm .= "$elementType";
1148 foreach ($this->_params
as $id => $values) {
1149 if ((is_array($values) && $values[0] == $nm) ||
1150 (in_array($elementName, array('phone', 'im'))
1151 && (strpos($values[0], $nm) !== FALSE)
1161 if ($field && isset($field['where'])) {
1162 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1163 $pf = substr($tableName, 8);
1164 $tName = $name . '-' . $pf . $elementType;
1165 if (isset($tableName)) {
1166 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1167 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1170 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1173 $this->_element
["{$tName}_id"] = 1;
1174 if (substr($tName, -15) == '-state_province') {
1175 // FIXME: hack to fix CRM-1900
1176 $a = Civi
::settings()->get('address_format');
1178 if (substr_count($a, 'state_province_name') > 0) {
1179 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1180 'pseudoField' => "{$pf}_id",
1181 'idCol' => "{$tName}_id",
1182 'bao' => 'CRM_Core_BAO_Address',
1184 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1187 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1188 'pseudoField' => 'state_province_abbreviation',
1189 'idCol' => "{$tName}_id",
1191 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1195 if (substr($elementFullName, 0, 2) == 'im') {
1196 $provider = "{$name}-{$elementFullName}-provider_id";
1197 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1198 $this->_element
[$provider] = 1;
1200 if ($pf == 'country' ||
$pf == 'county') {
1201 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1202 'pseudoField' => "{$pf}_id",
1203 'idCol' => "{$tName}_id",
1204 'bao' => 'CRM_Core_BAO_Address',
1206 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1209 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1213 if (in_array($pf, array('state_province', 'country', 'county'))) {
1214 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1217 $this->_element
["{$name}-{$elementFullName}"] = 1;
1220 if (empty($processed["`$tName`"])) {
1221 $processed["`$tName`"] = 1;
1222 $newName = $tableName . '_' . $index;
1223 switch ($tableName) {
1224 case 'civicrm_phone':
1225 case 'civicrm_email':
1227 case 'civicrm_openid':
1229 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1230 if ($tableName != 'civicrm_phone') {
1231 $this->_tables
[$tName] .= " AND `$tName`.$lCond";
1233 elseif (is_numeric($name)) {
1234 $this->_select
[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1237 // this special case to add phone type
1239 $phoneTypeCondition = " AND `$tName`.$cond ";
1240 //gross hack to pickup corrupted data also, CRM-7603
1241 if (strpos($cond, 'phone_type_id') !== FALSE) {
1242 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1243 if (!empty($lCond)) {
1244 $phoneTypeCondition .= " AND ( `$tName`.$lCond ) ";
1247 $this->_tables
[$tName] .= $phoneTypeCondition;
1250 //build locationType join
1251 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1254 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1258 case 'civicrm_state_province':
1259 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1260 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1261 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1263 $this->_whereTables
["{$name}-address"] = $addressJoin;
1267 case 'civicrm_country':
1268 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1269 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1270 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1272 $this->_whereTables
["{$name}-address"] = $addressJoin;
1276 case 'civicrm_county':
1277 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1278 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1279 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1281 $this->_whereTables
["{$name}-address"] = $addressJoin;
1287 $this->_whereTables
["{$name}-address"] = $addressJoin;
1296 // add location type join
1297 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1298 $this->_tables
[$locationTypeName] = $ltypeJoin;
1300 // table should be present in $this->_whereTables,
1301 // to add its condition in location type join, CRM-3939.
1302 if ($addWhereCount) {
1303 $locClause = array();
1304 foreach ($this->_whereTables
as $tableName => $clause) {
1305 if (!empty($locationTypeJoin[$tableName])) {
1306 $locClause[] = $locationTypeJoin[$tableName];
1310 if (!empty($locClause)) {
1311 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1316 if (!empty($addressCustomFieldIds)) {
1317 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1318 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1319 foreach ($locTypeName as $name => $dnc) {
1320 $this->_locationSpecificCustomFields
[$cfID] = array($name, array_search($name, $locationTypes));
1321 $fieldName = "$name-custom_{$cfID}";
1322 $tName = "$name-address-custom-{$cfID}";
1323 $aName = "`$name-address-custom-{$cfID}`";
1324 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1325 $this->_element
["{$tName}_id"] = 1;
1326 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1327 $this->_element
[$fieldName] = 1;
1328 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1335 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1337 public function addMultipleElements() {
1338 if (empty($this->_returnProperties
['website'])) {
1341 if (!is_array($this->_returnProperties
['website'])) {
1345 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1346 foreach ($elements as $elementFullName => $dontCare) {
1347 $tName = "website-{$key}-{$elementFullName}";
1348 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1349 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1350 $this->_element
["{$tName}_id"] = 1;
1351 $this->_element
["{$tName}"] = 1;
1353 $type = "website-{$key}-website_type_id";
1354 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1355 $this->_element
[$type] = 1;
1356 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1362 * Generate the query based on what type of query we need.
1364 * @param bool $count
1365 * @param bool $sortByChar
1366 * @param bool $groupContacts
1367 * @param bool $onlyDeleted
1370 * sql query parts as an array
1372 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1373 // build permission clause
1374 $this->generatePermissionClause($onlyDeleted, $count);
1377 if (isset($this->_rowCountClause
)) {
1378 $select = "SELECT {$this->_rowCountClause}";
1380 elseif (isset($this->_distinctComponentClause
)) {
1381 // we add distinct to get the right count for components
1382 // for the more complex result set, we use GROUP BY the same id
1384 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} ) as rowCount";
1387 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1389 $from = $this->_simpleFromClause
;
1390 if ($this->_useDistinct
) {
1391 $this->_useGroupBy
= TRUE;
1394 elseif ($sortByChar) {
1395 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1396 $from = $this->_simpleFromClause
;
1398 elseif ($groupContacts) {
1399 $select = 'SELECT contact_a.id as id';
1400 if ($this->_useDistinct
) {
1401 $this->_useGroupBy
= TRUE;
1403 $from = $this->_simpleFromClause
;
1406 if (!empty($this->_paramLookup
['group'])) {
1408 list($name, $op, $value, $grouping, $wildcard) = $this->_paramLookup
['group'][0];
1410 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
1411 $this->_paramLookup
['group'][0][1] = key($value);
1414 // Presumably the lines below come into manage groups screen.
1415 // make sure there is only one element
1416 // this is used when we are running under smog and need to know
1417 // how the contact was added (CRM-1203)
1418 $groups = (array) CRM_Utils_Array
::value($this->_paramLookup
['group'][0][1], $this->_paramLookup
['group'][0][2], $this->_paramLookup
['group'][0][2]);
1419 if ((count($this->_paramLookup
['group']) == 1) &&
1420 (count($groups) == 1)
1422 $groupId = $groups[0];
1424 //check if group is saved search
1425 $group = new CRM_Contact_BAO_Group();
1426 $group->id
= $groupId;
1429 if (!isset($group->saved_search_id
)) {
1430 $tbName = "`civicrm_group_contact-{$groupId}`";
1431 // CRM-17254 don't retrieve extra fields if contact_id is specifically requested
1432 // as this will add load to an intentionally light query.
1433 // ideally this code would be removed as it appears to be to support CRM-1203
1434 // and passing in the required returnProperties from the url would
1435 // make more sense that globally applying the requirements of one form.
1436 if (($this->_returnProperties
!= array('contact_id'))) {
1437 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1438 $this->_element
['group_contact_id'] = 1;
1439 $this->_select
['status'] = "$tbName.status as status";
1440 $this->_element
['status'] = 1;
1444 $this->_useGroupBy
= TRUE;
1446 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1447 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1449 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1450 $this->_useDistinct
= FALSE;
1451 $this->_useGroupBy
= TRUE;
1455 $select = $this->getSelect();
1456 $from = $this->_fromClause
;
1460 if (!empty($this->_whereClause
)) {
1461 $where = "WHERE {$this->_whereClause}";
1464 if (!empty($this->_permissionWhereClause
) && empty($this->_displayRelationshipType
)) {
1465 if (empty($where)) {
1466 $where = "WHERE $this->_permissionWhereClause";
1469 $where = "$where AND $this->_permissionWhereClause";
1474 if (!empty($this->_having
)) {
1475 foreach ($this->_having
as $havingSets) {
1476 foreach ($havingSets as $havingSet) {
1477 $havingValue[] = $havingSet;
1480 $having = ' HAVING ' . implode(' AND ', $havingValue);
1483 // if we are doing a transform, do it here
1484 // use the $from, $where and $having to get the contact ID
1485 if ($this->_displayRelationshipType
) {
1486 $this->filterRelatedContacts($from, $where, $having);
1489 return array($select, $from, $where, $having);
1493 * Get where values from the parameters.
1495 * @param string $name
1496 * @param mixed $grouping
1500 public function getWhereValues($name, $grouping) {
1502 foreach ($this->_params
as $values) {
1503 if ($values[0] == $name && $values[3] == $grouping) {
1514 * @param bool $relative
1515 * @param string $from
1518 public static function fixDateValues($relative, &$from, &$to) {
1520 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1525 * Convert values from form-appropriate to query-object appropriate.
1527 * The query object is increasingly supporting the sql-filter syntax which is the most flexible syntax.
1528 * So, ideally we would convert all fields to look like
1531 * // Set the operator for legacy reasons, but it is ignored
1533 * // array in sql filter syntax
1534 * 2 => array('BETWEEN' => array(1,60),
1539 * There are some examples of the syntax in
1540 * https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples/Relationship
1542 * More notes at CRM_Core_DAO::createSQLFilter
1544 * and a list of supported operators in CRM_Core_DAO
1546 * @param array $formValues
1547 * @param int $wildcard
1548 * @param bool $useEquals
1550 * @param string $apiEntity
1552 * @param array $entityReferenceFields
1553 * Field names of any entity reference fields (which will need reformatting to IN syntax).
1557 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL,
1558 $entityReferenceFields = array()) {
1560 if (empty($formValues)) {
1564 self
::filterCountryFromValuesIfStateExists($formValues);
1566 foreach ($formValues as $id => &$val) {
1567 // CRM-19374 - we don't want to change $val in $formValues.
1568 // Assign it to a temp variable which operates while iteration.
1571 if (self
::isAlreadyProcessedForQueryFormat($values)) {
1572 $params[] = $values;
1576 self
::legacyConvertFormValues($id, $values);
1578 // The form uses 1 field to represent two db fields
1579 if ($id == 'contact_type' && $values && (!is_array($values) ||
!array_intersect(array_keys($values), CRM_Core_DAO
::acceptedSQLOperators()))) {
1580 $contactType = array();
1582 foreach ((array) $values as $key => $type) {
1583 $types = explode('__', is_numeric($type) ?
$key : $type);
1584 $contactType[$types[0]] = $types[0];
1585 // Add sub-type if specified
1586 if (!empty($types[1])) {
1587 $subType[$types[1]] = $types[1];
1590 $params[] = array('contact_type', 'IN', $contactType, 0, 0);
1592 $params[] = array('contact_sub_type', 'IN', $subType, 0, 0);
1595 elseif ($id == 'privacy') {
1596 if (is_array($formValues['privacy'])) {
1597 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1598 foreach ($formValues['privacy'] as $key => $value) {
1600 $params[] = array($key, $op, $value, 0, 0);
1605 elseif ($id == 'email_on_hold') {
1606 if ($formValues['email_on_hold']['on_hold']) {
1607 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1610 elseif (substr($id, 0, 7) == 'custom_'
1612 substr($id, -9, 9) == '_relative'
1613 ||
substr($id, -5, 5) == '_from'
1614 ||
substr($id, -3, 3) == '_to'
1617 self
::convertCustomRelativeFields($formValues, $params, $values, $id);
1619 elseif (preg_match('/_date_relative$/', $id) ||
1620 $id == 'event_relative' ||
1621 $id == 'case_from_relative' ||
1622 $id == 'case_to_relative' ||
1623 $id == 'participant_relative'
1625 if ($id == 'event_relative') {
1626 $fromRange = 'event_start_date_low';
1627 $toRange = 'event_end_date_high';
1629 elseif ($id == 'participant_relative') {
1630 $fromRange = 'participant_register_date_low';
1631 $toRange = 'participant_register_date_high';
1633 elseif ($id == 'case_from_relative') {
1634 $fromRange = 'case_from_start_date_low';
1635 $toRange = 'case_from_start_date_high';
1637 elseif ($id == 'case_to_relative') {
1638 $fromRange = 'case_to_end_date_low';
1639 $toRange = 'case_to_end_date_high';
1642 $dateComponent = explode('_date_relative', $id);
1643 $fromRange = "{$dateComponent[0]}_date_low";
1644 $toRange = "{$dateComponent[0]}_date_high";
1647 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1648 // relative dates are not processed correctly as lower date value were ignored,
1649 // to ensure both high and low date value got added IF there is relative date,
1650 // we need to reset $formValues by unset and then adding again via CRM_Contact_BAO_Query::fixDateValues(...)
1651 if (!empty($formValues[$id])) {
1652 unset($formValues[$fromRange]);
1653 unset($formValues[$toRange]);
1655 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1659 elseif (in_array($id, $entityReferenceFields) && !empty($values) && is_string($values) && (strpos($values, ',') !=
1661 $params[] = array($id, 'IN', explode(',', $values), 0, 0);
1664 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
1669 $params[] = $values;
1676 * Function to support legacy format for groups and tags.
1679 * @param array|int $values
1682 public static function legacyConvertFormValues($id, &$values) {
1683 $legacyElements = array(
1688 'membership_type_id',
1689 'membership_status_id',
1691 if (in_array($id, $legacyElements) && is_array($values)) {
1692 // prior to 4.7, formValues for some attributes (e.g. group, tag) are stored in array(id1 => 1, id2 => 1),
1693 // as per the recent Search fixes $values need to be in standard array(id1, id2) format
1694 $values = CRM_Utils_Array
::convertCheckboxFormatToArray($values);
1699 * Fix values from query from/to something no-one cared enough to document.
1702 * @param array $values
1703 * @param int $wildcard
1704 * @param bool $useEquals
1706 * @param string $apiEntity
1708 * @return array|null
1710 public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1711 // skip a few search variables
1712 static $skipWhere = NULL;
1713 static $likeNames = NULL;
1716 // Change camelCase EntityName to lowercase with underscores
1717 $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity);
1719 // check if $value is in OK (Operator as Key) format as used by Get API
1720 if (CRM_Utils_System
::isNull($values)) {
1732 'display_relationship_type',
1736 if (in_array($id, $skipWhere) ||
1737 substr($id, 0, 4) == '_qf_' ||
1738 substr($id, 0, 7) == 'hidden_'
1744 (substr($id, 0, strlen($apiEntity)) != $apiEntity) &&
1745 (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_') &&
1746 (substr($id, 0, 7) != 'custom_')
1748 $id = $apiEntity . '_' . $id;
1752 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1755 // email comes in via advanced search
1756 // so use wildcard always
1757 if ($id == 'email') {
1761 if (!$useEquals && in_array($id, $likeNames)) {
1762 $result = array($id, 'LIKE', $values, 0, 1);
1764 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1765 $result = array($id, 'LIKE', $values, 0, 0);
1767 elseif ($id == 'contact_type' ||
1768 (!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO
::acceptedSQLOperators(), TRUE))
1770 $result = array($id, 'IN', $values, 0, $wildcard);
1773 $result = array($id, '=', $values, 0, $wildcard);
1780 * Get the where clause for a single field.
1782 * @param array $values
1783 * @param string $apiEntity
1785 public function whereClauseSingle(&$values, $apiEntity = NULL) {
1786 // do not process custom fields or prefixed contact ids or component params
1787 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1788 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1789 (substr($values[0], 0, 13) == 'contribution_') ||
1790 (substr($values[0], 0, 6) == 'event_') ||
1791 (substr($values[0], 0, 12) == 'participant_') ||
1792 (substr($values[0], 0, 7) == 'member_') ||
1793 (substr($values[0], 0, 6) == 'grant_') ||
1794 (substr($values[0], 0, 7) == 'pledge_') ||
1795 (substr($values[0], 0, 5) == 'case_') ||
1796 (substr($values[0], 0, 10) == 'financial_') ||
1797 (substr($values[0], 0, 8) == 'payment_') ||
1798 (substr($values[0], 0, 11) == 'membership_')
1803 // skip for hook injected fields / params
1804 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1805 if (array_key_exists($values[0], $extFields)) {
1809 switch ($values[0]) {
1810 case 'deleted_contacts':
1811 $this->deletedContacts($values);
1814 case 'contact_sub_type':
1815 $this->contactSubType($values);
1820 $this->group($values);
1823 // case tag comes from find contacts
1825 $this->tagSearch($values);
1829 case 'contact_tags':
1830 $this->tag($values);
1835 case 'note_subject':
1836 $this->notes($values);
1840 $this->ufUser($values);
1844 case 'display_name':
1845 $this->sortName($values);
1849 case 'postal_greeting':
1850 case 'email_greeting':
1851 $this->greetings($values);
1856 $this->email($values, $apiEntity);
1859 case 'phone_numeric':
1860 $this->phone_numeric($values);
1863 case 'phone_phone_type_id':
1864 case 'phone_location_type_id':
1865 $this->phone_option_group($values);
1868 case 'street_address':
1869 $this->street_address($values);
1872 case 'street_number':
1873 $this->street_number($values);
1876 case 'sortByCharacter':
1877 $this->sortByCharacter($values);
1880 case 'location_type':
1881 $this->locationType($values);
1885 $this->county($values);
1888 case 'state_province':
1889 case 'state_province_id':
1890 case 'state_province_name':
1891 $this->stateProvince($values);
1896 $this->country($values, FALSE);
1900 case 'postal_code_low':
1901 case 'postal_code_high':
1902 $this->postalCode($values);
1905 case 'activity_date':
1906 case 'activity_date_low':
1907 case 'activity_date_high':
1908 case 'activity_role':
1909 case 'activity_status_id':
1910 case 'activity_status':
1911 case 'activity_priority':
1912 case 'activity_priority_id':
1913 case 'followup_parent_id':
1915 case 'source_contact_id':
1916 case 'activity_text':
1917 case 'activity_option':
1918 case 'test_activities':
1919 case 'activity_type_id':
1920 case 'activity_type':
1921 case 'activity_survey_id':
1922 case 'activity_tags':
1923 case 'activity_taglist':
1924 case 'activity_test':
1925 case 'activity_campaign_id':
1926 case 'activity_engagement_level':
1928 case 'activity_result':
1929 case 'source_contact':
1930 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1935 case 'birth_date_low':
1936 case 'birth_date_high':
1937 case 'deceased_date_low':
1938 case 'deceased_date_high':
1939 $this->demographics($values);
1942 case 'age_asof_date':
1943 // handled by demographics
1946 case 'log_date_low':
1947 case 'log_date_high':
1948 $this->modifiedDates($values);
1952 $this->changeLog($values);
1955 case 'do_not_phone':
1956 case 'do_not_email':
1959 case 'do_not_trade':
1961 $this->privacy($values);
1964 case 'privacy_options':
1965 $this->privacyOptions($values);
1968 case 'privacy_operator':
1969 case 'privacy_toggle':
1970 // these are handled by privacy options
1973 case 'preferred_communication_method':
1974 $this->preferredCommunication($values);
1977 case 'relation_type_id':
1978 case 'relation_start_date_high':
1979 case 'relation_start_date_low':
1980 case 'relation_end_date_high':
1981 case 'relation_end_date_low':
1982 case 'relation_active_period_date_high':
1983 case 'relation_active_period_date_low':
1984 case 'relation_target_name':
1985 case 'relation_status':
1986 case 'relation_date_low':
1987 case 'relation_date_high':
1988 $this->relationship($values);
1989 $this->_relationshipValuesAdded
= TRUE;
1992 case 'task_status_id':
1993 $this->task($values);
1997 // since this case is handled with the above
2000 case 'prox_distance':
2001 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
2004 case 'prox_street_address':
2006 case 'prox_postal_code':
2007 case 'prox_state_province_id':
2008 case 'prox_country_id':
2009 case 'prox_geo_code_1':
2010 case 'prox_geo_code_2':
2011 // handled by the proximity_distance clause
2015 $this->restWhere($values);
2021 * Given a list of conditions in params generate the required where clause.
2023 * @param string $apiEntity
2027 public function whereClause($apiEntity = NULL) {
2028 $this->_where
[0] = array();
2029 $this->_qill
[0] = array();
2031 $this->includeContactIds();
2032 if (!empty($this->_params
)) {
2033 foreach (array_keys($this->_params
) as $id) {
2034 if (empty($this->_params
[$id][0])) {
2037 // check for both id and contact_id
2038 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
2039 $this->_where
[0][] = self
::buildClause("contact_a.id", $this->_params
[$id][1], $this->_params
[$id][2]);
2042 $this->whereClauseSingle($this->_params
[$id], $apiEntity);
2046 CRM_Core_Component
::alterQuery($this, 'where');
2048 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
2051 if ($this->_customQuery
) {
2052 // Added following if condition to avoid the wrong value display for 'my account' / any UF info.
2053 // Hope it wont affect the other part of civicrm.. if it does please remove it.
2054 if (!empty($this->_customQuery
->_where
)) {
2055 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
2058 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
2062 $andClauses = array();
2065 if (!empty($this->_where
)) {
2066 foreach ($this->_where
as $grouping => $values) {
2067 if ($grouping > 0 && !empty($values)) {
2068 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
2073 if (!empty($this->_where
[0])) {
2074 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
2076 if (!empty($clauses)) {
2077 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
2080 if ($validClauses > 1) {
2081 $this->_useDistinct
= TRUE;
2085 return implode(' AND ', $andClauses);
2089 * Generate where clause for any parameters not already handled.
2091 * @param array $values
2095 public function restWhere(&$values) {
2096 $name = CRM_Utils_Array
::value(0, $values);
2097 $op = CRM_Utils_Array
::value(1, $values);
2098 $value = CRM_Utils_Array
::value(2, $values);
2099 $grouping = CRM_Utils_Array
::value(3, $values);
2100 $wildcard = CRM_Utils_Array
::value(4, $values);
2102 if (isset($grouping) && empty($this->_where
[$grouping])) {
2103 $this->_where
[$grouping] = array();
2106 $multipleFields = array('url');
2108 //check if the location type exists for fields
2110 $locType = explode('-', $name);
2112 if (!in_array($locType[0], $multipleFields)) {
2113 //add phone type if exists
2114 if (isset($locType[2]) && $locType[2]) {
2115 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
2119 $field = CRM_Utils_Array
::value($name, $this->_fields
);
2122 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
2131 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2132 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2133 if (isset($locType[1]) && is_numeric($locType[1])) {
2134 $lType = $locationType[$locType[1]];
2137 $field['title'] .= " ($lType)";
2140 if (substr($name, 0, 14) === 'state_province') {
2141 if (isset($locType[1]) && is_numeric($locType[1])) {
2143 $aName = "{$lType}-address";
2144 $where = "`$aName`.state_province_id";
2147 $where = "civicrm_address.state_province_id";
2150 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value);
2151 $this->_tables
[$aName] = $this->_whereTables
[$aName] = 1;
2152 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
2153 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
2155 elseif (!empty($field['pseudoconstant'])) {
2156 $this->optionValueQuery(
2157 $name, $op, $value, $grouping,
2158 'CRM_Contact_DAO_Contact',
2164 if ($name == 'gender_id') {
2165 self
::$_openedPanes[ts('Demographics')] = TRUE;
2168 elseif (substr($name, 0, 7) === 'country' ||
substr($name, 0, 6) === 'county') {
2169 $name = (substr($name, 0, 7) === 'country') ?
"country_id" : "county_id";
2170 if (isset($locType[1]) && is_numeric($locType[1])) {
2172 $aName = "{$lType}-address";
2173 $where = "`$aName`.$name";
2176 $where = "civicrm_address.$name";
2179 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2180 $this->_tables
[$aName] = $this->_whereTables
[$aName] = 1;
2182 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
2183 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
2185 elseif ($name === 'world_region') {
2186 $this->optionValueQuery(
2187 $name, $op, $value, $grouping,
2195 elseif ($name === 'is_deceased') {
2196 $this->setQillAndWhere($name, $op, $value, $grouping, $field);
2197 self
::$_openedPanes[ts('Demographics')] = TRUE;
2199 elseif ($name === 'created_date' ||
$name === 'modified_date' ||
$name === 'deceased_date' ||
$name === 'birth_date') {
2200 $appendDateTime = TRUE;
2201 if ($name === 'deceased_date' ||
$name === 'birth_date') {
2202 $appendDateTime = FALSE;
2203 self
::$_openedPanes[ts('Demographics')] = TRUE;
2205 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2207 elseif ($name === 'contact_id') {
2208 if (is_int($value)) {
2209 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2210 $this->_qill
[$grouping][] = "$field[title] $op $value";
2213 elseif ($name === 'name') {
2214 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2217 $value = self
::getWildCardedValue($wildcard, $op, $value);
2219 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
2220 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2221 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2222 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2224 elseif ($name === 'current_employer') {
2227 $value = self
::getWildCardedValue($wildcard, $op, $value);
2229 $ceWhereClause = self
::buildClause("contact_a.organization_name", $op,
2232 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2233 $this->_where
[$grouping][] = $ceWhereClause;
2234 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2236 elseif ($name === 'email_greeting') {
2237 $filterCondition = array('greeting_type' => 'email_greeting');
2238 $this->optionValueQuery(
2239 $name, $op, $value, $grouping,
2240 CRM_Core_PseudoConstant
::greeting($filterCondition),
2242 ts('Email Greeting')
2245 elseif ($name === 'postal_greeting') {
2246 $filterCondition = array('greeting_type' => 'postal_greeting');
2247 $this->optionValueQuery(
2248 $name, $op, $value, $grouping,
2249 CRM_Core_PseudoConstant
::greeting($filterCondition),
2251 ts('Postal Greeting')
2254 elseif ($name === 'addressee') {
2255 $filterCondition = array('greeting_type' => 'addressee');
2256 $this->optionValueQuery(
2257 $name, $op, $value, $grouping,
2258 CRM_Core_PseudoConstant
::greeting($filterCondition),
2263 elseif (substr($name, 0, 4) === 'url-') {
2264 $tName = 'civicrm_website';
2265 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2266 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2269 $value = self
::getWildCardedValue($wildcard, $op, $value);
2272 $this->_where
[$grouping][] = $d = self
::buildClause('civicrm_website.url', $op, $value);
2273 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2275 elseif ($name === 'contact_is_deleted') {
2276 $this->setQillAndWhere('is_deleted', $op, $value, $grouping, $field);
2278 elseif (!empty($field['where'])) {
2280 if (!empty($field['type'])) {
2281 $type = CRM_Utils_Type
::typeToString($field['type']);
2284 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2286 if (isset($locType[1]) &&
2287 is_numeric($locType[1])
2291 //get the location name
2292 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2293 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
2294 $fieldName = "LOWER(`$tName`.$fldName)";
2296 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2297 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2301 if ($tableName == 'civicrm_contact') {
2302 $fieldName = "contact_a.{$fieldName}";
2305 if ($op != 'IN' && !is_numeric($value) && !is_array($value)) {
2306 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
2307 $fieldName = "LOWER({$field['where']})";
2310 $fieldName = "{$field['where']}";
2315 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2316 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(
2317 1 => $field['title'],
2319 3 => (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) ?
$qillVal : "'$qillVal'"));
2321 if (is_array($value)) {
2322 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2323 // for api style operators for functions that hit this point without worrying about regression
2324 // (the previous comments indicated the condition for hitting this point were unknown
2325 // per CRM-14743 we are adding modified_date & created_date operator support
2326 $operations = array_keys($value);
2327 foreach ($operations as $operator) {
2328 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2329 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2330 //so this condition will satisfy the search for now
2331 if (strpos($op, 'IN') !== FALSE) {
2332 $value = array($op => $value);
2334 // we don't know when this might happen
2336 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $operator)));
2340 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($fieldName, $value, $type);
2343 if (!strpos($op, 'IN')) {
2344 $value = $strtolower($value);
2348 $value = self
::getWildCardedValue($wildcard, $op, $value);
2351 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2355 if ($setTables && isset($field['where'])) {
2356 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2357 if (isset($tableName)) {
2358 $this->_tables
[$tableName] = 1;
2359 $this->_whereTables
[$tableName] = 1;
2371 public static function getLocationTableName(&$where, &$locType) {
2372 if (isset($locType[1]) && is_numeric($locType[1])) {
2373 list($tbName, $fldName) = explode(".", $where);
2375 //get the location name
2376 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2377 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2378 if (in_array($locType[0], $specialFields)) {
2379 //hack to fix / special handing for phone_ext
2380 if ($locType[0] == 'phone_ext') {
2381 $locType[0] = 'phone';
2383 if (isset($locType[2]) && $locType[2]) {
2384 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2387 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2390 elseif (in_array($locType[0],
2395 'street_number_suffix',
2397 'supplemental_address_1',
2398 'supplemental_address_2',
2399 'supplemental_address_3',
2402 'postal_code_suffix',
2408 //fix for search by profile with address fields.
2409 $tName = "{$locationType[$locType[1]]}-address";
2411 elseif (in_array($locType[0],
2419 $tName = "{$locationType[$locType[1]]}-email";
2421 elseif ($locType[0] == 'provider_id') {
2422 $tName = "{$locationType[$locType[1]]}-im";
2424 elseif ($locType[0] == 'openid') {
2425 $tName = "{$locationType[$locType[1]]}-openid";
2428 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2430 $tName = str_replace(' ', '_', $tName);
2431 return array($tName, $fldName);
2433 CRM_Core_Error
::fatal();
2437 * Given a result dao, extract the values and return that array
2439 * @param CRM_Core_DAO $dao
2442 * values for this query
2444 public function store($dao) {
2447 foreach ($this->_element
as $key => $dontCare) {
2448 if (property_exists($dao, $key)) {
2449 if (strpos($key, '-') !== FALSE) {
2450 $values = explode('-', $key);
2451 $lastElement = array_pop($values);
2453 $cnt = count($values);
2455 foreach ($values as $v) {
2456 if (!array_key_exists($v, $current)) {
2457 $current[$v] = array();
2459 //bad hack for im_provider
2460 if ($lastElement == 'provider_id') {
2461 if ($count < $cnt) {
2462 $current = &$current[$v];
2465 $lastElement = "{$v}_{$lastElement}";
2469 $current = &$current[$v];
2474 $current[$lastElement] = $dao->$key;
2477 $value[$key] = $dao->$key;
2485 * Getter for tables array.
2489 public function tables() {
2490 return $this->_tables
;
2494 * Sometimes used to create the from clause, but, not reliably, set
2495 * this AND set tables.
2497 * It's unclear the intent - there is a 'simpleFrom' clause which
2498 * takes whereTables into account & a fromClause which doesn't.
2500 * logic may have eroded?
2504 public function whereTables() {
2505 return $this->_whereTables
;
2509 * Generate the where clause (used in match contacts and permissions)
2511 * @param array $params
2512 * @param array $fields
2513 * @param array $tables
2514 * @param $whereTables
2515 * @param bool $strict
2519 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2520 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2524 $tables = array_merge($query->tables(), $tables);
2525 $whereTables = array_merge($query->whereTables(), $whereTables);
2527 return $query->_whereClause
;
2531 * Create the from clause.
2533 * @param array $tables
2534 * Tables that need to be included in this from clause. If null,
2535 * return mimimal from clause (i.e. civicrm_contact).
2536 * @param array $inner
2537 * Tables that should be inner-joined.
2538 * @param array $right
2539 * Tables that should be right-joined.
2540 * @param bool $primaryLocation
2541 * Search on primary location. See note below.
2543 * Determines search mode based on bitwise MODE_* constants.
2544 * @param string|NULL $apiEntity
2545 * Determines search mode based on entity by string.
2547 * The $primaryLocation flag only seems to be used when
2548 * locationType() has been called. This may be a search option
2549 * exposed, or perhaps it's a "search all details" approach which
2550 * predates decoupling of location types and primary fields?
2552 * @see https://issues.civicrm.org/jira/browse/CRM-19967
2557 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1, $apiEntity = NULL) {
2559 $from = ' FROM civicrm_contact contact_a';
2560 if (empty($tables)) {
2564 if (!empty($tables['civicrm_worldregion'])) {
2565 $tables = array_merge(array('civicrm_country' => 1), $tables);
2568 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2569 CRM_Utils_Array
::value('civicrm_county', $tables)
2570 ) && empty($tables['civicrm_address'])
2572 $tables = array_merge(array('civicrm_address' => 1),
2577 // add group_contact and group table is subscription history is present
2578 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2579 $tables = array_merge(array(
2580 'civicrm_group' => 1,
2581 'civicrm_group_contact' => 1,
2587 // to handle table dependencies of components
2588 CRM_Core_Component
::tableNames($tables);
2589 // to handle table dependencies of hook injected tables
2590 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2592 //format the table list according to the weight
2593 $info = CRM_Core_TableHierarchy
::info();
2595 foreach ($tables as $key => $value) {
2597 if (strpos($key, '-') !== FALSE) {
2598 $keyArray = explode('-', $key);
2599 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2601 elseif (strpos($key, '_') !== FALSE) {
2602 $keyArray = explode('_', $key);
2603 if (is_numeric(array_pop($keyArray))) {
2604 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2607 $k = CRM_Utils_Array
::value($key, $info, 99);
2611 $k = CRM_Utils_Array
::value($key, $info, 99);
2613 $tempTable[$k . ".$key"] = $key;
2616 $newTables = array();
2617 foreach ($tempTable as $key) {
2618 $newTables[$key] = $tables[$key];
2621 $tables = $newTables;
2623 foreach ($tables as $name => $value) {
2628 if (!empty($inner[$name])) {
2631 elseif (!empty($right[$name])) {
2639 // if there is already a join statement in value, use value itself
2640 if (strpos($value, 'JOIN')) {
2641 $from .= " $value ";
2644 $from .= " $side JOIN $name ON ( $value ) ";
2649 $limitToPrimaryClause = $primaryLocation ?
"AND {$name}.is_primary = 1" : '';
2652 case 'civicrm_address':
2653 //CRM-14263 further handling of address joins further down...
2654 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id {$limitToPrimaryClause} )";
2657 case 'civicrm_phone':
2658 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id {$limitToPrimaryClause}) ";
2661 case 'civicrm_email':
2662 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id {$limitToPrimaryClause})";
2666 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id {$limitToPrimaryClause}) ";
2670 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2671 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2672 $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)";
2675 case 'civicrm_openid':
2676 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id {$limitToPrimaryClause} )";
2679 case 'civicrm_worldregion':
2680 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2681 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2684 case 'civicrm_location_type':
2685 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2688 case 'civicrm_group':
2689 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2692 case 'civicrm_group_contact':
2693 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2696 case 'civicrm_group_contact_cache':
2697 $from .= " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
2700 case 'civicrm_activity':
2701 case 'civicrm_activity_tag':
2702 case 'activity_type':
2703 case 'activity_status':
2705 case 'civicrm_activity_contact':
2706 case 'source_contact':
2707 case 'activity_priority':
2708 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2711 case 'civicrm_entity_tag':
2712 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2713 civicrm_entity_tag.entity_id = contact_a.id ) ";
2716 case 'civicrm_note':
2717 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2718 contact_a.id = civicrm_note.entity_id ) ";
2721 case 'civicrm_subscription_history':
2722 $from .= " $side JOIN civicrm_subscription_history
2723 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2724 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2727 case 'civicrm_relationship':
2728 if (self
::$_relType == 'reciprocal') {
2729 if (self
::$_relationshipTempTable) {
2730 // we have a temptable to join on
2731 $tbl = self
::$_relationshipTempTable;
2732 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2735 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2736 $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)";
2739 elseif (self
::$_relType == 'b') {
2740 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2741 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2744 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2745 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2750 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2751 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2755 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2758 case 'civicrm_grant':
2759 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2762 case 'civicrm_campaign':
2763 //Move to default case if not in either mode.
2764 if ($mode & CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
2765 $from .= CRM_Contribute_BAO_Query
::from($name, $mode, $side);
2768 elseif ($mode & CRM_Contact_BAO_Query
::MODE_MAILING
) {
2769 $from .= CRM_Mailing_BAO_Query
::from($name, $mode, $side);
2772 elseif ($mode & CRM_Contact_BAO_Query
::MODE_CAMPAIGN
) {
2773 $from .= CRM_Campaign_BAO_Query
::from($name, $mode, $side);
2777 case 'civicrm_website':
2778 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2782 $locationTypeName = '';
2783 if (strpos($name, '-address') != 0) {
2784 $locationTypeName = 'address';
2786 elseif (strpos($name, '-phone') != 0) {
2787 $locationTypeName = 'phone';
2789 elseif (strpos($name, '-email') != 0) {
2790 $locationTypeName = 'email';
2792 elseif (strpos($name, '-im') != 0) {
2793 $locationTypeName = 'im';
2795 elseif (strpos($name, '-openid') != 0) {
2796 $locationTypeName = 'openid';
2799 if ($locationTypeName) {
2800 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2801 $parts = explode('-', $name);
2802 $locationTypes = CRM_Core_BAO_Address
::buildOptions('location_type_id', 'get');
2803 foreach ($locationTypes as $locationTypeID => $locationType) {
2804 if ($parts[0] == str_replace(' ', '_', $locationType)) {
2805 $locationID = $locationTypeID;
2808 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2811 $from .= CRM_Core_Component
::from($name, $mode, $side);
2813 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2822 * WHERE / QILL clause for deleted_contacts
2824 * @param array $values
2826 public function deletedContacts($values) {
2827 list($_, $_, $value, $grouping, $_) = $values;
2829 // *prepend* to the relevant grouping as this is quite an important factor
2830 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2835 * Where / qill clause for contact_type
2839 public function contactType(&$values) {
2840 list($name, $op, $value, $grouping, $wildcard) = $values;
2842 $subTypes = array();
2845 // account for search builder mapping multiple values
2846 if (!is_array($value)) {
2847 $values = self
::parseSearchBuilderString($value, 'String');
2848 if (is_array($values)) {
2849 $value = array_flip($values);
2853 if (is_array($value)) {
2854 foreach ($value as $k => $v) {
2859 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2860 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2863 if (!empty($subType)) {
2864 $subTypes[$subType] = 1;
2866 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2871 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2872 $contactType = $contactTypeANDSubType[0];
2873 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2874 if (!empty($subType)) {
2875 $subTypes[$subType] = 1;
2877 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2881 if (!empty($clause)) {
2883 if ($op == 'IN' ||
$op == 'NOT IN') {
2884 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2887 $type = array_pop($clause);
2888 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2891 $this->_qill
[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2893 if (!empty($subTypes)) {
2894 $this->includeContactSubTypes($subTypes, $grouping);
2900 * Where / qill clause for contact_sub_type.
2902 * @param array $values
2904 public function contactSubType(&$values) {
2905 list($name, $op, $value, $grouping, $wildcard) = $values;
2906 $this->includeContactSubTypes($value, $grouping, $op);
2914 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2916 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2918 $value = $value[$op];
2922 $alias = "contact_a.contact_sub_type";
2923 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
2925 $op = str_replace('IN', 'LIKE', $op);
2926 $op = str_replace('=', 'LIKE', $op);
2927 $op = str_replace('!', 'NOT ', $op);
2929 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2930 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
2932 elseif (is_array($value)) {
2933 foreach ($value as $k => $v) {
2934 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($v, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2938 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2941 if (!empty($clause)) {
2942 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2944 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', array(1 => $qillOperators[$op])) . implode(' ' . ts('or') . ' ', array_keys($clause));
2948 * Where / qill clause for groups.
2952 public function group($values) {
2953 list($name, $op, $value, $grouping, $wildcard) = $values;
2955 // If the $value is in OK (operator as key) array format we need to extract the key as operator and value first
2956 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2958 $value = $value[$op];
2961 // Replace pseudo operators from search builder
2962 $op = str_replace('EMPTY', 'NULL', $op);
2964 if (strpos($op, 'NULL')) {
2968 if (count($value) > 1) {
2969 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
2970 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $op)));
2972 $this->_useDistinct
= TRUE;
2975 if (isset($value)) {
2976 $value = CRM_Utils_Array
::value($op, $value, $value);
2979 if ($name == 'group_type') {
2980 $value = array_keys($this->getGroupsFromTypeCriteria($value));
2983 $regularGroupIDs = $smartGroupIDs = array();
2984 foreach ((array) $value as $id) {
2985 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
2986 $smartGroupIDs[] = $id;
2989 $regularGroupIDs[] = $id;
2993 $isNotOp = ($op == 'NOT IN' ||
$op == '!=');
2996 $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
2998 is_array($gcsValues[2])
3000 foreach ($gcsValues[2] as $k => $v) {
3002 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
3007 $statii[] = "'Added'";
3009 $groupClause = array();
3010 if (count($regularGroupIDs) ||
empty($value)) {
3011 // include child groups IDs if any
3012 $childGroupIds = (array) CRM_Contact_BAO_Group
::getChildGroupIds($regularGroupIDs);
3013 foreach ($childGroupIds as $key => $id) {
3014 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
3015 $smartGroupIDs[] = $id;
3016 unset($childGroupIds[$key]);
3019 if (count($childGroupIds)) {
3020 $regularGroupIDs = array_merge($regularGroupIDs, $childGroupIds);
3023 // if $regularGroupIDs is populated with regular child group IDs
3024 // then change the mysql operator to desired
3025 if (count($regularGroupIDs) > 1) {
3026 $op = strpos($op, 'IN') ?
$op : ($op == '!=') ?
'NOT IN' : 'IN';
3028 $groupIds = implode(',', (array) $regularGroupIDs);
3029 $gcTable = "`civicrm_group_contact-{$groupIds}`";
3030 $joinClause = array("contact_a.id = {$gcTable}.contact_id");
3032 if (strpos($op, 'IN') !== FALSE) {
3033 $clause = "{$gcTable}.group_id $op ( $groupIds ) ";
3035 elseif ($op == '!=') {
3036 $clause = "{$gcTable}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact cgc WHERE cgc.group_id = $groupIds )";
3039 $clause = "{$gcTable}.group_id $op $groupIds ";
3041 $groupClause[] = "( {$clause} )";
3044 $joinClause[] = "{$gcTable}.status IN (" . implode(', ', $statii) . ")";
3046 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3049 //CRM-19589: contact(s) removed from a Smart Group, resides in civicrm_group_contact table
3050 if (count($smartGroupIDs)) {
3051 $groupClause[] = " ( " . $this->addGroupContactCache($smartGroupIDs, NULL, "contact_a", $op) . " ) ";
3054 $and = ($op == 'IS NULL') ?
' AND ' : ' OR ';
3055 $this->_where
[$grouping][] = ' ( ' . implode($and, $groupClause) . ' ) ';
3057 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
3058 $this->_qill
[$grouping][] = ts("Group(s) %1 %2", array(1 => $qillop, 2 => $qillVal));
3059 if (strpos($op, 'NULL') === FALSE) {
3060 $this->_qill
[$grouping][] = ts("Group Status %1", array(1 => implode(' ' . ts('or') . ' ', $statii)));
3065 * Function translates selection of group type into a list of groups.
3070 public function getGroupsFromTypeCriteria($value) {
3071 $groupIds = array();
3072 foreach ((array) $value as $groupTypeValue) {
3073 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
3074 $groupIds = ($groupIds +
$groupList);
3080 * @param array $groups
3081 * @param string $tableAlias
3082 * @param string $joinTable
3085 * @return null|string
3087 public function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a", $op) {
3088 $isNullOp = (strpos($op, 'NULL') !== FALSE);
3089 $groupsIds = $groups;
3090 if (!$isNullOp && !$groups) {
3093 elseif (strpos($op, 'IN') !== FALSE) {
3094 $groups = array($op => $groups);
3096 elseif (is_array($groups) && count($groups)) {
3097 $groups = array('IN' => $groups);
3100 // Find all the groups that are part of a saved search.
3101 $smartGroupClause = self
::buildClause("id", $op, $groups, 'Int');
3103 SELECT id, cache_date, saved_search_id, children
3105 WHERE $smartGroupClause
3106 AND ( saved_search_id != 0
3107 OR saved_search_id IS NOT NULL
3108 OR children IS NOT NULL )
3111 $group = CRM_Core_DAO
::executeQuery($sql);
3113 while ($group->fetch()) {
3114 $this->_useDistinct
= TRUE;
3115 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
3116 CRM_Contact_BAO_GroupContactCache
::load($group);
3119 if ($group->N
== 0) {
3124 $tableAlias = "`civicrm_group_contact_cache_";
3125 $tableAlias .= ($isNullOp) ?
"a`" : implode(',', (array) $groupsIds) . "`";
3128 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.id = {$tableAlias}.contact_id ";
3129 return self
::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
3133 * Where / qill clause for cms users
3137 public function ufUser(&$values) {
3138 list($name, $op, $value, $grouping, $wildcard) = $values;
3141 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3143 $this->_qill
[$grouping][] = ts('CMS User');
3145 elseif ($value == 0) {
3146 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3148 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3149 $this->_qill
[$grouping][] = ts('Not a CMS User');
3154 * All tag search specific.
3156 * @param array $values
3158 public function tagSearch(&$values) {
3159 list($name, $op, $value, $grouping, $wildcard) = $values;
3162 $value = "%{$value}%";
3164 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3165 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3167 $etTable = "`civicrm_entity_tag-" . $value . "`";
3168 $tTable = "`civicrm_tag-" . $value . "`";
3170 if ($useAllTagTypes[2]) {
3171 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3172 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3173 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3175 // search tag in cases
3176 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3177 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
3178 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3179 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3180 LEFT JOIN civicrm_case
3181 ON (civicrm_case_contact.case_id = civicrm_case.id
3182 AND civicrm_case.is_deleted = 0 )
3183 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3184 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3185 // search tag in activities
3186 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3187 $tActTable = "`civicrm_act_tag-" . $value . "`";
3188 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3189 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3191 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3192 = " LEFT JOIN civicrm_activity_contact
3193 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3194 LEFT JOIN civicrm_activity
3195 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3196 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3197 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3198 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3200 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $value . "' OR {$tCaseTable}.name $op '" . $value . "' OR {$tActTable}.name $op '" . $value . "')";
3201 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
3204 $etTable = "`civicrm_entity_tag-" . $value . "`";
3205 $tTable = "`civicrm_tag-" . $value . "`";
3206 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3207 {$etTable}.entity_table = 'civicrm_contact' )
3208 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3210 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3211 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
3216 * Where / qill clause for tag.
3218 * @param array $values
3220 public function tag(&$values) {
3221 list($name, $op, $value, $grouping, $wildcard) = $values;
3223 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, array('onlyActive' => FALSE));
3224 // API/Search Builder format array(operator => array(values))
3225 if (is_array($value)) {
3226 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3228 $value = $value[$op];
3230 if (count($value) > 1) {
3231 $this->_useDistinct
= TRUE;
3233 $value = implode(',', (array) $value);
3236 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3237 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3239 $etTable = "`civicrm_entity_tag-" . $value . "`";
3241 if ($useAllTagTypes[2]) {
3242 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3243 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3245 // search tag in cases
3246 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3247 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3248 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3250 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3251 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3252 LEFT JOIN civicrm_case
3253 ON (civicrm_case_contact.case_id = civicrm_case.id
3254 AND civicrm_case.is_deleted = 0 )
3255 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3256 // search tag in activities
3257 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3258 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3259 = " LEFT JOIN civicrm_activity_contact
3260 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3261 LEFT JOIN civicrm_activity
3262 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3263 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3264 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3267 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3268 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3271 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3275 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3276 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3279 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3280 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3281 $op = str_replace('EMPTY', 'NULL', $op);
3282 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3284 // CRM-16941: for tag tried with != operator we don't show contact who don't have given $value AND also in other tag
3285 elseif ($op == '!=') {
3286 $this->_where
[$grouping][] = "{$etTable}.entity_id NOT IN (SELECT entity_id FROM civicrm_entity_tag cet WHERE cet.entity_table = 'civicrm_contact' AND " . self
::buildClause("cet.tag_id", '=', $value, 'Int') . ")";
3288 elseif ($op == '=' ||
strstr($op, 'IN')) {
3289 $op = ($op == '=') ?
'IN' : $op;
3290 $this->_where
[$grouping][] = "{$etTable}.tag_id $op ( $value )";
3293 $this->_qill
[$grouping][] = ts('Tagged %1 %2', array(1 => $qillop, 2 => $qillVal));
3297 * Where/qill clause for notes
3299 * @param array $values
3301 public function notes(&$values) {
3302 list($name, $op, $value, $grouping, $wildcard) = $values;
3304 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3305 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3306 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3308 $this->_useDistinct
= TRUE;
3310 $this->_tables
['civicrm_note'] = $this->_whereTables
['civicrm_note']
3311 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3313 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3315 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3317 if (strpos($value, '%') === FALSE) {
3318 $value = "%$value%";
3322 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3328 if ($noteOption %
2 == 0) {
3329 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3330 $label = ts('Note: Body Only');
3332 if ($noteOption %
3 == 0) {
3333 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3334 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3336 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3337 list($qillOp, $qillVal) = self
::buildQillForFieldValue(NULL, $name, $n, $op);
3338 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillOp, 3 => $qillVal));
3342 * @param string $name
3348 public function nameNullOrEmptyOp($name, $op, $grouping) {
3352 $this->_where
[$grouping][] = "contact_a.$name $op";
3353 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3357 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3358 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3361 case 'IS NOT EMPTY':
3362 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3363 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3372 * Where / qill clause for sort_name
3374 * @param array $values
3376 public function sortName(&$values) {
3377 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3379 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3380 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3384 $input = $value = trim($value);
3386 if (!strlen($value)) {
3390 $config = CRM_Core_Config
::singleton();
3394 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3397 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3399 $firstChar = substr($value, 0, 1);
3400 $lastChar = substr($value, -1, 1);
3401 $quotes = array("'", '"');
3402 // If string is quoted, strip quotes and otherwise don't alter it
3403 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3404 $value = trim($value, implode('', $quotes));
3406 // Replace spaces with wildcards for a LIKE operation
3407 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3408 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3409 $value = str_replace(' ', '%', $value);
3411 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($value)));
3412 if (strlen($value)) {
3413 $fieldsub = array();
3414 $value = "'" . self
::getWildCardedValue($wildcard, $op, $value) . "'";
3415 if ($fieldName == 'sort_name') {
3416 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3417 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3420 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3421 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3423 $fieldsub[] = " ( $wc $op $value )";
3424 if ($config->includeNickNameInName
) {
3425 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3426 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3427 $fieldsub[] = " ( $wc $op $value )";
3429 if ($config->includeEmailInName
) {
3430 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3432 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3435 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3437 $this->_where
[$grouping][] = $sub;
3438 if ($config->includeEmailInName
) {
3439 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3440 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3443 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3448 * Where/qill clause for greeting fields.
3450 * @param array $values
3452 public function greetings(&$values) {
3453 list($name, $op, $value, $grouping, $wildcard) = $values;
3454 $name .= '_display';
3456 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
3457 $this->_qill
[$grouping][] = ts('Greeting %1 %2', array(1 => $qillop, 2 => $qillVal));
3458 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value, 'String');
3462 * Where / qill clause for email
3464 * @param array $values
3465 * @param string $apiEntity
3467 protected function email(&$values, $apiEntity) {
3468 list($name, $op, $value, $grouping, $wildcard) = $values;
3469 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3471 // CRM-18147: for Contact's GET API, email fieldname got appended with its entity as in {$apiEntiy}_{$name}
3472 // so following code is use build whereClause for contact's primart email id
3473 if (!empty($apiEntity)) {
3474 $dataType = 'String';
3475 if ($name == 'email_id') {
3476 $dataType = 'Integer';
3480 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.is_primary', '=', 1, 'Integer');
3481 $this->_where
[$grouping][] = self
::buildClause("civicrm_email.$name", $op, $value, $dataType);
3485 $n = strtolower(trim($value));
3487 if (substr($n, 0, 1) == '"' &&
3488 substr($n, -1, 1) == '"'
3490 $n = substr($n, 1, -1);
3491 $value = CRM_Core_DAO
::escapeString($n);
3495 $value = self
::getWildCardedValue($wildcard, $op, $n);
3497 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3498 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3501 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3502 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3507 * Where / qill clause for phone number
3509 * @param array $values
3511 public function phone_numeric(&$values) {
3512 list($name, $op, $value, $grouping, $wildcard) = $values;
3513 // Strip non-numeric characters; allow wildcards
3514 $number = preg_replace('/[^\d%]/', '', $value);
3516 if (strpos($number, '%') === FALSE) {
3517 $number = "%$number%";
3520 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3521 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3522 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3527 * Where / qill clause for phone type/location
3529 * @param array $values
3531 public function phone_option_group($values) {
3532 list($name, $op, $value, $grouping, $wildcard) = $values;
3533 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3534 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3535 $optionName = $options[$value];
3536 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3537 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3538 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3542 * Where / qill clause for street_address.
3544 * @param array $values
3546 public function street_address(&$values) {
3547 list($name, $op, $value, $grouping, $wildcard) = $values;
3556 $value = strtolower($n);
3557 if (strpos($value, '%') === FALSE) {
3558 // only add wild card if not there
3559 $value = "%{$value}%";
3562 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3563 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3564 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3567 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3568 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3571 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3575 * Where / qill clause for street_unit.
3577 * @param array $values
3579 public function street_number(&$values) {
3580 list($name, $op, $value, $grouping, $wildcard) = $values;
3588 if (strtolower($n) == 'odd') {
3589 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3590 $this->_qill
[$grouping][] = ts('Street Number is odd');
3592 elseif (strtolower($n) == 'even') {
3593 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3594 $this->_qill
[$grouping][] = ts('Street Number is even');
3597 $value = strtolower($n);
3599 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3600 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3601 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3604 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3608 * Where / qill clause for sorting by character.
3610 * @param array $values
3612 public function sortByCharacter(&$values) {
3613 list($name, $op, $value, $grouping, $wildcard) = $values;
3615 $name = trim($value);
3616 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3617 $this->_where
[$grouping][] = $cond;
3618 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3622 * Where / qill clause for including contact ids.
3624 public function includeContactIDs() {
3625 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3629 $contactIds = array();
3630 foreach ($this->_params
as $id => $values) {
3631 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3632 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3635 CRM_Utils_Type
::validateAll($contactIds, 'Positive');
3636 if (!empty($contactIds)) {
3637 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3642 * Where / qill clause for postal code.
3644 * @param array $values
3646 public function postalCode(&$values) {
3647 // skip if the fields dont have anything to do with postal_code
3648 if (empty($this->_fields
['postal_code'])) {
3652 list($name, $op, $value, $grouping, $wildcard) = $values;
3654 // Handle numeric postal code range searches properly by casting the column as numeric
3655 if (is_numeric($value)) {
3656 $field = "IF (civicrm_address.postal_code REGEXP '^[0-9]{1,10}$', CAST(civicrm_address.postal_code AS UNSIGNED), 0)";
3657 $val = CRM_Utils_Type
::escape($value, 'Integer');
3660 $field = 'civicrm_address.postal_code';
3661 // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string.
3662 if (!is_array($value)) {
3663 $val = CRM_Utils_Type
::escape($value, 'String');
3666 // Do we need to escape values here? I would expect buildClause does.
3671 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3673 if ($name == 'postal_code') {
3674 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3675 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3677 elseif ($name == 'postal_code_low') {
3678 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3679 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3681 elseif ($name == 'postal_code_high') {
3682 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3683 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3688 * Where / qill clause for location type.
3690 * @param array $values
3691 * @param null $status
3695 public function locationType(&$values, $status = NULL) {
3696 list($name, $op, $value, $grouping, $wildcard) = $values;
3698 if (is_array($value)) {
3699 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3700 $this->_tables
['civicrm_address'] = 1;
3701 $this->_whereTables
['civicrm_address'] = 1;
3703 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3705 foreach ($value as $id) {
3706 $names[] = $locationType[$id];
3709 $this->_primaryLocation
= FALSE;
3712 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3715 return implode(' ' . ts('or') . ' ', $names);
3722 * @param bool $fromStateProvince
3724 * @return array|NULL
3726 public function country(&$values, $fromStateProvince = TRUE) {
3727 list($name, $op, $value, $grouping, $wildcard) = $values;
3729 if (!$fromStateProvince) {
3730 $stateValues = $this->getWhereValues('state_province', $grouping);
3731 if (!empty($stateValues)) {
3732 // return back to caller if there are state province values
3733 // since that handles this case
3738 $countryClause = $countryQill = NULL;
3739 if ($values && !empty($value)) {
3740 $this->_tables
['civicrm_address'] = 1;
3741 $this->_whereTables
['civicrm_address'] = 1;
3743 $countryClause = self
::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
3744 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, 'country_id', $value, $op);
3745 $countryQill = ts("%1 %2 %3", array(1 => 'Country', 2 => $qillop, 3 => $qillVal));
3747 if (!$fromStateProvince) {
3748 $this->_where
[$grouping][] = $countryClause;
3749 $this->_qill
[$grouping][] = $countryQill;
3753 if ($fromStateProvince) {
3754 if (!empty($countryClause)) {
3757 " ...AND... " . $countryQill,
3761 return array(NULL, NULL);
3767 * Where / qill clause for county (if present).
3769 * @param array $values
3770 * @param null $status
3774 public function county(&$values, $status = NULL) {
3775 list($name, $op, $value, $grouping, $wildcard) = $values;
3777 if (!is_array($value)) {
3778 // force the county to be an array
3779 $value = array($value);
3782 // check if the values are ids OR names of the counties
3783 $inputFormat = 'id';
3784 foreach ($value as $v) {
3785 if (!is_numeric($v)) {
3786 $inputFormat = 'name';
3794 elseif ($op == '!=') {
3798 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3799 $op = str_replace('EMPTY', 'NULL', $op);
3802 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3803 $clause = "civicrm_address.county_id $op";
3805 elseif ($inputFormat == 'id') {
3806 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3808 $county = CRM_Core_PseudoConstant
::county();
3809 foreach ($value as $id) {
3810 $names[] = CRM_Utils_Array
::value($id, $county);
3814 $inputClause = array();
3815 $county = CRM_Core_PseudoConstant
::county();
3816 foreach ($value as $name) {
3817 $name = trim($name);
3818 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3820 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3823 $this->_tables
['civicrm_address'] = 1;
3824 $this->_whereTables
['civicrm_address'] = 1;
3826 $this->_where
[$grouping][] = $clause;
3828 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3831 return implode(' ' . ts('or') . ' ', $names);
3836 * Where / qill clause for state/province AND country (if present).
3838 * @param array $values
3839 * @param null $status
3843 public function stateProvince(&$values, $status = NULL) {
3844 list($name, $op, $value, $grouping, $wildcard) = $values;
3846 $stateClause = self
::buildClause('civicrm_address.state_province_id', $op, $value, 'Positive');
3847 $this->_tables
['civicrm_address'] = 1;
3848 $this->_whereTables
['civicrm_address'] = 1;
3850 $countryValues = $this->getWhereValues('country', $grouping);
3851 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3852 if ($countryClause) {
3853 $clause = "( $stateClause AND $countryClause )";
3856 $clause = $stateClause;
3859 $this->_where
[$grouping][] = $clause;
3860 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
3862 $this->_qill
[$grouping][] = ts("State/Province %1 %2 %3", array(1 => $qillop, 2 => $qillVal, 3 => $countryQill));
3865 return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill;
3870 * Where / qill clause for change log.
3872 * @param array $values
3874 public function changeLog(&$values) {
3875 list($name, $op, $value, $grouping, $wildcard) = $values;
3877 $targetName = $this->getWhereValues('changed_by', $grouping);
3882 $name = trim($targetName[2]);
3883 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3884 $name = $targetName[4] ?
"%$name%" : $name;
3885 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3886 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3887 $this->_qill
[$grouping][] = ts('Modified By') . " $name";
3893 public function modifiedDates($values) {
3894 $this->_useDistinct
= TRUE;
3896 // CRM-11281, default to added date if not set
3897 $fieldTitle = ts('Added Date');
3898 $fieldName = 'created_date';
3899 foreach (array_keys($this->_params
) as $id) {
3900 if ($this->_params
[$id][0] == 'log_date') {
3901 if ($this->_params
[$id][2] == 2) {
3902 $fieldTitle = ts('Modified Date');
3903 $fieldName = 'modified_date';
3908 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3910 self
::$_openedPanes[ts('Change Log')] = TRUE;
3916 public function demographics(&$values) {
3917 list($name, $op, $value, $grouping, $wildcard) = $values;
3919 if (($name == 'age_low') ||
($name == 'age_high')) {
3920 $this->ageRangeQueryBuilder($values,
3921 'contact_a', 'age', 'birth_date', ts('Age')
3924 elseif (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3926 $this->dateQueryBuilder($values,
3927 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3930 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3932 $this->dateQueryBuilder($values,
3933 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3937 self
::$_openedPanes[ts('Demographics')] = TRUE;
3943 public function privacy(&$values) {
3944 list($name, $op, $value, $grouping, $wildcard) = $values;
3945 //fixed for profile search listing CRM-4633
3946 if (strpbrk($value, "[")) {
3947 $value = "'{$value}'";
3949 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3952 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3954 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3955 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
3956 $title = $field ?
$field['title'] : $name;
3957 $this->_qill
[$grouping][] = "$title $op $value";
3963 public function privacyOptions($values) {
3964 list($name, $op, $value, $grouping, $wildcard) = $values;
3966 if (empty($value) ||
!is_array($value)) {
3970 // get the operator and toggle values
3971 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3974 strtolower($opValues[2] == 'AND')
3979 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3981 if ($toggleValues &&
3982 $toggleValues[2] == 2
3989 foreach ($value as $dontCare => $pOption) {
3990 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
3991 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3992 $title = $field ?
$field['title'] : $pOption;
3993 $qill[] = " $title = 1 ";
3996 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
3997 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
4003 public function preferredCommunication(&$values) {
4004 list($name, $op, $value, $grouping, $wildcard) = $values;
4006 if (!is_array($value)) {
4007 $value = str_replace(array('(', ')'), '', explode(",", $value));
4009 elseif (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
4011 $value = $value[$op];
4013 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Contact', $name, $value, $op);
4015 if (self
::caseImportant($op)) {
4016 $value = implode("[[:cntrl:]]|[[:cntrl:]]", (array) $value);
4017 $op = (strstr($op, '!') ||
strstr($op, 'NOT')) ?
'NOT RLIKE' : 'RLIKE';
4018 $value = "[[:cntrl:]]" . $value . "[[:cntrl:]]";
4021 $this->_where
[$grouping][] = self
::buildClause("contact_a.preferred_communication_method", $op, $value);
4022 $this->_qill
[$grouping][] = ts('Preferred Communication Method %1 %2', array(1 => $qillop, 2 => $qillVal));
4026 * Where / qill clause for relationship.
4028 * @param array $values
4030 public function relationship(&$values) {
4031 list($name, $op, $value, $grouping, $wildcard) = $values;
4032 if ($this->_relationshipValuesAdded
) {
4035 // also get values array for relation_target_name
4036 // for relationship search we always do wildcard
4037 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4038 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4039 $relStatus = $this->getWhereValues('relation_status', $grouping);
4040 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4041 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4043 $nameClause = $name = NULL;
4045 $name = trim($targetName[2]);
4046 if (substr($name, 0, 1) == '"' &&
4047 substr($name, -1, 1) == '"'
4049 $name = substr($name, 1, -1);
4050 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4051 $nameClause = "= '$name'";
4054 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4055 $nameClause = "LIKE '%{$name}%'";
4059 $rTypeValues = $relTypes = $relTypesIds = array();
4060 if (!empty($relationType)) {
4061 $relationType[2] = (array) $relationType[2];
4062 foreach ($relationType[2] as $relType) {
4063 $rel = explode('_', $relType);
4064 self
::$_relType .= $rel[1];
4065 $params = array('id' => $rel[0]);
4066 $typeValues = array();
4067 $rTypeValue = CRM_Contact_BAO_RelationshipType
::retrieve($params, $typeValues);
4068 if (!empty($rTypeValue)) {
4069 $rTypeValues[] = $rTypeValue;
4070 $relTypesIds[] = $rel[0];
4071 $relTypes[] = $relType;
4075 if (!empty($rTypeValues)) {
4076 foreach ($rTypeValues as $rTypeValue) {
4077 $rTypeValue = (array) $rTypeValue;
4078 if ($rTypeValue['name_a_b'] == $rTypeValue['name_b_a']) {
4079 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4080 //@todo unless we are dealing with a target group
4081 self
::$_relType = 'reciprocal';
4085 // if we are creating a temp table we build our own where for the relationship table
4086 $relationshipTempTable = NULL;
4087 if (self
::$_relType == 'reciprocal' && empty($targetGroup)) {
4089 self
::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO
::createTempTableName('civicrm_rel');
4091 $where[$grouping][] = " sort_name $nameClause ";
4095 $where = &$this->_where
;
4097 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4100 $allRelationshipType = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE);
4101 if ($nameClause ||
!$targetGroup) {
4102 if (!empty($relationType)) {
4104 foreach ($relTypes as $rel) {
4105 if (!empty($relQill)) {
4108 $relQill .= $allRelationshipType[$rel];
4110 $this->_qill
[$grouping][] = 'Relationship Type(s) ' . $relQill . " $name";
4113 $this->_qill
[$grouping][] = $name;
4117 //check to see if the target contact is in specified group
4119 //add contacts from static groups
4120 $this->_tables
['civicrm_relationship_group_contact'] = $this->_whereTables
['civicrm_relationship_group_contact']
4121 = " 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'";
4122 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4123 implode(",", $targetGroup[2]) . ") ) ";
4125 //add contacts from saved searches
4126 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b", $op);
4128 //set the group where clause
4130 $groupWhere[] = "( " . $ssWhere . " )";
4132 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4134 //Get the names of the target groups for the qill
4135 $groupNames = CRM_Core_PseudoConstant
::group();
4136 $qillNames = array();
4137 foreach ($targetGroup[2] as $groupId) {
4138 if (array_key_exists($groupId, $groupNames)) {
4139 $qillNames[] = $groupNames[$groupId];
4142 if (!empty($relationType)) {
4144 foreach ($relTypes as $rel) {
4145 if (!empty($relQill)) {
4148 $relQill .= $allRelationshipType[$rel];
4150 $this->_qill
[$grouping][] = 'Relationship Type(s) ' . $relQill . " ( " . implode(", ", $qillNames) . " )";
4153 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4157 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4158 $today = date('Ymd');
4159 //check for active, inactive and all relation status
4160 if ($relStatus[2] == 0) {
4161 $where[$grouping][] = "(
4162 civicrm_relationship.is_active = 1 AND
4163 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4164 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4166 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4168 elseif ($relStatus[2] == 1) {
4169 $where[$grouping][] = "(
4170 civicrm_relationship.is_active = 0 OR
4171 civicrm_relationship.end_date < {$today} OR
4172 civicrm_relationship.start_date > {$today}
4174 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4178 if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
)) {
4181 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4183 //check for permissioned, non-permissioned and all permissioned relations
4184 if ($relPermission[2] == 1) {
4185 $where[$grouping][] = "(
4186 civicrm_relationship.is_permission_a_b = 1
4188 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4190 elseif ($relPermission[2] == 2) {
4191 //non-allowed permission relationship.
4192 $where[$grouping][] = "(
4193 civicrm_relationship.is_permission_a_b = 0
4195 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4198 $this->addRelationshipDateClauses($grouping, $where);
4199 $this->addRelationshipActivePeriodClauses($grouping, $where);
4200 if (!empty($relTypes)) {
4201 $where[$grouping][] = 'civicrm_relationship.relationship_type_id IN (' . implode(',', $relTypesIds) . ')';
4203 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4204 $this->_useDistinct
= TRUE;
4205 $this->_relationshipValuesAdded
= TRUE;
4206 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4208 // @todo creating a temp table could be expanded to group filter
4209 // as even creating a temp table of all relationships is much much more efficient than
4210 // an OR in the join
4211 if ($relationshipTempTable) {
4213 if (!empty($where[$grouping])) {
4214 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4215 $whereClause = str_replace('contact_b', 'c', $whereClause);
4218 CREATE TEMPORARY TABLE {$relationshipTempTable}
4219 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4220 FROM civicrm_relationship
4221 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4224 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4225 FROM civicrm_relationship
4226 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4229 CRM_Core_DAO
::executeQuery($sql);
4234 * Add start & end date criteria in
4235 * @param string $grouping
4236 * @param array $where
4237 * = array to add where clauses to, in case you are generating a temp table.
4238 * not the main query.
4240 public function addRelationshipDateClauses($grouping, &$where) {
4241 $dateValues = array();
4247 foreach ($dateTypes as $dateField) {
4248 $dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping);
4249 $dateValueHigh = $this->getWhereValues('relation_' . $dateField . '_high', $grouping);
4250 if (!empty($dateValueLow)) {
4251 $date = date('Ymd', strtotime($dateValueLow[2]));
4252 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4253 $this->_qill
[$grouping][] = ($dateField == 'end_date' ?
ts('Relationship Ended on or After') : ts('Relationship Recorded Start Date On or After')) . " " . CRM_Utils_Date
::customFormat($date);
4255 if (!empty($dateValueHigh)) {
4256 $date = date('Ymd', strtotime($dateValueHigh[2]));
4257 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4258 $this->_qill
[$grouping][] = ($dateField == 'end_date' ?
ts('Relationship Ended on or Before') : ts('Relationship Recorded Start Date On or Before')) . " " . CRM_Utils_Date
::customFormat($date);
4264 * Add start & end active period criteria in
4265 * @param string $grouping
4266 * @param array $where
4267 * = array to add where clauses to, in case you are generating a temp table.
4268 * not the main query.
4270 public function addRelationshipActivePeriodClauses($grouping, &$where) {
4271 $dateValues = array();
4272 $dateField = 'active_period_date';
4274 $dateValueLow = $this->getWhereValues('relation_active_period_date_low', $grouping);
4275 $dateValueHigh = $this->getWhereValues('relation_active_period_date_high', $grouping);
4276 $dateValueLowFormated = $dateValueHighFormated = NULL;
4277 if (!empty($dateValueLow) && !empty($dateValueHigh)) {
4278 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4279 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4280 $this->_qill
[$grouping][] = (ts('Relationship was active between')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated) . " and " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4282 elseif (!empty($dateValueLow)) {
4283 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4284 $this->_qill
[$grouping][] = (ts('Relationship was active after')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated);
4286 elseif (!empty($dateValueHigh)) {
4287 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4288 $this->_qill
[$grouping][] = (ts('Relationship was active before')) . " " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4291 if ($activePeriodClauses = self
::getRelationshipActivePeriodClauses($dateValueLowFormated, $dateValueHighFormated, TRUE)) {
4292 $where[$grouping][] = $activePeriodClauses;
4297 * Get start & end active period criteria
4299 public static function getRelationshipActivePeriodClauses($from, $to, $forceTableName) {
4300 $tableName = $forceTableName ?
'civicrm_relationship.' : '';
4301 if (!is_null($from) && !is_null($to)) {
4302 return '(((' . $tableName . 'start_date >= ' . $from . ' AND ' . $tableName . 'start_date <= ' . $to . ') OR
4303 (' . $tableName . 'end_date >= ' . $from . ' AND ' . $tableName . 'end_date <= ' . $to . ') OR
4304 (' . $tableName . 'start_date <= ' . $from . ' AND ' . $tableName . 'end_date >= ' . $to . ' )) OR
4305 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4306 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . ') OR
4307 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4309 elseif (!is_null($from)) {
4310 return '((' . $tableName . 'start_date >= ' . $from . ') OR
4311 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4312 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . '))';
4314 elseif (!is_null($to)) {
4315 return '((' . $tableName . 'start_date <= ' . $to . ') OR
4316 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4317 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4322 * Default set of return properties.
4327 * derault return properties
4329 public static function &defaultReturnProperties($mode = 1) {
4330 if (!isset(self
::$_defaultReturnProperties)) {
4331 self
::$_defaultReturnProperties = array();
4334 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4335 // add activity return properties
4336 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4337 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4340 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4343 if (empty(self
::$_defaultReturnProperties[$mode])) {
4344 self
::$_defaultReturnProperties[$mode] = array(
4347 'legal_identifier' => 1,
4348 'external_identifier' => 1,
4349 'contact_type' => 1,
4350 'contact_sub_type' => 1,
4352 'display_name' => 1,
4353 'preferred_mail_format' => 1,
4360 'formal_title' => 1,
4361 'communication_style_id' => 1,
4364 'street_address' => 1,
4365 'supplemental_address_1' => 1,
4366 'supplemental_address_2' => 1,
4367 'supplemental_address_3' => 1,
4370 'postal_code_suffix' => 1,
4371 'state_province' => 1,
4373 'world_region' => 1,
4380 'household_name' => 1,
4381 'organization_name' => 1,
4382 'deceased_date' => 1,
4387 'current_employer' => 1,
4388 // FIXME: should we use defaultHierReturnProperties() for the below?
4389 'do_not_email' => 1,
4392 'do_not_phone' => 1,
4393 'do_not_trade' => 1,
4395 'contact_is_deleted' => 1,
4396 'preferred_communication_method' => 1,
4397 'preferred_language' => 1,
4401 return self
::$_defaultReturnProperties[$mode];
4405 * Get primary condition for a sql clause.
4409 * @return string|NULL
4411 public static function getPrimaryCondition($value) {
4412 if (is_numeric($value)) {
4413 $value = (int ) $value;
4414 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4420 * Wrapper for a simple search query.
4422 * @param array $params
4423 * @param array $returnProperties
4424 * @param bool $count
4428 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4429 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4430 list($select, $from, $where, $having) = $query->query();
4431 $groupBy = ($query->_useGroupBy
) ?
'GROUP BY contact_a.id' : '';
4433 $query = "$select $from $where $groupBy $having";
4438 * These are stub comments as this function needs more explanation - particularly in terms of how it
4439 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4441 * This function was originally written as a wrapper for the api query but is called from multiple places
4442 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4443 * but it is unclear as to whehter that is historical or there is a reason
4444 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4446 * @param array $params
4447 * @param array $returnProperties
4448 * @param null $fields
4449 * @param string $sort
4450 * @param int $offset
4451 * @param int $row_count
4452 * @param bool $smartGroupCache
4453 * ?? update smart group cache?.
4454 * @param bool $count
4455 * Return count obnly.
4456 * @param bool $skipPermissions
4457 * Should permissions be ignored or should the logged in user's permissions be applied.
4459 * This basically correlates to the component.
4460 * @param string $apiEntity
4461 * The api entity being called.
4462 * This sort-of duplicates $mode in a confusing way. Probably not by design.
4464 * @param bool|null $primaryLocationOnly
4467 public static function apiQuery(
4469 $returnProperties = NULL,
4474 $smartGroupCache = TRUE,
4476 $skipPermissions = TRUE,
4477 $mode = CRM_Contact_BAO_Query
::MODE_CONTACTS
,
4479 $primaryLocationOnly = NULL
4482 $query = new CRM_Contact_BAO_Query(
4483 $params, $returnProperties,
4484 NULL, TRUE, FALSE, $mode,
4486 TRUE, $smartGroupCache,
4488 $apiEntity, $primaryLocationOnly
4491 //this should add a check for view deleted if permissions are enabled
4492 if ($skipPermissions) {
4493 $query->_skipDeleteClause
= TRUE;
4495 $query->generatePermissionClause(FALSE, $count);
4497 // note : this modifies _fromClause and _simpleFromClause
4498 $query->includePseudoFieldsJoin($sort);
4500 list($select, $from, $where, $having) = $query->query($count);
4502 $options = $query->_options
;
4503 if (!empty($query->_permissionWhereClause
)) {
4504 if (empty($where)) {
4505 $where = "WHERE $query->_permissionWhereClause";
4508 $where = "$where AND $query->_permissionWhereClause";
4512 $sql = "$select $from $where $having";
4514 // add group by only when API action is not getcount
4515 // otherwise query fetches incorrect count
4516 if ($query->_useGroupBy
&& !$count) {
4517 $sql .= self
::getGroupByFromSelectColumns($query->_select
, 'contact_a.id');
4519 if (!empty($sort)) {
4520 $sort = CRM_Utils_Type
::escape($sort, 'String');
4521 $sql .= " ORDER BY $sort ";
4523 if ($row_count > 0 && $offset >= 0) {
4524 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4525 $row_count = CRM_Utils_Type
::escape($row_count, 'Int');
4526 $sql .= " LIMIT $offset, $row_count ";
4529 $dao = CRM_Core_DAO
::executeQuery($sql);
4531 // @todo derive this from the component class rather than hard-code two options.
4532 $entityIDField = ($mode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) ?
'contribution_id' : 'contact_id';
4535 while ($dao->fetch()) {
4537 $noRows = $dao->rowCount
;
4539 return array($noRows, NULL);
4541 $val = $query->store($dao);
4542 $convertedVals = $query->convertToPseudoNames($dao, TRUE, TRUE);
4544 if (!empty($convertedVals)) {
4545 $val = array_replace_recursive($val, $convertedVals);
4547 $values[$dao->$entityIDField] = $val;
4550 return array($values, $options);
4554 * Get the actual custom field name by stripping off the appended string.
4556 * The string could be _relative, _from, or _to
4558 * @todo use metadata rather than convention to do this.
4560 * @param string $parameterName
4561 * The name of the parameter submitted to the form.
4568 public static function getCustomFieldName($parameterName) {
4569 if (substr($parameterName, -5, 5) == '_from') {
4570 return substr($parameterName, 0, strpos($parameterName, '_from'));
4572 if (substr($parameterName, -9, 9) == '_relative') {
4573 return substr($parameterName, 0, strpos($parameterName, '_relative'));
4575 if (substr($parameterName, -3, 3) == '_to') {
4576 return substr($parameterName, 0, strpos($parameterName, '_to'));
4581 * Convert submitted values for relative custom fields to query object format.
4583 * The query will support the sqlOperator format so convert to that format.
4585 * @param array $formValues
4587 * @param array $params
4588 * Converted parameters for the query object.
4589 * @param string $values
4591 * @param string $fieldName
4592 * Submitted field name. (Matches form field not DB field.)
4594 protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) {
4595 if (empty($values)) {
4596 // e.g we might have relative set & from & to empty. The form flow is a bit funky &
4597 // this function gets called again after they fields have been converted which can get ugly.
4600 $customFieldName = self
::getCustomFieldName($fieldName);
4602 if (substr($fieldName, -9, 9) == '_relative') {
4603 list($from, $to) = CRM_Utils_Date
::getFromTo($values, NULL, NULL);
4606 if ($fieldName == $customFieldName . '_to' && CRM_Utils_Array
::value($customFieldName . '_from', $formValues)) {
4607 // Both to & from are set. We only need to acton one, choosing from.
4611 $from = CRM_Utils_Array
::value($customFieldName . '_from', $formValues, NULL);
4612 $to = CRM_Utils_Array
::value($customFieldName . '_to', $formValues, NULL);
4614 if (self
::isCustomDateField($customFieldName)) {
4615 list($from, $to) = CRM_Utils_Date
::getFromTo(NULL, $from, $to);
4621 $relativeFunction = array('BETWEEN' => array($from, $to));
4624 $relativeFunction = array('>=' => $from);
4628 $relativeFunction = array('<=' => $to);
4640 * Are we dealing with custom field of type date.
4646 public static function isCustomDateField($fieldName) {
4647 if (($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($fieldName)) == FALSE) {
4650 if ('Date' == civicrm_api3('CustomField', 'getvalue', array('id' => $customFieldID, 'return' => 'data_type'))) {
4657 * Has this field already been reformatting to Query object syntax.
4659 * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems
4660 * to come with associated double queries & is possibly damaging performance.
4662 * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns
4665 * @param mixed $values
4666 * Value in formValues for the field.
4670 public static function isAlreadyProcessedForQueryFormat($values) {
4671 if (!is_array($values)) {
4674 if (($operator = CRM_Utils_Array
::value(1, $values)) == FALSE) {
4677 return in_array($operator, CRM_Core_DAO
::acceptedSQLOperators());
4681 * If the state and country are passed remove state.
4683 * Country is implicit from the state, but including both results in
4684 * a poor query as there is no combined index on state AND country.
4688 * @param array $formValues
4690 public static function filterCountryFromValuesIfStateExists(&$formValues) {
4691 if (!empty($formValues['country']) && !empty($formValues['state_province'])) {
4692 // The use of array map sanitises the data by ensuring we are dealing with integers.
4693 $states = implode(', ', array_map('intval', $formValues['state_province']));
4694 $countryList = CRM_Core_DAO
::singleValueQuery(
4695 "SELECT GROUP_CONCAT(country_id) FROM civicrm_state_province WHERE id IN ($states)"
4697 if ($countryList == $formValues['country']) {
4698 unset($formValues['country']);
4704 * For some special cases, grouping by subset of select fields becomes mandatory.
4705 * Hence, full_group_by mode is handled by appending any_value
4706 * keyword to select fields not present in groupBy
4708 * @param array $selectClauses
4709 * @param array $groupBy - Columns already included in GROUP By clause.
4710 * @param string $aggregateFunction
4714 public static function appendAnyValueToSelect($selectClauses, $groupBy, $aggregateFunction = 'ANY_VALUE') {
4715 if (!CRM_Utils_SQL
::disableFullGroupByMode()) {
4716 $groupBy = array_map('trim', (array) $groupBy);
4717 $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4718 foreach ($selectClauses as $key => &$val) {
4719 list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL);
4720 // append ANY_VALUE() keyword
4721 if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) {
4722 $val = ($aggregateFunction == 'GROUP_CONCAT') ?
4723 str_replace($selectColumn, "$aggregateFunction(DISTINCT {$selectColumn})", $val) :
4724 str_replace($selectColumn, "$aggregateFunction({$selectColumn})", $val);
4729 return "SELECT " . implode(', ', $selectClauses) . " ";
4733 * For some special cases, where if non-aggregate ORDER BY columns are not present in GROUP BY
4734 * on full_group_by mode, then append the those missing columns to GROUP BY clause
4735 * keyword to select fields not present in groupBy
4737 * @param string $groupBy - GROUP BY clause where missing ORDER BY columns will be appended
4738 * @param array $orderBys - ORDER BY sub-clauses
4741 public static function getGroupByFromOrderBy(&$groupBy, $orderBys) {
4742 if (!CRM_Utils_SQL
::disableFullGroupByMode()) {
4743 foreach ($orderBys as $orderBy) {
4744 $orderBy = str_replace(array(' DESC', ' ASC', '`'), '', $orderBy); // remove sort syntax from ORDER BY clauses if present
4745 // if ORDER BY column is not present in GROUP BY then append it to end
4746 if (preg_match('/(MAX|MIN)\(/i', trim($orderBy)) !== 1 && !strstr($groupBy, $orderBy)) {
4747 $groupBy .= ", {$orderBy}";
4754 * Include Select columns in groupBy clause.
4756 * @param array $selectClauses
4757 * @param array $groupBy - Columns already included in GROUP By clause.
4761 public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NULL) {
4762 $groupBy = (array) $groupBy;
4763 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4764 $sqlMode = CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode');
4766 //return if ONLY_FULL_GROUP_BY is not enabled.
4767 if (CRM_Utils_SQL
::supportsFullGroupBy() && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
4768 $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4769 foreach ($selectClauses as $key => $val) {
4770 $aliasArray = preg_split('/ as /i', $val);
4771 // if more than 1 alias we need to split by ','.
4772 if (count($aliasArray) > 2) {
4773 $aliasArray = preg_split('/,/', $val);
4774 foreach ($aliasArray as $key => $value) {
4775 $alias = current(preg_split('/ as /i', $value));
4776 if (!in_array($alias, $groupBy) && preg_match($regexToExclude, trim($alias)) !== 1) {
4777 $groupBy[] = $alias;
4782 list($selectColumn, $alias) = array_pad($aliasArray, 2, NULL);
4783 $dateRegex = '/^(DATE_FORMAT|DATE_ADD|CASE)/i';
4784 $tableName = current(explode('.', $selectColumn));
4785 $primaryKey = "{$tableName}.id";
4786 // exclude columns which are already included in groupBy and aggregate functions from select
4787 // CRM-18439 - Also exclude the columns which are functionally dependent on columns in $groupBy (MySQL 5.7+)
4788 if (!in_array($selectColumn, $groupBy) && !in_array($primaryKey, $groupBy) && preg_match($regexToExclude, trim($selectColumn)) !== 1) {
4789 if (!empty($alias) && preg_match($dateRegex, trim($selectColumn))) {
4790 $groupBy[] = $alias;
4793 $groupBy[] = $selectColumn;
4800 if (!empty($groupBy)) {
4801 return " GROUP BY " . implode(', ', $groupBy);
4807 * Create and query the db for an contact search.
4809 * @param int $offset
4810 * The offset for the query.
4811 * @param int $rowCount
4812 * The number of rows to return.
4813 * @param string|CRM_Utils_Sort $sort
4814 * The order by string.
4815 * @param bool $count
4816 * Is this a count only query ?.
4817 * @param bool $includeContactIds
4818 * Should we include contact ids?.
4819 * @param bool $sortByChar
4820 * If true returns the distinct array of first characters for search results.
4821 * @param bool $groupContacts
4822 * If true, return only the contact ids.
4823 * @param bool $returnQuery
4824 * Should we return the query as a string.
4825 * @param string $additionalWhereClause
4826 * If the caller wants to further restrict the search (used for components).
4827 * @param null $sortOrder
4828 * @param string $additionalFromClause
4829 * Should be clause with proper joins, effective to reduce where clause load.
4831 * @param bool $skipOrderAndLimit
4833 * @return CRM_Core_DAO
4835 public function searchQuery(
4836 $offset = 0, $rowCount = 0, $sort = NULL,
4837 $count = FALSE, $includeContactIds = FALSE,
4838 $sortByChar = FALSE, $groupContacts = FALSE,
4839 $returnQuery = FALSE,
4840 $additionalWhereClause = NULL, $sortOrder = NULL,
4841 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4844 if ($includeContactIds) {
4845 $this->_includeContactIds
= TRUE;
4846 $this->_whereClause
= $this->whereClause();
4849 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4851 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4852 // and that contact happens to be deleted, set $onlyDeleted to true
4853 foreach ($this->_params
as $values) {
4854 $name = CRM_Utils_Array
::value(0, $values);
4855 $op = CRM_Utils_Array
::value(1, $values);
4856 $value = CRM_Utils_Array
::value(2, $values);
4857 if ($name == 'contact_id' and $op == '=') {
4858 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4859 $onlyDeleted = TRUE;
4865 // building the query string
4866 $groupBy = $groupByCols = NULL;
4868 if (isset($this->_groupByComponentClause
)) {
4869 $groupBy = $this->_groupByComponentClause
;
4870 $groupByCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause
));
4871 $groupByCols = explode(', ', $groupByCols);
4873 elseif ($this->_useGroupBy
) {
4874 $groupByCols = array('contact_a.id');
4877 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4878 $groupByCols = array('civicrm_activity.id');
4881 $order = $orderBy = $limit = '';
4883 list($order, $additionalFromClause) = $this->prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause);
4885 if ($rowCount > 0 && $offset >= 0) {
4886 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4887 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4888 $limit = " LIMIT $offset, $rowCount ";
4893 $this->_sort
= $sort;
4896 $this->includePseudoFieldsJoin($sort);
4898 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4900 if (!empty($groupByCols)) {
4901 $select = self
::appendAnyValueToSelect($this->_select
, $groupByCols, 'GROUP_CONCAT');
4902 $groupBy = " GROUP BY " . implode(', ', $groupByCols);
4903 if (!empty($order)) {
4904 // retrieve order by columns from ORDER BY clause
4905 $orderBys = explode(",", str_replace('ORDER BY ', '', $order));
4906 self
::getGroupByFromOrderBy($groupBy, $orderBys);
4910 if ($additionalWhereClause) {
4911 $where = $where . ' AND ' . $additionalWhereClause;
4914 //additional from clause should be w/ proper joins.
4915 if ($additionalFromClause) {
4916 $from .= "\n" . $additionalFromClause;
4919 // if we are doing a transform, do it here
4920 // use the $from, $where and $having to get the contact ID
4921 if ($this->_displayRelationshipType
) {
4922 $this->filterRelatedContacts($from, $where, $having);
4925 if ($skipOrderAndLimit) {
4926 $query = "$select $from $where $having $groupBy";
4929 $query = "$select $from $where $having $groupBy $order $limit";
4936 return CRM_Core_DAO
::singleValueQuery($query);
4939 $dao = CRM_Core_DAO
::executeQuery($query);
4940 if ($groupContacts) {
4942 while ($dao->fetch()) {
4946 return implode(',', $ids);
4953 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4955 * @param string $cacheKey
4956 * @param int $offset
4957 * @param int $rowCount
4958 * @param bool $includeContactIds
4959 * @return CRM_Core_DAO
4961 public function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4962 $this->_includeContactIds
= $includeContactIds;
4963 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4964 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
4965 $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);
4966 $order = " ORDER BY pnc.id";
4967 $groupByCol = array('contact_a.id', 'pnc.id');
4968 $select = self
::appendAnyValueToSelect($this->_select
, $groupByCol, 'GROUP_CONCAT');
4969 $groupBy = " GROUP BY " . implode(', ', $groupByCol);
4970 $limit = " LIMIT $offset, $rowCount";
4971 $query = "$select $from $where $groupBy $order $limit";
4973 return CRM_Core_DAO
::executeQuery($query);
4977 * Populate $this->_permissionWhereClause with permission related clause and update other
4978 * query related properties.
4980 * Function calls ACL permission class and hooks to filter the query appropriately
4982 * Note that these 2 params were in the code when extracted from another function
4983 * and a second round extraction would be to make them properties of the class
4985 * @param bool $onlyDeleted
4986 * Only get deleted contacts.
4987 * @param bool $count
4988 * Return Count only.
4990 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4991 if (!$this->_skipPermission
) {
4992 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4993 CRM_Core_Permission
::VIEW
,
4995 $this->_whereTables
,
4998 $this->_skipDeleteClause
5001 // regenerate fromClause since permission might have added tables
5002 if ($this->_permissionWhereClause
) {
5003 //fix for row count in qill (in contribute/membership find)
5005 $this->_useDistinct
= TRUE;
5008 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
5009 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
5010 // note : this modifies _fromClause and _simpleFromClause
5011 $this->includePseudoFieldsJoin($this->_sort
);
5015 // add delete clause if needed even if we are skipping permission
5017 if (!$this->_skipDeleteClause
) {
5018 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
5019 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
5023 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
5032 public function setSkipPermission($val) {
5033 $this->_skipPermission
= $val;
5037 * @param null $context
5041 public function &summaryContribution($context = NULL) {
5042 list($innerselect, $from, $where, $having) = $this->query(TRUE);
5046 SELECT COUNT( conts.total_amount ) as total_count,
5047 SUM( conts.total_amount ) as total_amount,
5048 AVG( conts.total_amount ) as total_avg,
5049 conts.currency as currency";
5050 if ($this->_permissionWhereClause
) {
5051 $where .= " AND " . $this->_permissionWhereClause
;
5053 if ($context == 'search') {
5054 $where .= " AND contact_a.is_deleted = 0 ";
5057 $query = $this->appendFinancialTypeWhereAndFromToQueryStrings($where, $from);
5059 // make sure contribution is completed - CRM-4989
5060 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
5063 $summary['total'] = array();
5064 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
5065 $innerQuery = "SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
5066 civicrm_contribution.currency $from $completedWhere";
5067 $query = "$select FROM (
5068 $innerQuery GROUP BY civicrm_contribution.id
5072 $dao = CRM_Core_DAO
::executeQuery($query);
5074 $summary['total']['count'] = 0;
5075 $summary['total']['amount'] = $summary['total']['avg'] = array();
5076 while ($dao->fetch()) {
5077 $summary['total']['count'] +
= $dao->total_count
;
5078 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
5079 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
5082 $orderBy = 'ORDER BY civicrm_contribution_total_amount_count DESC';
5083 $groupBy = 'GROUP BY currency, civicrm_contribution.total_amount';
5084 $modeSQL = "$select, SUBSTRING_INDEX(GROUP_CONCAT(conts.total_amount
5085 ORDER BY conts.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
5086 MAX(conts.civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count
5088 $groupBy $orderBy) as conts
5091 $summary['total']['mode'] = CRM_Contribute_BAO_Contribution
::computeStats('mode', $modeSQL);
5093 $medianSQL = "{$from} {$completedWhere}";
5094 $summary['total']['median'] = CRM_Contribute_BAO_Contribution
::computeStats('median', $medianSQL, 'civicrm_contribution');
5095 $summary['total']['currencyCount'] = count($summary['total']['median']);
5097 if (!empty($summary['total']['amount'])) {
5098 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
5099 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
5100 $summary['total']['mode'] = implode(', ', $summary['total']['mode']);
5101 $summary['total']['median'] = implode(', ', $summary['total']['median']);
5104 $summary['total']['amount'] = $summary['total']['avg'] = $summary['total']['median'] = 0;
5107 // soft credit summary
5108 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
5109 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
5112 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
5113 GROUP BY civicrm_contribution_soft.id
5116 $dao = CRM_Core_DAO
::executeQuery($query);
5117 $summary['soft_credit']['count'] = 0;
5118 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
5119 while ($dao->fetch()) {
5120 $summary['soft_credit']['count'] +
= $dao->total_count
;
5121 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
5122 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
5124 if (!empty($summary['soft_credit']['amount'])) {
5125 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
5126 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
5129 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
5134 //@todo - this could be one query using the IF in mysql - eg
5135 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
5136 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
5137 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
5138 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
5139 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
5140 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
5141 // FROM civicrm_contact contact_a
5142 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
5143 // WHERE ( ... where clause....
5144 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
5148 SELECT COUNT( conts.total_amount ) as cancel_count,
5149 SUM( conts.total_amount ) as cancel_amount,
5150 AVG( conts.total_amount ) as cancel_avg,
5151 conts.currency as currency";
5153 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
5154 if ($context == 'search') {
5155 $where .= " AND contact_a.is_deleted = 0 ";
5158 $query = "$select FROM (
5159 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
5160 GROUP BY civicrm_contribution.id
5164 $dao = CRM_Core_DAO
::executeQuery($query);
5167 if ($dao->fetch()) {
5168 $summary['cancel']['count'] = $dao->cancel_count
;
5169 $summary['cancel']['amount'] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
5170 $summary['cancel']['avg'] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
5174 $summary['cancel']['count'] = 0;
5175 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
5176 while ($dao->fetch()) {
5177 $summary['cancel']['count'] +
= $dao->cancel_count
;
5178 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
5179 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
5181 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
5182 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
5189 * Append financial ACL limits to the query from & where clauses, if applicable.
5191 * @param string $where
5192 * @param string $from
5194 public function appendFinancialTypeWhereAndFromToQueryStrings(&$where, &$from) {
5195 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
5198 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
5199 if (!empty($financialTypes)) {
5200 $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
5201 $from .= " LEFT JOIN civicrm_line_item li
5202 ON civicrm_contribution.id = li.contribution_id AND
5203 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
5206 $where .= " AND civicrm_contribution.financial_type_id IN (0)";
5211 * Getter for the qill object.
5215 public function qill() {
5216 return $this->_qill
;
5220 * Default set of return default hier return properties.
5224 public static function &defaultHierReturnProperties() {
5225 if (!isset(self
::$_defaultHierReturnProperties)) {
5226 self
::$_defaultHierReturnProperties = array(
5229 'legal_identifier' => 1,
5230 'external_identifier' => 1,
5231 'contact_type' => 1,
5232 'contact_sub_type' => 1,
5234 'display_name' => 1,
5241 'formal_title' => 1,
5242 'communication_style_id' => 1,
5243 'email_greeting' => 1,
5244 'postal_greeting' => 1,
5248 'preferred_communication_method' => 1,
5249 'do_not_phone' => 1,
5250 'do_not_email' => 1,
5253 'do_not_trade' => 1,
5254 'location' => array(
5256 'location_type' => 1,
5257 'street_address' => 1,
5259 'state_province' => 1,
5261 'postal_code_suffix' => 1,
5264 'phone-Mobile' => 1,
5277 'location_type' => 1,
5278 'street_address' => 1,
5280 'state_province' => 1,
5282 'postal_code_suffix' => 1,
5285 'phone-Mobile' => 1,
5299 return self
::$_defaultHierReturnProperties;
5303 * Build query for a date field.
5305 * @param array $values
5306 * @param string $tableName
5307 * @param string $fieldName
5308 * @param string $dbFieldName
5309 * @param string $fieldTitle
5310 * @param bool $appendTimeStamp
5311 * @param string $dateFormat
5313 public function dateQueryBuilder(
5314 &$values, $tableName, $fieldName,
5315 $dbFieldName, $fieldTitle,
5316 $appendTimeStamp = TRUE,
5317 $dateFormat = 'YmdHis'
5319 list($name, $op, $value, $grouping, $wildcard) = $values;
5321 if ($name == "{$fieldName}_low" ||
5322 $name == "{$fieldName}_high"
5324 if (isset($this->_rangeCache
[$fieldName]) ||
!$value) {
5327 $this->_rangeCache
[$fieldName] = 1;
5329 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
5331 if ($name == $fieldName . '_low') {
5333 $firstPhrase = ts('greater than or equal to');
5334 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5336 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5337 if (!empty($secondValues) && $secondValues[2]) {
5339 $secondPhrase = ts('less than or equal to');
5340 $secondValue = $secondValues[2];
5342 if ($appendTimeStamp && strlen($secondValue) == 10) {
5343 $secondValue .= ' 23:59:59';
5345 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5348 elseif ($name == $fieldName . '_high') {
5350 $firstPhrase = ts('less than or equal to');
5352 if ($appendTimeStamp && strlen($value) == 10) {
5353 $value .= ' 23:59:59';
5355 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5357 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5358 if (!empty($secondValues) && $secondValues[2]) {
5360 $secondPhrase = ts('greater than or equal to');
5361 $secondValue = $secondValues[2];
5362 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5366 if (!$appendTimeStamp) {
5367 $firstDate = substr($firstDate, 0, 8);
5369 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5372 if (!$appendTimeStamp) {
5373 $secondDate = substr($secondDate, 0, 8);
5375 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5378 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5380 $this->_where
[$grouping][] = "
5381 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5382 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5384 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5387 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5388 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5392 if ($name == $fieldName) {
5393 //In Get API, for operators other then '=' the $value is in array(op => value) format
5394 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5396 $value = $value[$op];
5399 $date = $format = NULL;
5400 if (strstr($op, 'IN')) {
5402 foreach ($value as &$date) {
5403 $date = CRM_Utils_Date
::processDate($date, NULL, FALSE, $dateFormat);
5404 if (!$appendTimeStamp) {
5405 $date = substr($date, 0, 8);
5407 $format[] = CRM_Utils_Date
::customFormat($date);
5409 $date = "('" . implode("','", $value) . "')";
5410 $format = implode(', ', $format);
5412 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5413 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5414 if (!$appendTimeStamp) {
5415 $date = substr($date, 0, 8);
5417 $format = CRM_Utils_Date
::customFormat($date);
5422 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5425 $this->_where
[$grouping][] = self
::buildClause("{$tableName}.{$dbFieldName}", $op);
5428 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5430 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
5431 $this->_qill
[$grouping][] = "$fieldTitle $op $format";
5437 * @param string $tableName
5438 * @param string $fieldName
5439 * @param string $dbFieldName
5440 * @param $fieldTitle
5441 * @param null $options
5443 public function numberRangeBuilder(
5445 $tableName, $fieldName,
5446 $dbFieldName, $fieldTitle,
5449 list($name, $op, $value, $grouping, $wildcard) = $values;
5451 if ($name == "{$fieldName}_low" ||
5452 $name == "{$fieldName}_high"
5454 if (isset($this->_rangeCache
[$fieldName])) {
5457 $this->_rangeCache
[$fieldName] = 1;
5459 $secondOP = $secondPhrase = $secondValue = NULL;
5461 if ($name == "{$fieldName}_low") {
5463 $firstPhrase = ts('greater than');
5465 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5466 if (!empty($secondValues)) {
5468 $secondPhrase = ts('less than');
5469 $secondValue = $secondValues[2];
5474 $firstPhrase = ts('less than');
5476 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5477 if (!empty($secondValues)) {
5479 $secondPhrase = ts('greater than');
5480 $secondValue = $secondValues[2];
5485 $this->_where
[$grouping][] = "
5486 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5487 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5489 $displayValue = $options ?
$options[$value] : $value;
5490 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5492 $this->_qill
[$grouping][]
5493 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5496 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5497 $displayValue = $options ?
$options[$value] : $value;
5498 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5500 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5505 if ($name == $fieldName) {
5509 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5511 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5512 $displayValue = $options ?
$options[$value] : $value;
5513 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5520 * @param string $tableName
5521 * @param string $fieldName
5522 * @param string $dbFieldName
5523 * @param $fieldTitle
5524 * @param null $options
5526 public function ageRangeQueryBuilder(
5528 $tableName, $fieldName,
5529 $dbFieldName, $fieldTitle,
5532 list($name, $op, $value, $grouping, $wildcard) = $values;
5534 $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
5535 $asofDate = NULL; // will be treated as current day
5536 if ($asofDateValues) {
5537 $asofDate = CRM_Utils_Date
::processDate($asofDateValues[2]);
5538 $asofDateFormat = CRM_Utils_Date
::customFormat(substr($asofDate, 0, 8));
5539 $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat;
5542 if ($name == "{$fieldName}_low" ||
5543 $name == "{$fieldName}_high"
5545 if (isset($this->_rangeCache
[$fieldName])) {
5548 $this->_rangeCache
[$fieldName] = 1;
5550 $secondOP = $secondPhrase = $secondValue = NULL;
5552 if ($name == "{$fieldName}_low") {
5553 $firstPhrase = ts('greater than or equal to');
5554 // NB: age > X means date of birth < Y
5556 $firstDate = self
::calcDateFromAge($asofDate, $value, 'min');
5558 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5559 if (!empty($secondValues)) {
5561 $secondPhrase = ts('less than or equal to');
5562 $secondValue = $secondValues[2];
5563 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'max');
5568 $firstPhrase = ts('less than or equal to');
5569 $firstDate = self
::calcDateFromAge($asofDate, $value, 'max');
5571 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5572 if (!empty($secondValues)) {
5574 $secondPhrase = ts('greater than or equal to');
5575 $secondValue = $secondValues[2];
5576 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'min');
5581 $this->_where
[$grouping][] = "
5582 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5583 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5585 $displayValue = $options ?
$options[$value] : $value;
5586 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5588 $this->_qill
[$grouping][]
5589 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5592 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5593 $displayValue = $options ?
$options[$value] : $value;
5594 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5596 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5602 * Calculate date from age.
5604 * @param string $asofDate
5606 * @param string $type
5610 public static function calcDateFromAge($asofDate, $age, $type) {
5611 $date = new DateTime($asofDate);
5612 if ($type == "min") {
5613 // minimum age is $age: dob <= date - age "235959"
5614 $date->sub(new DateInterval("P" . $age . "Y"));
5615 return $date->format('Ymd') . "235959";
5618 // max age is $age: dob >= date - (age + 1y) + 1d "000000"
5619 $date->sub(new DateInterval("P" . ($age +
1) . "Y"))->add(new DateInterval("P1D"));
5620 return $date->format('Ymd') . "000000";
5625 * Given the field name, operator, value & its data type
5626 * builds the where Clause for the query
5627 * used for handling 'IS NULL'/'IS NOT NULL' operators
5629 * @param string $field
5633 * @param string $value
5635 * @param string $dataType
5636 * Data type of the field.
5639 * Where clause for the query.
5641 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5643 $clause = "$field $op";
5651 $clause = " (NULLIF($field, '') IS NULL) ";
5654 case 'IS NOT EMPTY':
5655 $clause = " (NULLIF($field, '') IS NOT NULL) ";
5660 // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
5661 if (!empty($value) && (!is_array($value) ||
!array_key_exists($op, $value))) {
5662 $value = array($op => (array) $value);
5666 if (empty($dataType)) {
5667 $dataType = 'String';
5669 if (is_array($value)) {
5670 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5671 // widely used and consistent across the codebase
5672 // adding this here won't accept the search functions which don't submit an array
5673 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, $value, $dataType)) != FALSE) {
5675 return $queryString;
5678 // This is the here-be-dragons zone. We have no other hopes left for an array so lets assume it 'should' be array('IN' => array(2,5))
5679 // but we got only array(2,5) from the form.
5680 // We could get away with keeping this in 4.6 if we make it such that it throws an enotice in 4.7 so
5681 // people have to de-slopify it.
5682 if (!empty($value[0])) {
5683 if ($op != 'BETWEEN') {
5684 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReport;
5686 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => $value), $dataType)) != FALSE) {
5687 return $queryString;
5692 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReportUsingOldFormat;
5693 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => array_keys($value)), $dataType)) != FALSE) {
5694 return $queryString;
5699 $value = CRM_Utils_Type
::escape($value, $dataType);
5700 // if we don't have a dataType we should assume
5701 if ($dataType == 'String' ||
$dataType == 'Text') {
5702 $value = "'" . strtolower($value) . "'";
5704 return "$clause $value";
5709 * @param bool $reset
5713 public function openedSearchPanes($reset = FALSE) {
5714 if (!$reset ||
empty($this->_whereTables
)) {
5715 return self
::$_openedPanes;
5718 // pane name to table mapper
5719 $panesMapper = array(
5720 ts('Contributions') => 'civicrm_contribution',
5721 ts('Memberships') => 'civicrm_membership',
5722 ts('Events') => 'civicrm_participant',
5723 ts('Relationships') => 'civicrm_relationship',
5724 ts('Activities') => 'civicrm_activity',
5725 ts('Pledges') => 'civicrm_pledge',
5726 ts('Cases') => 'civicrm_case',
5727 ts('Grants') => 'civicrm_grant',
5728 ts('Address Fields') => 'civicrm_address',
5729 ts('Notes') => 'civicrm_note',
5730 ts('Change Log') => 'civicrm_log',
5731 ts('Mailings') => 'civicrm_mailing',
5733 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5735 foreach (array_keys($this->_whereTables
) as $table) {
5736 if ($panName = array_search($table, $panesMapper)) {
5737 self
::$_openedPanes[$panName] = TRUE;
5741 return self
::$_openedPanes;
5747 public function setOperator($operator) {
5748 $validOperators = array('AND', 'OR');
5749 if (!in_array($operator, $validOperators)) {
5752 $this->_operator
= $operator;
5758 public function getOperator() {
5759 return $this->_operator
;
5767 public function filterRelatedContacts(&$from, &$where, &$having) {
5768 static $_rTypeProcessed = NULL;
5769 static $_rTypeFrom = NULL;
5770 static $_rTypeWhere = NULL;
5772 if (!$_rTypeProcessed) {
5773 $_rTypeProcessed = TRUE;
5775 // create temp table with contact ids
5776 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5777 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5778 CRM_Core_DAO
::executeQuery($sql);
5781 REPLACE INTO $tableName ( contact_id )
5787 CRM_Core_DAO
::executeQuery($sql);
5789 $qillMessage = ts('Contacts with a Relationship Type of: ');
5790 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5792 if (is_numeric($this->_displayRelationshipType
)) {
5793 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5795 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5796 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5799 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5800 AND displayRelType.is_active = 1
5804 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5805 if ($dirOne == 'a') {
5806 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5808 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5809 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5813 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5815 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5816 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5820 WHERE displayRelType.relationship_type_id = $relType
5821 AND displayRelType.is_active = 1
5824 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5827 if (!empty($this->_permissionWhereClause
)) {
5828 $_rTypeWhere .= "AND $this->_permissionWhereClause";
5831 if (strpos($from, $_rTypeFrom) === FALSE) {
5832 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5833 // this happens when we have an event_type in the quert (CRM-7969)
5834 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5835 $from .= $_rTypeFrom;
5836 $where = $_rTypeWhere;
5843 * See CRM-19811 for why this is database hurty without apparent benefit.
5849 public static function caseImportant($op) {
5851 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5855 * @param $returnProperties
5860 public static function componentPresent(&$returnProperties, $prefix) {
5861 foreach ($returnProperties as $name => $dontCare) {
5862 if (substr($name, 0, strlen($prefix)) == $prefix) {
5870 * Builds the necessary structures for all fields that are similar to option value look-ups.
5872 * @param string $name
5873 * the name of the field.
5875 * the sql operator, this function should handle ALL SQL operators.
5876 * @param string $value
5877 * depends on the operator and who's calling the query builder.
5878 * @param int $grouping
5879 * the index where to place the where clause.
5880 * @param string $daoName
5882 * @param array $field
5883 * an array that contains various properties of the field identified by $name.
5884 * @param string $label
5885 * The label for this field element.
5886 * @param string $dataType
5887 * The data type for this element.
5888 * @param bool $useIDsOnly
5890 public function optionValueQuery(
5898 $dataType = 'String',
5902 $pseudoFields = array(
5909 'communication_style_id',
5913 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5914 if ($tableName == 'civicrm_contact') {
5915 $wc = "contact_a.$fieldName";
5918 $wc = "$tableName.id";
5922 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
5923 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5925 if (in_array($name, $pseudoFields)) {
5926 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5927 $wc = "contact_a.{$name}_id";
5929 $dataType = 'Positive';
5930 $value = (!$value) ?
0 : $value;
5932 if ($name == "world_region") {
5933 $field['name'] = $name;
5936 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue($daoName, $field['name'], $value, $op);
5937 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillop, 3 => $qillVal));
5938 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5942 * Check and explode a user defined numeric string into an array
5943 * this was the protocol used by search builder in the old old days before we had
5944 * super nice js widgets to do the hard work
5946 * @param string $string
5947 * @param string $dataType
5948 * The dataType we should check for the values, default integer.
5950 * @return bool|array
5951 * false if string does not match the pattern
5952 * array of numeric values if string does match the pattern
5954 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5955 $string = trim($string);
5956 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5960 $string = substr($string, 1, -1);
5961 $values = explode(',', $string);
5962 if (empty($values)) {
5966 $returnValues = array();
5967 foreach ($values as $v) {
5968 if ($dataType == 'Integer' && !is_numeric($v)) {
5971 elseif ($dataType == 'String' && !is_string($v)) {
5974 $returnValues[] = trim($v);
5977 if (empty($returnValues)) {
5981 return $returnValues;
5985 * Convert the pseudo constants id's to their names
5987 * @param CRM_Core_DAO $dao
5988 * @param bool $return
5989 * @param bool $usedForAPI
5991 * @return array|NULL
5993 public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) {
5994 if (empty($this->_pseudoConstantsSelect
)) {
5998 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5999 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
6003 if (is_object($dao) && property_exists($dao, $value['idCol'])) {
6004 $val = $dao->{$value['idCol']};
6005 if ($key == 'groups') {
6006 $dao->groups
= $this->convertGroupIDStringToLabelString($dao, $val);
6010 if (CRM_Utils_System
::isNull($val)) {
6013 elseif (!empty($value['pseudoconstant'])) {
6014 // If pseudoconstant is set that is kind of defacto for 'we have a bit more info about this'
6015 // and we can use the metadata to figure it out.
6016 // ideally this bit of IF will absorb & replace all the rest in time as we move to
6017 // more metadata based choices.
6018 if (strpos($val, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
6019 $dbValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($val, CRM_Core_DAO
::VALUE_SEPARATOR
));
6020 foreach ($dbValues as $pseudoValue) {
6021 $convertedValues[] = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $pseudoValue);
6024 $dao->$key = ($usedForAPI) ?
$convertedValues : implode(', ', $convertedValues);
6025 $realFieldName = CRM_Utils_Array
::value('field_name', $this->_pseudoConstantsSelect
[$key]);
6026 if ($usedForAPI && $realFieldName) {
6027 // normally we would see 2 fields returned for pseudoConstants. An exception is
6028 // preferred_communication_method where there is no id-variant.
6029 // For the api we prioritise getting the real data returned.
6030 // over the resolved version
6031 $dao->$realFieldName = $dbValues;
6036 // This is basically the same as the default but since we have the bao we can use
6037 // a cached function.
6038 $dao->$key = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $val);
6041 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
6043 $idColumn = "{$key}_id";
6044 $dao->$idColumn = $val;
6046 if ($key == 'state_province_name') {
6047 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::stateProvince($val);
6050 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
6053 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
6054 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
6056 // @todo handle this in the section above for pseudoconstants.
6057 elseif (in_array($value['pseudoField'], array('participant_role_id', 'participant_role'))) {
6058 // @todo define bao on this & merge into the above condition.
6059 $viewValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val);
6061 if ($value['pseudoField'] == 'participant_role') {
6062 $pseudoOptions = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'role_id');
6063 foreach ($viewValues as $k => $v) {
6064 $viewValues[$k] = $pseudoOptions[$v];
6067 $dao->$key = ($usedForAPI && count($viewValues) > 1) ?
$viewValues : implode(', ', $viewValues);
6070 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
6071 $dao->$key = $labels[$val];
6074 // return converted values in array format
6076 if (strpos($key, '-') !== FALSE) {
6077 $keyVal = explode('-', $key);
6078 $current = &$values;
6079 $lastElement = array_pop($keyVal);
6080 foreach ($keyVal as $v) {
6081 if (!array_key_exists($v, $current)) {
6082 $current[$v] = array();
6084 $current = &$current[$v];
6086 $current[$lastElement] = $dao->$key;
6089 $values[$key] = $dao->$key;
6096 'gender_id' => 'gender',
6097 'prefix_id' => 'individual_prefix',
6098 'suffix_id' => 'individual_suffix',
6099 'communication_style_id' => 'communication_style',
6100 ) as $realField => $labelField) {
6101 // This is a temporary routine for handling these fields while
6102 // we figure out how to handled them based on metadata in
6103 /// export and search builder. CRM-19815, CRM-19830.
6104 if (isset($dao->$realField) && is_numeric($dao->$realField) && isset($dao->$labelField)) {
6105 $dao->$realField = $dao->$labelField;
6113 * Include pseudo fields LEFT JOIN.
6114 * @param string|array $sort can be a object or string
6116 * @return array|NULL
6118 public function includePseudoFieldsJoin($sort) {
6119 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
6122 $sort = is_string($sort) ?
$sort : $sort->orderBy();
6125 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
6126 if (!empty($value['table'])) {
6127 $regex = "/({$value['table']}\.|{$name})/";
6128 if (preg_match($regex, $sort)) {
6129 $this->_elemnt
[$value['element']] = 1;
6130 $this->_select
[$value['element']] = $value['select'];
6131 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
6132 $present[$value['table']] = $value['join'];
6136 $presentSimpleFrom = $present;
6138 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
6139 array_key_exists('civicrm_country', $presentSimpleFrom)
6141 unset($presentSimpleFrom['civicrm_country']);
6143 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
6144 array_key_exists('civicrm_country', $present)
6146 unset($present['civicrm_country']);
6149 $presentClause = $presentSimpleFromClause = NULL;
6150 if (!empty($present)) {
6151 $presentClause = implode(' ', $present);
6153 if (!empty($presentSimpleFrom)) {
6154 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
6157 $this->_fromClause
= $this->_fromClause
. $presentClause;
6158 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
6160 return array($presentClause, $presentSimpleFromClause);
6164 * Build qill for field.
6166 * Qill refers to the query detail visible on the UI.
6168 * @param string $daoName
6169 * @param string $fieldName
6170 * @param mixed $fieldValue
6172 * @param array $pseudoExtraParam
6174 * Type of the field per CRM_Utils_Type
6178 public static function buildQillForFieldValue(
6183 $pseudoExtraParam = array(),
6184 $type = CRM_Utils_Type
::T_STRING
6186 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
6188 //API usually have fieldValue format as array(operator => array(values)),
6189 //so we need to separate operator out of fieldValue param
6190 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
6191 $op = key($fieldValue);
6192 $fieldValue = $fieldValue[$op];
6195 // if Operator chosen is NULL/EMPTY then
6196 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
6197 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), '');
6200 if ($fieldName == 'activity_type_id') {
6201 $pseudoOptions = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
6203 elseif ($fieldName == 'country_id') {
6204 $pseudoOptions = CRM_Core_PseudoConstant
::country();
6206 elseif ($fieldName == 'county_id') {
6207 $pseudoOptions = CRM_Core_PseudoConstant
::county();
6209 elseif ($fieldName == 'world_region') {
6210 $pseudoOptions = CRM_Core_PseudoConstant
::worldRegion();
6212 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
6213 $checkPermission = CRM_Utils_Array
::value('check_permission', $pseudoExtraParam, TRUE);
6214 $pseudoOptions = CRM_Event_BAO_Event
::getEvents(0, $fieldValue, TRUE, $checkPermission, TRUE);
6216 elseif ($fieldName == 'contribution_product_id') {
6217 $pseudoOptions = CRM_Contribute_PseudoConstant
::products();
6219 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
6220 $pseudoOptions = CRM_Core_PseudoConstant
::group();
6222 elseif ($daoName == 'CRM_Batch_BAO_EntityBatch' && $fieldName == 'batch_id') {
6223 $pseudoOptions = CRM_Contribute_PseudoConstant
::batch();
6226 $pseudoOptions = CRM_Core_PseudoConstant
::get($daoName, $fieldName, $pseudoExtraParam);
6229 if (is_array($fieldValue)) {
6230 $qillString = array();
6231 if (!empty($pseudoOptions)) {
6232 foreach ((array) $fieldValue as $val) {
6233 $qillString[] = CRM_Utils_Array
::value($val, $pseudoOptions, $val);
6235 $fieldValue = implode(', ', $qillString);
6238 if ($type == CRM_Utils_Type
::T_DATE
) {
6239 foreach ($fieldValue as $index => $value) {
6240 $fieldValue[$index] = CRM_Utils_Date
::customFormat($value);
6244 // @todo - this is a bit specific (one operator).
6245 // However it is covered by a unit test so can be altered later with
6247 if ($op == 'BETWEEN') {
6248 $separator = ' AND ';
6250 $fieldValue = implode($separator, $fieldValue);
6253 elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) {
6254 $fieldValue = $pseudoOptions[$fieldValue];
6256 elseif ($type === CRM_Utils_Type
::T_DATE
) {
6257 $fieldValue = CRM_Utils_Date
::customFormat($fieldValue);
6260 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), $fieldValue);
6264 * Alter value to reflect wildcard settings.
6266 * The form will have tried to guess whether this is a good field to wildcard but there is
6267 * also a site-wide setting that specifies whether it is OK to append the wild card to the beginning
6268 * or only the end of the string
6270 * @param bool $wildcard
6271 * This is a bool made on an assessment 'elsewhere' on whether this is a good field to wildcard.
6273 * Generally '=' or 'LIKE'.
6274 * @param string $value
6275 * The search string.
6279 public static function getWildCardedValue($wildcard, $op, $value) {
6280 if ($wildcard && $op == 'LIKE') {
6281 if (CRM_Core_Config
::singleton()->includeWildCardInName
&& (substr($value, 0, 1) != '%')) {
6294 * Process special fields of Search Form in OK (Operator in Key) format
6296 * @param array $formValues
6297 * @param array $specialFields
6298 * Special params to be processed
6299 * @param array $changeNames
6300 * Array of fields whose name should be changed
6302 public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = array()) {
6303 // Array of special fields whose value are considered only for NULL or EMPTY operators
6304 $nullableFields = array('contribution_batch_id');
6306 foreach ($specialFields as $element) {
6307 $value = CRM_Utils_Array
::value($element, $formValues);
6309 if (is_array($value)) {
6310 if (in_array($element, array_keys($changeNames))) {
6311 unset($formValues[$element]);
6312 $element = $changeNames[$element];
6314 $formValues[$element] = array('IN' => $value);
6316 elseif (in_array($value, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
6317 $formValues[$element] = array($value => 1);
6319 elseif (!in_array($element, $nullableFields)) {
6320 // if wildcard is already present return searchString as it is OR append and/or prepend with wildcard
6321 $isWilcard = strstr($value, '%') ?
FALSE : CRM_Core_Config
::singleton()->includeWildCardInName
;
6322 $formValues[$element] = array('LIKE' => self
::getWildCardedValue($isWilcard, 'LIKE', $value));
6329 * Parse and assimilate the various sort options.
6331 * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`,
6332 * `email`), the related table may be joined automatically.
6334 * At time of writing, this code is deeply flawed and should be rewritten. For the moment,
6335 * it's been extracted to a standalone function.
6337 * @param string|CRM_Utils_Sort $sort
6338 * The order by string.
6339 * @param bool $sortByChar
6340 * If true returns the distinct array of first characters for search results.
6341 * @param null $sortOrder
6342 * Who knows? Hu knows. He who knows Hu knows who.
6343 * @param string $additionalFromClause
6344 * Should be clause with proper joins, effective to reduce where clause load.
6346 * list(string $orderByClause, string $additionalFromClause).
6348 protected function prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause) {
6350 $orderByArray = array();
6351 $config = CRM_Core_Config
::singleton();
6352 if ($config->includeOrderByClause ||
6353 isset($this->_distinctComponentClause
)
6356 if (is_string($sort)) {
6360 $orderBy = trim($sort->orderBy());
6362 // Deliberately remove the backticks again, as they mess up the evil
6363 // string munging below. This balanced by re-escaping before use.
6364 $orderBy = str_replace('`', '', $orderBy);
6366 if (!empty($orderBy)) {
6367 // this is special case while searching for
6368 // change log CRM-1718
6369 if (preg_match('/sort_name/i', $orderBy)) {
6370 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
6373 $order = " ORDER BY $orderBy";
6376 $order .= " $sortOrder";
6379 // always add contact_a.id to the ORDER clause
6380 // so the order is deterministic
6381 if (strpos('contact_a.id', $order) === FALSE) {
6382 $order .= ", contact_a.id";
6386 elseif ($sortByChar) {
6387 $orderByArray = array("UPPER(LEFT(contact_a.sort_name, 1)) asc");
6390 $order = " ORDER BY contact_a.sort_name ASC, contact_a.id";
6393 if (!$order && empty($orderByArray)) {
6394 return array($order, $additionalFromClause);
6396 // Remove this here & add it at the end for simplicity.
6397 $order = trim(str_replace('ORDER BY', '', $order));
6399 // hack for order clause
6400 if (!empty($orderByArray)) {
6401 $order = implode(', ', $orderByArray);
6404 $orderByArray = explode(',', $order);
6406 foreach ($orderByArray as $orderByClause) {
6407 $orderByClauseParts = explode(' ', trim($orderByClause));
6408 $field = $orderByClauseParts[0];
6409 $direction = isset($orderByClauseParts[1]) ?
$orderByClauseParts[1] : 'asc';
6414 $this->_tables
["civicrm_address"] = $this->_whereTables
["civicrm_address"] = 1;
6415 $order = str_replace($field, "civicrm_address.{$field}", $order);
6419 case 'state_province':
6420 $this->_tables
["civicrm_{$field}"] = $this->_whereTables
["civicrm_{$field}"] = 1;
6421 if (is_array($this->_returnProperties
) && empty($this->_returnProperties
)) {
6422 $additionalFromClause .= " LEFT JOIN civicrm_{$field} ON civicrm_{$field}.id = civicrm_address.{$field}_id";
6424 $order = str_replace($field, "civicrm_{$field}.name", $order);
6428 $this->_tables
["civicrm_email"] = $this->_whereTables
["civicrm_email"] = 1;
6429 $order = str_replace($field, "civicrm_email.{$field}", $order);
6433 foreach ($this->_pseudoConstantsSelect
as $key => $pseudoConstantMetadata) {
6434 // By replacing the join to the option value table with the mysql construct
6435 // ORDER BY field('contribution_status_id', 2,1,4)
6436 // we can remove a join. In the case of the option value join it is
6437 /// a join known to cause slow queries.
6438 // @todo cover other pseudoconstant types. Limited to option group ones in the
6439 // first instance for scope reasons. They require slightly different handling as the column (label)
6440 // is not declared for them.
6441 // @todo so far only integer fields are being handled. If we add string fields we need to look at
6443 if (isset($pseudoConstantMetadata['pseudoconstant'])
6444 && isset($pseudoConstantMetadata['pseudoconstant']['optionGroupName'])
6445 && $field === CRM_Utils_Array
::value('optionGroupName', $pseudoConstantMetadata['pseudoconstant'])
6447 $sortedOptions = $pseudoConstantMetadata['bao']::buildOptions($pseudoConstantMetadata['pseudoField'], NULL, array(
6448 'orderColumn' => 'label',
6450 $order = str_replace("$field $direction", "field({$pseudoConstantMetadata['pseudoField']}," . implode(',', array_keys($sortedOptions)) . ") $direction", $order);
6452 //CRM-12565 add "`" around $field if it is a pseudo constant
6453 // This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
6454 if (!empty($pseudoConstantMetadata['element']) && $pseudoConstantMetadata['element'] == $field) {
6455 $order = str_replace($field, "`{$field}`", $order);
6461 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6462 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6464 // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
6465 // clause. But this magic helper which forgivingly reescapes ORDER BY.
6466 // Note: $sortByChar implies that $order was hard-coded/trusted, so it can do funky things.
6468 return array(' ORDER BY ' . $order, $additionalFromClause);
6471 $order = CRM_Utils_Type
::escape($order, 'MysqlOrderBy');
6472 return array(' ORDER BY ' . $order, $additionalFromClause);
6477 * Convert a string of group IDs to a string of group labels.
6479 * The original string may include duplicates and groups the user does not have
6480 * permission to see.
6482 * @param CRM_Core_DAO $dao
6483 * @param string $val
6487 public function convertGroupIDStringToLabelString(&$dao, $val) {
6488 $groupIDs = explode(',', $val);
6489 // Note that groups that the user does not have permission to will be excluded (good).
6490 $groups = array_intersect_key(CRM_Core_PseudoConstant
::group(), array_flip($groupIDs));
6491 return implode(', ', $groups);
6496 * Set the qill and where properties for a field.
6498 * This function is intended as a short-term function to encourage refactoring
6499 * & re-use - but really we should just have less special-casing.
6501 * @param string $name
6503 * @param string|array $value
6504 * @param string $grouping
6505 * @param string $field
6507 public function setQillAndWhere($name, $op, $value, $grouping, $field) {
6508 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
6509 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
6510 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(
6511 1 => $field['title'],
6518 * Has the pseudoconstant of the field been requested.
6520 * For example if the field is payment_instrument_id then it
6521 * has been requested if either payment_instrument_id or payment_instrument
6522 * have been requested. Payment_instrument is the option groun name field value.
6524 * @param array $field
6525 * @param string $fieldName
6526 * The unique name of the field - ie. the one it will be aliased to in the query.
6530 private function pseudoConstantNameIsInReturnProperties($field, $fieldName = NULL) {
6531 if (!isset($field['pseudoconstant']['optionGroupName'])) {
6535 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
6538 if (CRM_Utils_Array
::value($fieldName, $this->_returnProperties
)) {
6541 // Is this still required - the above goes off the unique name. Test with things like
6542 // communication_prefferences & prefix_id.
6543 if (CRM_Utils_Array
::value($field['name'], $this->_returnProperties
)) {
6550 * Get Select Clause.
6554 public function getSelect() {
6555 $select = "SELECT ";
6556 if (isset($this->_distinctComponentClause
)) {
6557 $select .= "{$this->_distinctComponentClause}, ";
6559 $select .= implode(', ', $this->_select
);