3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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',
61 MODE_PLEDGEBANK
= 256,
71 * The default set of return properties.
75 static $_defaultReturnProperties = NULL;
78 * The default set of hier return properties.
82 static $_defaultHierReturnProperties;
85 * The set of input params.
98 * The set of output params
102 public $_returnProperties;
112 * The name of the elements that are in the select clause
113 * used to extract the values.
120 * The tables involved in the query.
127 * The table involved in the where clause.
131 public $_whereTables;
134 * Array of WHERE clause components.
141 * The WHERE clause as a string.
145 public $_whereClause;
148 * Additional WHERE clause for permissions.
152 public $_permissionWhereClause;
162 * Additional permission from clause
166 public $_permissionFromClause;
169 * The from clause for the simple select and alphabetical
174 public $_simpleFromClause;
184 * The english language version of the query
191 * All the fields that could potentially be involved in
199 * The cache to translate the option values into labels.
206 * Are we in search mode.
210 public $_search = TRUE;
213 * Should we skip permission checking.
217 public $_skipPermission = FALSE;
220 * Should we skip adding of delete clause.
224 public $_skipDeleteClause = FALSE;
227 * Are we in strict mode (use equality over LIKE)
231 public $_strict = FALSE;
234 * What operator to use to group the clauses.
238 public $_operator = 'AND';
243 * Should we only search on primary location.
247 public $_primaryLocation = TRUE;
250 * Are contact ids part of the query.
254 public $_includeContactIds = FALSE;
257 * Should we use the smart group cache.
261 public $_smartGroupCache = TRUE;
264 * Should we display contacts with a specific relationship type.
268 public $_displayRelationshipType = NULL;
271 * Reference to the query object for custom values.
275 public $_customQuery;
278 * Should we enable the distinct clause, used if we are including
279 * more than one group
283 public $_useDistinct = FALSE;
286 * Should we just display one contact record
288 public $_useGroupBy = FALSE;
291 * The relationship type direction
302 static $_activityRole;
305 * Consider the component activity type
306 * during activity search.
310 static $_considerCompActivities;
313 * Consider with contact activities only,
314 * during activity search.
318 static $_withContactActivitiesOnly;
321 * Use distinct component clause for component searches
325 public $_distinctComponentClause;
327 public $_rowCountClause;
330 * Use groupBy component clause for component searches
334 public $_groupByComponentClause;
337 * Track open panes, useful in advance search
341 public static $_openedPanes = array();
344 * For search builder - which custom fields are location-dependent
347 public $_locationSpecificCustomFields = array();
350 * The tables which have a dependency on location and/or address
354 static $_dependencies = array(
355 'civicrm_state_province' => 1,
356 'civicrm_country' => 1,
357 'civicrm_county' => 1,
358 'civicrm_address' => 1,
359 'civicrm_location_type' => 1,
363 * List of location specific fields.
365 static $_locationSpecificFields = array(
370 'supplemental_address_1',
371 'supplemental_address_2',
372 'supplemental_address_3',
375 'postal_code_suffix',
389 * Remember if we handle either end of a number or date range
390 * so we can skip the other
392 protected $_rangeCache = array();
394 * Set to true when $this->relationship is run to avoid adding twice
397 protected $_relationshipValuesAdded = FALSE;
400 * Set to the name of the temp table if one has been created
403 static $_relationshipTempTable = NULL;
405 public $_pseudoConstantsSelect = array();
408 * Class constructor which also does all the work.
410 * @param array $params
411 * @param array $returnProperties
412 * @param array $fields
413 * @param bool $includeContactIds
414 * @param bool $strict
415 * @param bool|int $mode - mode the search is operating on
417 * @param bool $skipPermission
418 * @param bool $searchDescendentGroups
419 * @param bool $smartGroupCache
420 * @param null $displayRelationshipType
421 * @param string $operator
422 * @param string $apiEntity
424 * @return \CRM_Contact_BAO_Query
426 public function __construct(
427 $params = NULL, $returnProperties = NULL, $fields = NULL,
428 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
429 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
430 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
434 $this->_params
= &$params;
435 if ($this->_params
== NULL) {
436 $this->_params
= array();
439 if ($returnProperties === self
::NO_RETURN_PROPERTIES
) {
440 $this->_returnProperties
= array();
442 elseif (empty($returnProperties)) {
443 $this->_returnProperties
= self
::defaultReturnProperties($mode);
446 $this->_returnProperties
= &$returnProperties;
449 $this->_includeContactIds
= $includeContactIds;
450 $this->_strict
= $strict;
451 $this->_mode
= $mode;
452 $this->_skipPermission
= $skipPermission;
453 $this->_smartGroupCache
= $smartGroupCache;
454 $this->_displayRelationshipType
= $displayRelationshipType;
455 $this->setOperator($operator);
458 $this->_fields
= &$fields;
459 $this->_search
= FALSE;
460 $this->_skipPermission
= TRUE;
463 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE, FALSE, !$skipPermission);
465 $fields = CRM_Core_Component
::getQueryFields(!$this->_skipPermission
);
466 unset($fields['note']);
467 $this->_fields
= array_merge($this->_fields
, $fields);
469 // add activity fields
470 $fields = CRM_Activity_BAO_Activity
::exportableFields();
471 $this->_fields
= array_merge($this->_fields
, $fields);
473 // add any fields provided by hook implementers
474 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
475 $this->_fields
= array_merge($this->_fields
, $extFields);
478 // basically do all the work once, and then reuse it
479 $this->initialize($apiEntity);
483 * Function which actually does all the work for the constructor.
485 * @param string $apiEntity
486 * The api entity being called.
487 * This sort-of duplicates $mode in a confusing way. Probably not by design.
489 public function initialize($apiEntity = NULL) {
490 $this->_select
= array();
491 $this->_element
= array();
492 $this->_tables
= array();
493 $this->_whereTables
= array();
494 $this->_where
= array();
495 $this->_qill
= array();
496 $this->_options
= array();
497 $this->_cfIDs
= array();
498 $this->_paramLookup
= array();
499 $this->_having
= array();
501 $this->_customQuery
= NULL;
503 // reset cached static variables - CRM-5803
504 self
::$_activityRole = NULL;
505 self
::$_considerCompActivities = NULL;
506 self
::$_withContactActivitiesOnly = NULL;
508 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
509 $this->_element
['contact_id'] = 1;
510 $this->_tables
['civicrm_contact'] = 1;
512 if (!empty($this->_params
)) {
513 $this->buildParamsLookup();
516 $this->_whereTables
= $this->_tables
;
518 $this->selectClause($apiEntity);
519 $this->_whereClause
= $this->whereClause($apiEntity);
520 if (array_key_exists('civicrm_contribution', $this->_whereTables
)) {
521 $component = 'contribution';
523 if (array_key_exists('civicrm_membership', $this->_whereTables
)) {
524 $component = 'membership';
526 if (isset($component)) {
527 CRM_Financial_BAO_FinancialType
::buildPermissionedClause($this->_whereClause
, $component);
530 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
, $apiEntity);
531 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
533 $this->openedSearchPanes(TRUE);
537 * Function for same purpose as convertFormValues.
539 * Like convert form values this function exists to pre-Process parameters from the form.
541 * It is unclear why they are different functions & likely relates to advances search
542 * versus search builder.
544 * The direction we are going is having the form convert values to a standardised format &
545 * moving away from weird & wonderful where clause switches.
547 * Fix and handle contact deletion nicely.
549 * this code is primarily for search builder use case where different clauses can specify if they want deleted.
553 public function buildParamsLookup() {
554 $trashParamExists = FALSE;
555 $paramByGroup = array();
556 foreach ($this->_params
as $k => $param) {
557 if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
558 $trashParamExists = TRUE;
560 if (!empty($param[3])) {
561 $paramByGroup[$param[3]][$k] = $param;
565 if ($trashParamExists) {
566 $this->_skipDeleteClause
= TRUE;
568 //cycle through group sets and explicitly add trash param if not set
569 foreach ($paramByGroup as $setID => $set) {
571 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params
) &&
572 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params
)
574 $this->_params
[] = array(
575 'contact_is_deleted',
585 foreach ($this->_params
as $value) {
586 if (empty($value[0])) {
589 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
591 if (!array_key_exists($cfID, $this->_cfIDs
)) {
592 $this->_cfIDs
[$cfID] = array();
594 // Set wildcard value based on "and/or" selection
595 foreach ($this->_params
as $key => $param) {
596 if ($param[0] == $value[0] . '_operator') {
597 $value[4] = $param[2] == 'or';
601 $this->_cfIDs
[$cfID][] = $value;
604 if (!array_key_exists($value[0], $this->_paramLookup
)) {
605 $this->_paramLookup
[$value[0]] = array();
607 if ($value[0] !== 'group') {
608 // Just trying to unravel how group interacts here! This whole function is weird.
609 $this->_paramLookup
[$value[0]][] = $value;
615 * Some composite fields do not appear in the fields array hack to make them part of the query.
618 * The api entity being called.
619 * This sort-of duplicates $mode in a confusing way. Probably not by design.
621 public function addSpecialFields($apiEntity) {
622 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
623 // if get called via Contact.get API having address_id as return parameter
624 if ($apiEntity == 'Contact') {
625 $special[] = 'address_id';
627 foreach ($special as $name) {
628 if (!empty($this->_returnProperties
[$name])) {
629 if ($name == 'address_id') {
630 $this->_tables
['civicrm_address'] = 1;
631 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
632 $this->_element
['address_id'] = 1;
635 $this->_select
[$name] = "contact_a.{$name} as $name";
636 $this->_element
[$name] = 1;
643 * Given a list of conditions in params and a list of desired
644 * return Properties generate the required select and from
645 * clauses. Note that since the where clause introduces new
646 * tables, the initial attempt also retrieves all variables used
649 * @param string $apiEntity
650 * The api entity being called.
651 * This sort-of duplicates $mode in a confusing way. Probably not by design.
653 public function selectClause($apiEntity = NULL) {
655 // @todo Tidy up this. This arises because 1) we are ignoring the $mode & adding a new
656 // param ($apiEntity) instead - presumably an oversight & 2 because
657 // contact is not implemented as a component.
658 $this->addSpecialFields($apiEntity);
660 foreach ($this->_fields
as $name => $field) {
661 // skip component fields
662 // there are done by the alter query below
663 // and need not be done on every field
664 // @todo remove these & handle using metadata - only obscure fields
665 // that are hack-added should need to be excluded from the main loop.
667 (substr($name, 0, 12) == 'participant_') ||
668 (substr($name, 0, 7) == 'pledge_') ||
669 (substr($name, 0, 5) == 'case_')
674 // redirect to activity select clause
676 (substr($name, 0, 9) == 'activity_') ||
677 ($name == 'parent_id')
679 CRM_Activity_BAO_Query
::select($this);
682 // if this is a hierarchical name, we ignore it
683 $names = explode('-', $name);
684 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
688 // make an exception for special cases, to add the field in select clause
689 $makeException = FALSE;
691 //special handling for groups/tags
692 if (in_array($name, array('groups', 'tags', 'notes'))
693 && isset($this->_returnProperties
[substr($name, 0, -1)])
695 // @todo instead of setting make exception to get us into
696 // an if clause that has handling for these fields buried with in it
697 // move the handling to here.
698 $makeException = TRUE;
701 // since note has 3 different options we need special handling
702 // note / note_subject / note_body
703 if ($name == 'notes') {
704 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
705 if (isset($this->_returnProperties
[$noteField])) {
706 $makeException = TRUE;
712 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
714 !empty($this->_paramLookup
[$name])
715 ||
!empty($this->_returnProperties
[$name])
716 ||
$this->pseudoConstantNameIsInReturnProperties($field)
720 // add to cfIDs array if not present
721 if (!array_key_exists($cfID, $this->_cfIDs
)) {
722 $this->_cfIDs
[$cfID] = array();
725 elseif (isset($field['where'])) {
726 list($tableName, $fieldName) = explode('.', $field['where'], 2);
727 if (isset($tableName)) {
728 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
729 $this->_tables
['civicrm_address'] = 1;
730 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
731 $this->_element
['address_id'] = 1;
734 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
735 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
737 if ($tableName == 'im_provider') {
738 CRM_Core_OptionValue
::select($this);
741 if (in_array($tableName,
742 array('email_greeting', 'postal_greeting', 'addressee'))) {
743 $this->_element
["{$name}_id"] = 1;
744 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
745 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
746 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
747 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
749 if ($tableName == 'email_greeting') {
751 $this->_pseudoConstantsSelect
[$name]['join']
752 = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
753 $this->_pseudoConstantsSelect
[$name]['join'] .=
754 " 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 ) ";
756 elseif ($tableName == 'postal_greeting') {
758 $this->_pseudoConstantsSelect
[$name]['join']
759 = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
760 $this->_pseudoConstantsSelect
[$name]['join'] .=
761 " 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 ) ";
763 elseif ($tableName == 'addressee') {
765 $this->_pseudoConstantsSelect
[$name]['join']
766 = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
767 $this->_pseudoConstantsSelect
[$name]['join'] .=
768 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
770 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
773 $greetField = "{$name}_display";
774 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
775 $this->_element
[$greetField] = 1;
777 $greetField = "{$name}_custom";
778 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
779 $this->_element
[$greetField] = 1;
783 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
784 $this->_tables
[$tableName] = 1;
787 // also get the id of the tableName
788 $tName = substr($tableName, 8);
789 if (in_array($tName, array('country', 'state_province', 'county'))) {
790 if ($tName == 'state_province') {
791 $this->_pseudoConstantsSelect
['state_province_name'] = array(
792 'pseudoField' => "{$tName}",
793 'idCol' => "{$tName}_id",
794 'bao' => 'CRM_Core_BAO_Address',
795 'table' => "civicrm_{$tName}",
796 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
799 $this->_pseudoConstantsSelect
[$tName] = array(
800 'pseudoField' => 'state_province_abbreviation',
801 'idCol' => "{$tName}_id",
802 'table' => "civicrm_{$tName}",
803 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
807 $this->_pseudoConstantsSelect
[$name] = array(
808 'pseudoField' => "{$tName}_id",
809 'idCol' => "{$tName}_id",
810 'bao' => 'CRM_Core_BAO_Address',
811 'table' => "civicrm_{$tName}",
812 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
816 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
817 $this->_element
["{$tName}_id"] = 1;
819 elseif ($tName != 'contact') {
820 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
821 $this->_element
["{$tName}_id"] = 1;
824 //special case for phone
825 if ($name == 'phone') {
826 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
827 $this->_element
['phone_type_id'] = 1;
830 // if IM then select provider_id also
831 // to get "IM Service Provider" in a file to be exported, CRM-3140
833 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
834 $this->_element
['provider_id'] = 1;
837 if ($tName == 'contact' && $fieldName == 'organization_name') {
838 // special case, when current employer is set for Individual contact
839 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
841 elseif ($tName == 'contact' && $fieldName === 'id') {
842 // Handled elsewhere, explicitly ignore. Possibly for all tables...
844 elseif (in_array($tName, array('country', 'county'))) {
845 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
846 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
848 elseif ($tName == 'state_province') {
849 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
850 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
852 elseif (strpos($name, 'contribution_soft_credit') !== FALSE) {
853 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled($this->_params
)) {
854 $this->_select
[$name] = "{$field['where']} as `$name`";
858 // If we have an option group defined then rather than joining the option value table in
859 // (which is an unindexed join) we render the option value on output.
860 // @todo - extend this to other pseudoconstants.
861 if ($this->pseudoConstantNameIsInReturnProperties($field, $name)) {
862 $pseudoFieldName = $field['pseudoconstant']['optionGroupName'];
863 $this->_pseudoConstantsSelect
[$pseudoFieldName] = array(
864 'pseudoField' => $field['name'],
866 'field_name' => $field['name'],
867 'bao' => $field['bao'],
868 'pseudoconstant' => $field['pseudoconstant'],
870 $this->_tables
[$tableName] = 1;
871 $this->_element
[$pseudoFieldName] = 1;
873 $this->_select
[$name] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$name`");
875 if (!in_array($tName, array('state_province', 'country', 'county'))) {
876 $this->_element
[$name] = 1;
881 elseif ($name === 'tags') {
882 //@todo move this handling outside the big IF & ditch $makeException
883 $this->_useGroupBy
= TRUE;
884 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
885 $this->_element
[$name] = 1;
886 $this->_tables
['civicrm_tag'] = 1;
887 $this->_tables
['civicrm_entity_tag'] = 1;
889 elseif ($name === 'groups') {
890 //@todo move this handling outside the big IF & ditch $makeException
891 $this->_useGroupBy
= TRUE;
892 // Duplicates will be created here but better to sort them out in php land.
893 $this->_select
[$name] = "
895 GROUP_CONCAT(DISTINCT IF(civicrm_group_contact.status = 'Added', civicrm_group_contact.group_id, '')),
896 GROUP_CONCAT(DISTINCT civicrm_group_contact_cache.group_id)
899 $this->_element
[$name] = 1;
900 $this->_tables
['civicrm_group_contact'] = 1;
901 $this->_tables
['civicrm_group_contact_cache'] = 1;
902 $this->_pseudoConstantsSelect
["{$name}"] = array(
903 'pseudoField' => "groups",
907 elseif ($name === 'notes') {
908 //@todo move this handling outside the big IF & ditch $makeException
909 // if note field is subject then return subject else body of the note
910 $noteColumn = 'note';
911 if (isset($noteField) && $noteField == 'note_subject') {
912 $noteColumn = 'subject';
915 $this->_useGroupBy
= TRUE;
916 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
917 $this->_element
[$name] = 1;
918 $this->_tables
['civicrm_note'] = 1;
920 elseif ($name === 'current_employer') {
921 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
922 $this->_element
[$name] = 1;
926 if ($cfID && !empty($field['is_search_range'])) {
927 // this is a custom field with range search enabled, so we better check for two/from values
928 if (!empty($this->_paramLookup
[$name . '_from'])) {
929 if (!array_key_exists($cfID, $this->_cfIDs
)) {
930 $this->_cfIDs
[$cfID] = array();
932 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
933 // search in the cdID array for the same grouping
935 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
936 if ($c[3] == $p[3]) {
937 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
942 $p[2] = array('from' => $p[2]);
943 $this->_cfIDs
[$cfID][] = $p;
947 if (!empty($this->_paramLookup
[$name . '_to'])) {
948 if (!array_key_exists($cfID, $this->_cfIDs
)) {
949 $this->_cfIDs
[$cfID] = array();
951 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
952 // search in the cdID array for the same grouping
954 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
955 if ($c[4] == $p[4]) {
956 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
961 $p[2] = array('to' => $p[2]);
962 $this->_cfIDs
[$cfID][] = $p;
969 // add location as hierarchical elements
970 $this->addHierarchicalElements();
972 // add multiple field like website
973 $this->addMultipleElements();
976 CRM_Core_Component
::alterQuery($this, 'select');
978 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
980 if (!empty($this->_cfIDs
)) {
981 // @todo This function is the select function but instead of running 'select' it
982 // is running the whole query.
983 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
984 $this->_customQuery
->query();
985 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
986 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
987 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
988 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
989 $this->_options
= $this->_customQuery
->_options
;
994 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
996 public function addHierarchicalElements() {
997 if (empty($this->_returnProperties
['location'])) {
1000 if (!is_array($this->_returnProperties
['location'])) {
1004 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1005 $processed = array();
1008 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
1009 $addressCustomFieldIds = array();
1011 foreach ($this->_returnProperties
['location'] as $name => $elements) {
1012 $lCond = self
::getPrimaryCondition($name);
1015 $locationTypeId = array_search($name, $locationTypes);
1016 if ($locationTypeId === FALSE) {
1019 $lCond = "location_type_id = $locationTypeId";
1020 $this->_useDistinct
= TRUE;
1022 //commented for CRM-3256
1023 $this->_useGroupBy
= TRUE;
1026 $name = str_replace(' ', '_', $name);
1028 $tName = "$name-location_type";
1029 $ltName = "`$name-location_type`";
1030 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1031 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
1032 $this->_element
["{$tName}_id"] = 1;
1033 $this->_element
["{$tName}"] = 1;
1035 $locationTypeName = $tName;
1036 $locationTypeJoin = array();
1038 $addAddress = FALSE;
1040 foreach ($elements as $elementFullName => $dontCare) {
1042 $elementName = $elementCmpName = $elementFullName;
1044 if (substr($elementCmpName, 0, 5) == 'phone') {
1045 $elementCmpName = 'phone';
1048 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
1049 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
1050 $addressCustomFieldIds[$cfID][$name] = 1;
1053 //add address table only once
1054 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
1056 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
1058 $tName = "$name-address";
1059 $aName = "`$name-address`";
1060 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1061 $this->_element
["{$tName}_id"] = 1;
1062 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
1063 $this->_tables
[$tName] = $addressJoin;
1064 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1065 $processed[$aName] = 1;
1069 $cond = $elementType = '';
1070 if (strpos($elementName, '-') !== FALSE) {
1071 // this is either phone, email or IM
1072 list($elementName, $elementType) = explode('-', $elementName);
1074 if (($elementName != 'phone') && ($elementName != 'im')) {
1075 $cond = self
::getPrimaryCondition($elementType);
1077 // CRM-13011 : If location type is primary, do not restrict search to the phone
1078 // type id - we want the primary phone, regardless of what type it is.
1079 // Otherwise, restrict to the specified phone type for the given field.
1080 if ((!$cond) && ($elementName == 'phone')) {
1081 $cond = "phone_type_id = '$elementType'";
1083 elseif ((!$cond) && ($elementName == 'im')) {
1084 // IM service provider id, CRM-3140
1085 $cond = "provider_id = '$elementType'";
1087 $elementType = '-' . $elementType;
1090 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
1092 // hack for profile, add location id
1095 // fix for CRM-882( to handle phone types )
1096 !is_numeric($elementType)
1098 if (is_numeric($name)) {
1099 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1102 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1105 elseif (is_numeric($name)) {
1106 //this for phone type to work
1107 if (in_array($elementName, array('phone', 'phone_ext'))) {
1108 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1111 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1115 //this is for phone type to work for profile edit
1116 if (in_array($elementName, array('phone', 'phone_ext'))) {
1117 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1120 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1125 // Check if there is a value, if so also add to where Clause
1127 if ($this->_params
) {
1129 if (isset($locationTypeId)) {
1130 $nm .= "-$locationTypeId";
1132 if (!is_numeric($elementType)) {
1133 $nm .= "$elementType";
1136 foreach ($this->_params
as $id => $values) {
1137 if ((is_array($values) && $values[0] == $nm) ||
1138 (in_array($elementName, array('phone', 'im'))
1139 && (strpos($values[0], $nm) !== FALSE)
1149 if ($field && isset($field['where'])) {
1150 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1151 $pf = substr($tableName, 8);
1152 $tName = $name . '-' . $pf . $elementType;
1153 if (isset($tableName)) {
1154 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1155 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1158 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1161 $this->_element
["{$tName}_id"] = 1;
1162 if (substr($tName, -15) == '-state_province') {
1163 // FIXME: hack to fix CRM-1900
1164 $a = Civi
::settings()->get('address_format');
1166 if (substr_count($a, 'state_province_name') > 0) {
1167 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1168 'pseudoField' => "{$pf}_id",
1169 'idCol' => "{$tName}_id",
1170 'bao' => 'CRM_Core_BAO_Address',
1172 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1175 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1176 'pseudoField' => 'state_province_abbreviation',
1177 'idCol' => "{$tName}_id",
1179 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1183 if (substr($elementFullName, 0, 2) == 'im') {
1184 $provider = "{$name}-{$elementFullName}-provider_id";
1185 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1186 $this->_element
[$provider] = 1;
1188 if ($pf == 'country' ||
$pf == 'county') {
1189 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1190 'pseudoField' => "{$pf}_id",
1191 'idCol' => "{$tName}_id",
1192 'bao' => 'CRM_Core_BAO_Address',
1194 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1197 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1201 if (in_array($pf, array('state_province', 'country', 'county'))) {
1202 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1205 $this->_element
["{$name}-{$elementFullName}"] = 1;
1208 if (empty($processed["`$tName`"])) {
1209 $processed["`$tName`"] = 1;
1210 $newName = $tableName . '_' . $index;
1211 switch ($tableName) {
1212 case 'civicrm_phone':
1213 case 'civicrm_email':
1215 case 'civicrm_openid':
1217 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1218 if ($tableName != 'civicrm_phone') {
1219 $this->_tables
[$tName] .= " AND `$tName`.$lCond";
1221 elseif (is_numeric($name)) {
1222 $this->_select
[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1225 // this special case to add phone type
1227 $phoneTypeCondition = " AND `$tName`.$cond ";
1228 //gross hack to pickup corrupted data also, CRM-7603
1229 if (strpos($cond, 'phone_type_id') !== FALSE) {
1230 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1231 if (!empty($lCond)) {
1232 $phoneTypeCondition .= " AND ( `$tName`.$lCond ) ";
1235 $this->_tables
[$tName] .= $phoneTypeCondition;
1238 //build locationType join
1239 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1242 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1246 case 'civicrm_state_province':
1247 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1248 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1249 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1251 $this->_whereTables
["{$name}-address"] = $addressJoin;
1255 case 'civicrm_country':
1256 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1257 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1258 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1260 $this->_whereTables
["{$name}-address"] = $addressJoin;
1264 case 'civicrm_county':
1265 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1266 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1267 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1269 $this->_whereTables
["{$name}-address"] = $addressJoin;
1275 $this->_whereTables
["{$name}-address"] = $addressJoin;
1284 // add location type join
1285 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1286 $this->_tables
[$locationTypeName] = $ltypeJoin;
1288 // table should be present in $this->_whereTables,
1289 // to add its condition in location type join, CRM-3939.
1290 if ($addWhereCount) {
1291 $locClause = array();
1292 foreach ($this->_whereTables
as $tableName => $clause) {
1293 if (!empty($locationTypeJoin[$tableName])) {
1294 $locClause[] = $locationTypeJoin[$tableName];
1298 if (!empty($locClause)) {
1299 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1304 if (!empty($addressCustomFieldIds)) {
1305 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1306 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1307 foreach ($locTypeName as $name => $dnc) {
1308 $this->_locationSpecificCustomFields
[$cfID] = array($name, array_search($name, $locationTypes));
1309 $fieldName = "$name-custom_{$cfID}";
1310 $tName = "$name-address-custom-{$cfID}";
1311 $aName = "`$name-address-custom-{$cfID}`";
1312 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1313 $this->_element
["{$tName}_id"] = 1;
1314 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1315 $this->_element
[$fieldName] = 1;
1316 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1323 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1325 public function addMultipleElements() {
1326 if (empty($this->_returnProperties
['website'])) {
1329 if (!is_array($this->_returnProperties
['website'])) {
1333 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1334 foreach ($elements as $elementFullName => $dontCare) {
1335 $tName = "website-{$key}-{$elementFullName}";
1336 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1337 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1338 $this->_element
["{$tName}_id"] = 1;
1339 $this->_element
["{$tName}"] = 1;
1341 $type = "website-{$key}-website_type_id";
1342 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1343 $this->_element
[$type] = 1;
1344 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1350 * Generate the query based on what type of query we need.
1352 * @param bool $count
1353 * @param bool $sortByChar
1354 * @param bool $groupContacts
1355 * @param bool $onlyDeleted
1358 * sql query parts as an array
1360 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1361 // build permission clause
1362 $this->generatePermissionClause($onlyDeleted, $count);
1365 if (isset($this->_rowCountClause
)) {
1366 $select = "SELECT {$this->_rowCountClause}";
1368 elseif (isset($this->_distinctComponentClause
)) {
1369 // we add distinct to get the right count for components
1370 // for the more complex result set, we use GROUP BY the same id
1372 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} ) as rowCount";
1375 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1377 $from = $this->_simpleFromClause
;
1378 if ($this->_useDistinct
) {
1379 $this->_useGroupBy
= TRUE;
1382 elseif ($sortByChar) {
1383 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1384 $from = $this->_simpleFromClause
;
1386 elseif ($groupContacts) {
1387 $select = 'SELECT contact_a.id as id';
1388 if ($this->_useDistinct
) {
1389 $this->_useGroupBy
= TRUE;
1391 $from = $this->_simpleFromClause
;
1394 if (!empty($this->_paramLookup
['group'])) {
1396 list($name, $op, $value, $grouping, $wildcard) = $this->_paramLookup
['group'][0];
1398 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
1399 $this->_paramLookup
['group'][0][1] = key($value);
1402 // Presumably the lines below come into manage groups screen.
1403 // make sure there is only one element
1404 // this is used when we are running under smog and need to know
1405 // how the contact was added (CRM-1203)
1406 $groups = (array) CRM_Utils_Array
::value($this->_paramLookup
['group'][0][1], $this->_paramLookup
['group'][0][2], $this->_paramLookup
['group'][0][2]);
1407 if ((count($this->_paramLookup
['group']) == 1) &&
1408 (count($groups) == 1)
1410 $groupId = $groups[0];
1412 //check if group is saved search
1413 $group = new CRM_Contact_BAO_Group();
1414 $group->id
= $groupId;
1417 if (!isset($group->saved_search_id
)) {
1418 $tbName = "`civicrm_group_contact-{$groupId}`";
1419 // CRM-17254 don't retrieve extra fields if contact_id is specifically requested
1420 // as this will add load to an intentionally light query.
1421 // ideally this code would be removed as it appears to be to support CRM-1203
1422 // and passing in the required returnProperties from the url would
1423 // make more sense that globally applying the requirements of one form.
1424 if (($this->_returnProperties
!= array('contact_id'))) {
1425 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1426 $this->_element
['group_contact_id'] = 1;
1427 $this->_select
['status'] = "$tbName.status as status";
1428 $this->_element
['status'] = 1;
1432 $this->_useGroupBy
= TRUE;
1434 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1435 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1437 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1438 $this->_useDistinct
= FALSE;
1439 $this->_useGroupBy
= TRUE;
1443 $select = "SELECT ";
1444 if (isset($this->_distinctComponentClause
)) {
1445 $select .= "{$this->_distinctComponentClause}, ";
1447 $select .= implode(', ', $this->_select
);
1448 $from = $this->_fromClause
;
1452 if (!empty($this->_whereClause
)) {
1453 $where = "WHERE {$this->_whereClause}";
1456 if (!empty($this->_permissionWhereClause
) && empty($this->_displayRelationshipType
)) {
1457 if (empty($where)) {
1458 $where = "WHERE $this->_permissionWhereClause";
1461 $where = "$where AND $this->_permissionWhereClause";
1466 if (!empty($this->_having
)) {
1467 foreach ($this->_having
as $havingSets) {
1468 foreach ($havingSets as $havingSet) {
1469 $havingValue[] = $havingSet;
1472 $having = ' HAVING ' . implode(' AND ', $havingValue);
1475 // if we are doing a transform, do it here
1476 // use the $from, $where and $having to get the contact ID
1477 if ($this->_displayRelationshipType
) {
1478 $this->filterRelatedContacts($from, $where, $having);
1481 return array($select, $from, $where, $having);
1485 * Get where values from the parameters.
1487 * @param string $name
1488 * @param mixed $grouping
1492 public function getWhereValues($name, $grouping) {
1494 foreach ($this->_params
as $values) {
1495 if ($values[0] == $name && $values[3] == $grouping) {
1506 * @param bool $relative
1507 * @param string $from
1510 public static function fixDateValues($relative, &$from, &$to) {
1512 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1517 * Convert values from form-appropriate to query-object appropriate.
1519 * The query object is increasingly supporting the sql-filter syntax which is the most flexible syntax.
1520 * So, ideally we would convert all fields to look like
1523 * // Set the operator for legacy reasons, but it is ignored
1525 * // array in sql filter syntax
1526 * 2 => array('BETWEEN' => array(1,60),
1531 * There are some examples of the syntax in
1532 * https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples/Relationship
1534 * More notes at CRM_Core_DAO::createSQLFilter
1536 * and a list of supported operators in CRM_Core_DAO
1538 * @param array $formValues
1539 * @param int $wildcard
1540 * @param bool $useEquals
1542 * @param string $apiEntity
1544 * @param array $entityReferenceFields
1545 * Field names of any entity reference fields (which will need reformatting to IN syntax).
1549 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL,
1550 $entityReferenceFields = array()) {
1552 if (empty($formValues)) {
1556 self
::filterCountryFromValuesIfStateExists($formValues);
1558 foreach ($formValues as $id => &$val) {
1559 // CRM-19374 - we don't want to change $val in $formValues.
1560 // Assign it to a temp variable which operates while iteration.
1563 if (self
::isAlreadyProcessedForQueryFormat($values)) {
1564 $params[] = $values;
1568 self
::legacyConvertFormValues($id, $values);
1570 // The form uses 1 field to represent two db fields
1571 if ($id == 'contact_type' && $values && (!is_array($values) ||
!array_intersect(array_keys($values), CRM_Core_DAO
::acceptedSQLOperators()))) {
1572 $contactType = array();
1574 foreach ((array) $values as $key => $type) {
1575 $types = explode('__', is_numeric($type) ?
$key : $type);
1576 $contactType[$types[0]] = $types[0];
1577 // Add sub-type if specified
1578 if (!empty($types[1])) {
1579 $subType[$types[1]] = $types[1];
1582 $params[] = array('contact_type', 'IN', $contactType, 0, 0);
1584 $params[] = array('contact_sub_type', 'IN', $subType, 0, 0);
1587 elseif ($id == 'privacy') {
1588 if (is_array($formValues['privacy'])) {
1589 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1590 foreach ($formValues['privacy'] as $key => $value) {
1592 $params[] = array($key, $op, $value, 0, 0);
1597 elseif ($id == 'email_on_hold') {
1598 if ($formValues['email_on_hold']['on_hold']) {
1599 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1602 elseif (substr($id, 0, 7) == 'custom_'
1604 substr($id, -9, 9) == '_relative'
1605 ||
substr($id, -5, 5) == '_from'
1606 ||
substr($id, -3, 3) == '_to'
1609 self
::convertCustomRelativeFields($formValues, $params, $values, $id);
1611 elseif (preg_match('/_date_relative$/', $id) ||
1612 $id == 'event_relative' ||
1613 $id == 'case_from_relative' ||
1614 $id == 'case_to_relative' ||
1615 $id == 'participant_relative'
1617 if ($id == 'event_relative') {
1618 $fromRange = 'event_start_date_low';
1619 $toRange = 'event_end_date_high';
1621 elseif ($id == 'participant_relative') {
1622 $fromRange = 'participant_register_date_low';
1623 $toRange = 'participant_register_date_high';
1625 elseif ($id == 'case_from_relative') {
1626 $fromRange = 'case_from_start_date_low';
1627 $toRange = 'case_from_start_date_high';
1629 elseif ($id == 'case_to_relative') {
1630 $fromRange = 'case_to_end_date_low';
1631 $toRange = 'case_to_end_date_high';
1634 $dateComponent = explode('_date_relative', $id);
1635 $fromRange = "{$dateComponent[0]}_date_low";
1636 $toRange = "{$dateComponent[0]}_date_high";
1639 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1640 // relative dates are not processed correctly as lower date value were ignored,
1641 // to ensure both high and low date value got added IF there is relative date,
1642 // we need to reset $formValues by unset and then adding again via CRM_Contact_BAO_Query::fixDateValues(...)
1643 if (!empty($formValues[$id])) {
1644 unset($formValues[$fromRange]);
1645 unset($formValues[$toRange]);
1647 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1651 elseif (in_array($id, $entityReferenceFields) && !empty($values) && is_string($values) && (strpos($values, ',') !=
1653 $params[] = array($id, 'IN', explode(',', $values), 0, 0);
1656 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
1661 $params[] = $values;
1668 * Function to support legacy format for groups and tags.
1671 * @param array|int $values
1674 public static function legacyConvertFormValues($id, &$values) {
1675 $legacyElements = array(
1680 'membership_type_id',
1681 'membership_status_id',
1683 if (in_array($id, $legacyElements) && is_array($values)) {
1684 // prior to 4.7, formValues for some attributes (e.g. group, tag) are stored in array(id1 => 1, id2 => 1),
1685 // as per the recent Search fixes $values need to be in standard array(id1, id2) format
1686 $values = CRM_Utils_Array
::convertCheckboxFormatToArray($values);
1691 * Fix values from query from/to something no-one cared enough to document.
1694 * @param array $values
1695 * @param int $wildcard
1696 * @param bool $useEquals
1698 * @param string $apiEntity
1700 * @return array|null
1702 public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1703 // skip a few search variables
1704 static $skipWhere = NULL;
1705 static $likeNames = NULL;
1708 // Change camelCase EntityName to lowercase with underscores
1709 $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity);
1711 // check if $value is in OK (Operator as Key) format as used by Get API
1712 if (CRM_Utils_System
::isNull($values)) {
1724 'display_relationship_type',
1728 if (in_array($id, $skipWhere) ||
1729 substr($id, 0, 4) == '_qf_' ||
1730 substr($id, 0, 7) == 'hidden_'
1736 (substr($id, 0, strlen($apiEntity)) != $apiEntity) &&
1737 (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_') &&
1738 (substr($id, 0, 7) != 'custom_')
1740 $id = $apiEntity . '_' . $id;
1744 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1747 // email comes in via advanced search
1748 // so use wildcard always
1749 if ($id == 'email') {
1753 if (!$useEquals && in_array($id, $likeNames)) {
1754 $result = array($id, 'LIKE', $values, 0, 1);
1756 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1757 $result = array($id, 'LIKE', $values, 0, 0);
1759 elseif ($id == 'contact_type' ||
1760 (!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO
::acceptedSQLOperators(), TRUE))
1762 $result = array($id, 'IN', $values, 0, $wildcard);
1765 $result = array($id, '=', $values, 0, $wildcard);
1772 * Get the where clause for a single field.
1774 * @param array $values
1775 * @param string $apiEntity
1777 public function whereClauseSingle(&$values, $apiEntity = NULL) {
1778 // do not process custom fields or prefixed contact ids or component params
1779 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1780 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1781 (substr($values[0], 0, 13) == 'contribution_') ||
1782 (substr($values[0], 0, 6) == 'event_') ||
1783 (substr($values[0], 0, 12) == 'participant_') ||
1784 (substr($values[0], 0, 7) == 'member_') ||
1785 (substr($values[0], 0, 6) == 'grant_') ||
1786 (substr($values[0], 0, 7) == 'pledge_') ||
1787 (substr($values[0], 0, 5) == 'case_') ||
1788 (substr($values[0], 0, 10) == 'financial_') ||
1789 (substr($values[0], 0, 8) == 'payment_') ||
1790 (substr($values[0], 0, 11) == 'membership_')
1795 // skip for hook injected fields / params
1796 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1797 if (array_key_exists($values[0], $extFields)) {
1801 switch ($values[0]) {
1802 case 'deleted_contacts':
1803 $this->deletedContacts($values);
1806 case 'contact_sub_type':
1807 $this->contactSubType($values);
1812 $this->group($values);
1815 // case tag comes from find contacts
1817 $this->tagSearch($values);
1821 case 'contact_tags':
1822 $this->tag($values);
1827 case 'note_subject':
1828 $this->notes($values);
1832 $this->ufUser($values);
1836 case 'display_name':
1837 $this->sortName($values);
1841 case 'postal_greeting':
1842 case 'email_greeting':
1843 $this->greetings($values);
1848 $this->email($values, $apiEntity);
1851 case 'phone_numeric':
1852 $this->phone_numeric($values);
1855 case 'phone_phone_type_id':
1856 case 'phone_location_type_id':
1857 $this->phone_option_group($values);
1860 case 'street_address':
1861 $this->street_address($values);
1864 case 'street_number':
1865 $this->street_number($values);
1868 case 'sortByCharacter':
1869 $this->sortByCharacter($values);
1872 case 'location_type':
1873 $this->locationType($values);
1877 $this->county($values);
1880 case 'state_province':
1881 case 'state_province_id':
1882 case 'state_province_name':
1883 $this->stateProvince($values);
1888 $this->country($values, FALSE);
1892 case 'postal_code_low':
1893 case 'postal_code_high':
1894 $this->postalCode($values);
1897 case 'activity_date':
1898 case 'activity_date_low':
1899 case 'activity_date_high':
1900 case 'activity_role':
1901 case 'activity_status_id':
1902 case 'activity_status':
1903 case 'activity_priority':
1904 case 'activity_priority_id':
1905 case 'followup_parent_id':
1907 case 'source_contact_id':
1908 case 'activity_text':
1909 case 'activity_option':
1910 case 'test_activities':
1911 case 'activity_type_id':
1912 case 'activity_type':
1913 case 'activity_survey_id':
1914 case 'activity_tags':
1915 case 'activity_taglist':
1916 case 'activity_test':
1917 case 'activity_campaign_id':
1918 case 'activity_engagement_level':
1920 case 'activity_result':
1921 case 'source_contact':
1922 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1927 case 'birth_date_low':
1928 case 'birth_date_high':
1929 case 'deceased_date_low':
1930 case 'deceased_date_high':
1931 $this->demographics($values);
1934 case 'age_asof_date':
1935 // handled by demographics
1938 case 'log_date_low':
1939 case 'log_date_high':
1940 $this->modifiedDates($values);
1944 $this->changeLog($values);
1947 case 'do_not_phone':
1948 case 'do_not_email':
1951 case 'do_not_trade':
1953 $this->privacy($values);
1956 case 'privacy_options':
1957 $this->privacyOptions($values);
1960 case 'privacy_operator':
1961 case 'privacy_toggle':
1962 // these are handled by privacy options
1965 case 'preferred_communication_method':
1966 $this->preferredCommunication($values);
1969 case 'relation_type_id':
1970 case 'relation_start_date_high':
1971 case 'relation_start_date_low':
1972 case 'relation_end_date_high':
1973 case 'relation_end_date_low':
1974 case 'relation_active_period_date_high':
1975 case 'relation_active_period_date_low':
1976 case 'relation_target_name':
1977 case 'relation_status':
1978 case 'relation_date_low':
1979 case 'relation_date_high':
1980 $this->relationship($values);
1981 $this->_relationshipValuesAdded
= TRUE;
1984 case 'task_status_id':
1985 $this->task($values);
1989 // since this case is handled with the above
1992 case 'prox_distance':
1993 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1996 case 'prox_street_address':
1998 case 'prox_postal_code':
1999 case 'prox_state_province_id':
2000 case 'prox_country_id':
2001 // handled by the proximity_distance clause
2005 $this->restWhere($values);
2011 * Given a list of conditions in params generate the required where clause.
2013 * @param string $apiEntity
2017 public function whereClause($apiEntity = NULL) {
2018 $this->_where
[0] = array();
2019 $this->_qill
[0] = array();
2021 $this->includeContactIds();
2022 if (!empty($this->_params
)) {
2023 foreach (array_keys($this->_params
) as $id) {
2024 if (empty($this->_params
[$id][0])) {
2027 // check for both id and contact_id
2028 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
2029 $this->_where
[0][] = self
::buildClause("contact_a.id", $this->_params
[$id][1], $this->_params
[$id][2]);
2032 $this->whereClauseSingle($this->_params
[$id], $apiEntity);
2036 CRM_Core_Component
::alterQuery($this, 'where');
2038 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
2041 if ($this->_customQuery
) {
2042 // Added following if condition to avoid the wrong value display for 'my account' / any UF info.
2043 // Hope it wont affect the other part of civicrm.. if it does please remove it.
2044 if (!empty($this->_customQuery
->_where
)) {
2045 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
2048 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
2052 $andClauses = array();
2055 if (!empty($this->_where
)) {
2056 foreach ($this->_where
as $grouping => $values) {
2057 if ($grouping > 0 && !empty($values)) {
2058 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
2063 if (!empty($this->_where
[0])) {
2064 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
2066 if (!empty($clauses)) {
2067 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
2070 if ($validClauses > 1) {
2071 $this->_useDistinct
= TRUE;
2075 return implode(' AND ', $andClauses);
2079 * Generate where clause for any parameters not already handled.
2081 * @param array $values
2085 public function restWhere(&$values) {
2086 $name = CRM_Utils_Array
::value(0, $values);
2087 $op = CRM_Utils_Array
::value(1, $values);
2088 $value = CRM_Utils_Array
::value(2, $values);
2089 $grouping = CRM_Utils_Array
::value(3, $values);
2090 $wildcard = CRM_Utils_Array
::value(4, $values);
2092 if (isset($grouping) && empty($this->_where
[$grouping])) {
2093 $this->_where
[$grouping] = array();
2096 $multipleFields = array('url');
2098 //check if the location type exists for fields
2100 $locType = explode('-', $name);
2102 if (!in_array($locType[0], $multipleFields)) {
2103 //add phone type if exists
2104 if (isset($locType[2]) && $locType[2]) {
2105 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
2109 $field = CRM_Utils_Array
::value($name, $this->_fields
);
2112 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
2121 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2122 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2123 if (isset($locType[1]) && is_numeric($locType[1])) {
2124 $lType = $locationType[$locType[1]];
2127 $field['title'] .= " ($lType)";
2130 if (substr($name, 0, 14) === 'state_province') {
2131 if (isset($locType[1]) && is_numeric($locType[1])) {
2133 $aName = "{$lType}-address";
2134 $where = "`$aName`.state_province_id";
2137 $where = "civicrm_address.state_province_id";
2140 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value);
2141 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
2142 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
2144 elseif (!empty($field['pseudoconstant'])) {
2145 $this->optionValueQuery(
2146 $name, $op, $value, $grouping,
2147 'CRM_Contact_DAO_Contact',
2153 if ($name == 'gender_id') {
2154 self
::$_openedPanes[ts('Demographics')] = TRUE;
2157 elseif (substr($name, 0, 7) === 'country' ||
substr($name, 0, 6) === 'county') {
2158 $name = (substr($name, 0, 7) === 'country') ?
"country_id" : "county_id";
2159 if (isset($locType[1]) && is_numeric($locType[1])) {
2161 $aName = "{$lType}-address";
2162 $where = "`$aName`.$name";
2165 $where = "civicrm_address.$name";
2168 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2170 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
2171 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
2173 elseif ($name === 'world_region') {
2174 $this->optionValueQuery(
2175 $name, $op, $value, $grouping,
2183 elseif ($name === 'is_deceased') {
2184 $this->setQillAndWhere($name, $op, $value, $grouping, $field);
2185 self
::$_openedPanes[ts('Demographics')] = TRUE;
2187 elseif ($name === 'created_date' ||
$name === 'modified_date' ||
$name === 'deceased_date' ||
$name === 'birth_date') {
2188 $appendDateTime = TRUE;
2189 if ($name === 'deceased_date' ||
$name === 'birth_date') {
2190 $appendDateTime = FALSE;
2191 self
::$_openedPanes[ts('Demographics')] = TRUE;
2193 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2195 elseif ($name === 'contact_id') {
2196 if (is_int($value)) {
2197 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2198 $this->_qill
[$grouping][] = "$field[title] $op $value";
2201 elseif ($name === 'name') {
2202 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2205 $value = self
::getWildCardedValue($wildcard, $op, $value);
2207 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
2208 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2209 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2210 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2212 elseif ($name === 'current_employer') {
2215 $value = self
::getWildCardedValue($wildcard, $op, $value);
2217 $ceWhereClause = self
::buildClause("contact_a.organization_name", $op,
2220 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2221 $this->_where
[$grouping][] = $ceWhereClause;
2222 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2224 elseif ($name === 'email_greeting') {
2225 $filterCondition = array('greeting_type' => 'email_greeting');
2226 $this->optionValueQuery(
2227 $name, $op, $value, $grouping,
2228 CRM_Core_PseudoConstant
::greeting($filterCondition),
2230 ts('Email Greeting')
2233 elseif ($name === 'postal_greeting') {
2234 $filterCondition = array('greeting_type' => 'postal_greeting');
2235 $this->optionValueQuery(
2236 $name, $op, $value, $grouping,
2237 CRM_Core_PseudoConstant
::greeting($filterCondition),
2239 ts('Postal Greeting')
2242 elseif ($name === 'addressee') {
2243 $filterCondition = array('greeting_type' => 'addressee');
2244 $this->optionValueQuery(
2245 $name, $op, $value, $grouping,
2246 CRM_Core_PseudoConstant
::greeting($filterCondition),
2251 elseif (substr($name, 0, 4) === 'url-') {
2252 $tName = 'civicrm_website';
2253 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2254 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2257 $value = self
::getWildCardedValue($wildcard, $op, $value);
2260 $this->_where
[$grouping][] = $d = self
::buildClause('civicrm_website.url', $op, $value);
2261 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2263 elseif ($name === 'contact_is_deleted') {
2264 $this->setQillAndWhere('is_deleted', $op, $value, $grouping, $field);
2266 elseif (!empty($field['where'])) {
2268 if (!empty($field['type'])) {
2269 $type = CRM_Utils_Type
::typeToString($field['type']);
2272 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2274 if (isset($locType[1]) &&
2275 is_numeric($locType[1])
2279 //get the location name
2280 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2281 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
2282 $fieldName = "LOWER(`$tName`.$fldName)";
2284 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2285 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2289 if ($tableName == 'civicrm_contact') {
2290 $fieldName = "contact_a.{$fieldName}";
2293 if ($op != 'IN' && !is_numeric($value) && !is_array($value)) {
2294 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
2295 $fieldName = "LOWER({$field['where']})";
2298 $fieldName = "{$field['where']}";
2303 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2304 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(
2305 1 => $field['title'],
2307 3 => (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) ?
$qillVal : "'$qillVal'"));
2309 if (is_array($value)) {
2310 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2311 // for api style operators for functions that hit this point without worrying about regression
2312 // (the previous comments indicated the condition for hitting this point were unknown
2313 // per CRM-14743 we are adding modified_date & created_date operator support
2314 $operations = array_keys($value);
2315 foreach ($operations as $operator) {
2316 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2317 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2318 //so this condition will satisfy the search for now
2319 if (strpos($op, 'IN') !== FALSE) {
2320 $value = array($op => $value);
2322 // we don't know when this might happen
2324 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $operator)));
2328 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($fieldName, $value, $type);
2331 if (!strpos($op, 'IN')) {
2332 $value = $strtolower($value);
2336 $value = self
::getWildCardedValue($wildcard, $op, $value);
2339 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2343 if ($setTables && isset($field['where'])) {
2344 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2345 if (isset($tableName)) {
2346 $this->_tables
[$tableName] = 1;
2347 $this->_whereTables
[$tableName] = 1;
2359 public static function getLocationTableName(&$where, &$locType) {
2360 if (isset($locType[1]) && is_numeric($locType[1])) {
2361 list($tbName, $fldName) = explode(".", $where);
2363 //get the location name
2364 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2365 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2366 if (in_array($locType[0], $specialFields)) {
2367 //hack to fix / special handing for phone_ext
2368 if ($locType[0] == 'phone_ext') {
2369 $locType[0] = 'phone';
2371 if (isset($locType[2]) && $locType[2]) {
2372 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2375 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2378 elseif (in_array($locType[0],
2383 'street_number_suffix',
2385 'supplemental_address_1',
2386 'supplemental_address_2',
2387 'supplemental_address_3',
2390 'postal_code_suffix',
2396 //fix for search by profile with address fields.
2397 $tName = "{$locationType[$locType[1]]}-address";
2399 elseif (in_array($locType[0],
2407 $tName = "{$locationType[$locType[1]]}-email";
2409 elseif ($locType[0] == 'provider_id') {
2410 $tName = "{$locationType[$locType[1]]}-im";
2412 elseif ($locType[0] == 'openid') {
2413 $tName = "{$locationType[$locType[1]]}-openid";
2416 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2418 $tName = str_replace(' ', '_', $tName);
2419 return array($tName, $fldName);
2421 CRM_Core_Error
::fatal();
2425 * Given a result dao, extract the values and return that array
2427 * @param CRM_Core_DAO $dao
2430 * values for this query
2432 public function store($dao) {
2435 foreach ($this->_element
as $key => $dontCare) {
2436 if (property_exists($dao, $key)) {
2437 if (strpos($key, '-') !== FALSE) {
2438 $values = explode('-', $key);
2439 $lastElement = array_pop($values);
2441 $cnt = count($values);
2443 foreach ($values as $v) {
2444 if (!array_key_exists($v, $current)) {
2445 $current[$v] = array();
2447 //bad hack for im_provider
2448 if ($lastElement == 'provider_id') {
2449 if ($count < $cnt) {
2450 $current = &$current[$v];
2453 $lastElement = "{$v}_{$lastElement}";
2457 $current = &$current[$v];
2462 $current[$lastElement] = $dao->$key;
2465 $value[$key] = $dao->$key;
2473 * Getter for tables array.
2477 public function tables() {
2478 return $this->_tables
;
2482 * Sometimes used to create the from clause, but, not reliably, set
2483 * this AND set tables.
2485 * It's unclear the intent - there is a 'simpleFrom' clause which
2486 * takes whereTables into account & a fromClause which doesn't.
2488 * logic may have eroded?
2492 public function whereTables() {
2493 return $this->_whereTables
;
2497 * Generate the where clause (used in match contacts and permissions)
2499 * @param array $params
2500 * @param array $fields
2501 * @param array $tables
2502 * @param $whereTables
2503 * @param bool $strict
2507 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2508 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2512 $tables = array_merge($query->tables(), $tables);
2513 $whereTables = array_merge($query->whereTables(), $whereTables);
2515 return $query->_whereClause
;
2519 * Create the from clause.
2521 * @param array $tables
2522 * Tables that need to be included in this from clause. If null,
2523 * return mimimal from clause (i.e. civicrm_contact).
2524 * @param array $inner
2525 * Tables that should be inner-joined.
2526 * @param array $right
2527 * Tables that should be right-joined.
2528 * @param bool $primaryLocation
2529 * Search on primary location. See note below.
2531 * Determines search mode based on bitwise MODE_* constants.
2532 * @param string|NULL $apiEntity
2533 * Determines search mode based on entity by string.
2535 * The $primaryLocation flag only seems to be used when
2536 * locationType() has been called. This may be a search option
2537 * exposed, or perhaps it's a "search all details" approach which
2538 * predates decoupling of location types and primary fields?
2540 * @see https://issues.civicrm.org/jira/browse/CRM-19967
2545 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1, $apiEntity = NULL) {
2547 $from = ' FROM civicrm_contact contact_a';
2548 if (empty($tables)) {
2552 if (!empty($tables['civicrm_worldregion'])) {
2553 $tables = array_merge(array('civicrm_country' => 1), $tables);
2556 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2557 CRM_Utils_Array
::value('civicrm_county', $tables)
2558 ) && empty($tables['civicrm_address'])
2560 $tables = array_merge(array('civicrm_address' => 1),
2565 // add group_contact and group table is subscription history is present
2566 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2567 $tables = array_merge(array(
2568 'civicrm_group' => 1,
2569 'civicrm_group_contact' => 1,
2575 // to handle table dependencies of components
2576 CRM_Core_Component
::tableNames($tables);
2577 // to handle table dependencies of hook injected tables
2578 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2580 //format the table list according to the weight
2581 $info = CRM_Core_TableHierarchy
::info();
2583 foreach ($tables as $key => $value) {
2585 if (strpos($key, '-') !== FALSE) {
2586 $keyArray = explode('-', $key);
2587 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2589 elseif (strpos($key, '_') !== FALSE) {
2590 $keyArray = explode('_', $key);
2591 if (is_numeric(array_pop($keyArray))) {
2592 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2595 $k = CRM_Utils_Array
::value($key, $info, 99);
2599 $k = CRM_Utils_Array
::value($key, $info, 99);
2601 $tempTable[$k . ".$key"] = $key;
2604 $newTables = array();
2605 foreach ($tempTable as $key) {
2606 $newTables[$key] = $tables[$key];
2609 $tables = $newTables;
2611 foreach ($tables as $name => $value) {
2616 if (!empty($inner[$name])) {
2619 elseif (!empty($right[$name])) {
2627 // if there is already a join statement in value, use value itself
2628 if (strpos($value, 'JOIN')) {
2629 $from .= " $value ";
2632 $from .= " $side JOIN $name ON ( $value ) ";
2636 $searchPrimary = '';
2637 if (Civi
::settings()->get('searchPrimaryDetailsOnly') ||
$apiEntity) {
2638 $searchPrimary = "AND {$name}.is_primary = 1";
2641 case 'civicrm_address':
2642 //CRM-14263 further handling of address joins further down...
2643 if (!$primaryLocation) {
2644 $searchPrimary = '';
2646 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id {$searchPrimary} )";
2649 case 'civicrm_phone':
2650 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id {$searchPrimary}) ";
2653 case 'civicrm_email':
2654 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id {$searchPrimary})";
2658 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id {$searchPrimary}) ";
2662 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2663 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2664 $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)";
2667 case 'civicrm_openid':
2668 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id {$searchPrimary} )";
2671 case 'civicrm_worldregion':
2672 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2673 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2676 case 'civicrm_location_type':
2677 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2680 case 'civicrm_group':
2681 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2684 case 'civicrm_group_contact':
2685 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2688 case 'civicrm_group_contact_cache':
2689 $from .= " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
2692 case 'civicrm_activity':
2693 case 'civicrm_activity_tag':
2694 case 'activity_type':
2695 case 'activity_status':
2697 case 'civicrm_activity_contact':
2698 case 'source_contact':
2699 case 'activity_priority':
2700 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2703 case 'civicrm_entity_tag':
2704 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2705 civicrm_entity_tag.entity_id = contact_a.id ) ";
2708 case 'civicrm_note':
2709 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2710 contact_a.id = civicrm_note.entity_id ) ";
2713 case 'civicrm_subscription_history':
2714 $from .= " $side JOIN civicrm_subscription_history
2715 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2716 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2719 case 'civicrm_relationship':
2720 if (self
::$_relType == 'reciprocal') {
2721 if (self
::$_relationshipTempTable) {
2722 // we have a temptable to join on
2723 $tbl = self
::$_relationshipTempTable;
2724 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2727 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2728 $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)";
2731 elseif (self
::$_relType == 'b') {
2732 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2733 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2736 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2737 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2742 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2743 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2747 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2750 case 'civicrm_grant':
2751 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2754 case 'civicrm_campaign':
2755 //Move to default case if not in either mode.
2756 if ($mode & CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
2757 $from .= CRM_Contribute_BAO_Query
::from($name, $mode, $side);
2760 elseif ($mode & CRM_Contact_BAO_Query
::MODE_MAILING
) {
2761 $from .= CRM_Mailing_BAO_Query
::from($name, $mode, $side);
2765 case 'civicrm_website':
2766 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2770 $locationTypeName = '';
2771 if (strpos($name, '-address') != 0) {
2772 $locationTypeName = 'address';
2774 elseif (strpos($name, '-phone') != 0) {
2775 $locationTypeName = 'phone';
2777 elseif (strpos($name, '-email') != 0) {
2778 $locationTypeName = 'email';
2780 elseif (strpos($name, '-im') != 0) {
2781 $locationTypeName = 'im';
2783 elseif (strpos($name, '-openid') != 0) {
2784 $locationTypeName = 'openid';
2787 if ($locationTypeName) {
2788 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2789 $parts = explode('-', $name);
2790 $locationID = array_search($parts[0], CRM_Core_BAO_Address
::buildOptions('location_type_id', 'get', array('name' => $parts[0])));
2791 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2794 $from .= CRM_Core_Component
::from($name, $mode, $side);
2796 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2805 * WHERE / QILL clause for deleted_contacts
2807 * @param array $values
2809 public function deletedContacts($values) {
2810 list($_, $_, $value, $grouping, $_) = $values;
2812 // *prepend* to the relevant grouping as this is quite an important factor
2813 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2818 * Where / qill clause for contact_type
2822 public function contactType(&$values) {
2823 list($name, $op, $value, $grouping, $wildcard) = $values;
2825 $subTypes = array();
2828 // account for search builder mapping multiple values
2829 if (!is_array($value)) {
2830 $values = self
::parseSearchBuilderString($value, 'String');
2831 if (is_array($values)) {
2832 $value = array_flip($values);
2836 if (is_array($value)) {
2837 foreach ($value as $k => $v) {
2842 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2843 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2846 if (!empty($subType)) {
2847 $subTypes[$subType] = 1;
2849 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2854 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2855 $contactType = $contactTypeANDSubType[0];
2856 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2857 if (!empty($subType)) {
2858 $subTypes[$subType] = 1;
2860 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2864 if (!empty($clause)) {
2866 if ($op == 'IN' ||
$op == 'NOT IN') {
2867 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2870 $type = array_pop($clause);
2871 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2874 $this->_qill
[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2876 if (!empty($subTypes)) {
2877 $this->includeContactSubTypes($subTypes, $grouping);
2883 * Where / qill clause for contact_sub_type.
2885 * @param array $values
2887 public function contactSubType(&$values) {
2888 list($name, $op, $value, $grouping, $wildcard) = $values;
2889 $this->includeContactSubTypes($value, $grouping, $op);
2897 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2899 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2901 $value = $value[$op];
2905 $alias = "contact_a.contact_sub_type";
2906 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
2908 $op = str_replace('IN', 'LIKE', $op);
2909 $op = str_replace('=', 'LIKE', $op);
2910 $op = str_replace('!', 'NOT ', $op);
2912 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2913 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
2915 elseif (is_array($value)) {
2916 foreach ($value as $k => $v) {
2917 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($v, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2921 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2924 if (!empty($clause)) {
2925 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2927 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', array(1 => $qillOperators[$op])) . implode(' ' . ts('or') . ' ', array_keys($clause));
2931 * Where / qill clause for groups.
2935 public function group($values) {
2936 list($name, $op, $value, $grouping, $wildcard) = $values;
2938 // If the $value is in OK (operator as key) array format we need to extract the key as operator and value first
2939 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2941 $value = $value[$op];
2944 // Replace pseudo operators from search builder
2945 $op = str_replace('EMPTY', 'NULL', $op);
2947 if (strpos($op, 'NULL')) {
2951 if (count($value) > 1) {
2952 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
2953 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $op)));
2955 $this->_useDistinct
= TRUE;
2958 if (isset($value)) {
2959 $value = CRM_Utils_Array
::value($op, $value, $value);
2962 if ($name == 'group_type') {
2963 $value = array_keys($this->getGroupsFromTypeCriteria($value));
2966 $regularGroupIDs = $smartGroupIDs = array();
2967 foreach ((array) $value as $id) {
2968 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
2969 $smartGroupIDs[] = $id;
2972 $regularGroupIDs[] = $id;
2976 $isNotOp = ($op == 'NOT IN' ||
$op == '!=');
2979 $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
2981 is_array($gcsValues[2])
2983 foreach ($gcsValues[2] as $k => $v) {
2985 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2990 $statii[] = "'Added'";
2992 $groupClause = array();
2993 if (count($regularGroupIDs) ||
empty($value)) {
2994 // include child groups IDs if any
2995 $childGroupIds = (array) CRM_Contact_BAO_Group
::getChildGroupIds($regularGroupIDs);
2996 foreach ($childGroupIds as $key => $id) {
2997 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
2998 $smartGroupIDs[] = $id;
2999 unset($childGroupIds[$key]);
3002 if (count($childGroupIds)) {
3003 $regularGroupIDs = array_merge($regularGroupIDs, $childGroupIds);
3006 // if $regularGroupIDs is populated with regular child group IDs
3007 // then change the mysql operator to desired
3008 if (count($regularGroupIDs) > 1) {
3009 $op = strpos($op, 'IN') ?
$op : ($op == '!=') ?
'NOT IN' : 'IN';
3011 $groupIds = implode(',', (array) $regularGroupIDs);
3012 $gcTable = "`civicrm_group_contact-{$groupIds}`";
3013 $joinClause = array("contact_a.id = {$gcTable}.contact_id");
3015 if (strpos($op, 'IN') !== FALSE) {
3016 $clause = "{$gcTable}.group_id $op ( $groupIds ) ";
3018 elseif ($op == '!=') {
3019 $clause = "{$gcTable}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact cgc WHERE cgc.group_id = $groupIds )";
3022 $clause = "{$gcTable}.group_id $op $groupIds ";
3024 $groupClause[] = "( {$clause} )";
3027 $joinClause[] = "{$gcTable}.status IN (" . implode(', ', $statii) . ")";
3029 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3032 //CRM-19589: contact(s) removed from a Smart Group, resides in civicrm_group_contact table
3033 if (count($smartGroupIDs)) {
3034 $groupClause[] = " ( " . $this->addGroupContactCache($smartGroupIDs, NULL, "contact_a", $op) . " ) ";
3037 $and = ($op == 'IS NULL') ?
' AND ' : ' OR ';
3038 $this->_where
[$grouping][] = ' ( ' . implode($and, $groupClause) . ' ) ';
3040 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
3041 $this->_qill
[$grouping][] = ts("Group(s) %1 %2", array(1 => $qillop, 2 => $qillVal));
3042 if (strpos($op, 'NULL') === FALSE) {
3043 $this->_qill
[$grouping][] = ts("Group Status %1", array(1 => implode(' ' . ts('or') . ' ', $statii)));
3048 * Function translates selection of group type into a list of groups.
3053 public function getGroupsFromTypeCriteria($value) {
3054 $groupIds = array();
3055 foreach ((array) $value as $groupTypeValue) {
3056 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
3057 $groupIds = ($groupIds +
$groupList);
3063 * @param array $groups
3064 * @param string $tableAlias
3065 * @param string $joinTable
3068 * @return null|string
3070 public function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a", $op) {
3071 $isNullOp = (strpos($op, 'NULL') !== FALSE);
3072 $groupsIds = $groups;
3073 if (!$isNullOp && !$groups) {
3076 elseif (strpos($op, 'IN') !== FALSE) {
3077 $groups = array($op => $groups);
3079 elseif (is_array($groups) && count($groups)) {
3080 $groups = array('IN' => $groups);
3083 // Find all the groups that are part of a saved search.
3084 $smartGroupClause = self
::buildClause("id", $op, $groups, 'Int');
3086 SELECT id, cache_date, saved_search_id, children
3088 WHERE $smartGroupClause
3089 AND ( saved_search_id != 0
3090 OR saved_search_id IS NOT NULL
3091 OR children IS NOT NULL )
3094 $group = CRM_Core_DAO
::executeQuery($sql);
3096 while ($group->fetch()) {
3097 $this->_useDistinct
= TRUE;
3098 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
3099 CRM_Contact_BAO_GroupContactCache
::load($group);
3102 if ($group->N
== 0) {
3107 $tableAlias = "`civicrm_group_contact_cache_";
3108 $tableAlias .= ($isNullOp) ?
"a`" : implode(',', (array) $groupsIds) . "`";
3111 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.id = {$tableAlias}.contact_id ";
3112 return self
::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
3116 * Where / qill clause for cms users
3120 public function ufUser(&$values) {
3121 list($name, $op, $value, $grouping, $wildcard) = $values;
3124 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3126 $this->_qill
[$grouping][] = ts('CMS User');
3128 elseif ($value == 0) {
3129 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3131 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3132 $this->_qill
[$grouping][] = ts('Not a CMS User');
3137 * All tag search specific.
3139 * @param array $values
3141 public function tagSearch(&$values) {
3142 list($name, $op, $value, $grouping, $wildcard) = $values;
3145 $value = "%{$value}%";
3147 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3148 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3150 $etTable = "`civicrm_entity_tag-" . $value . "`";
3151 $tTable = "`civicrm_tag-" . $value . "`";
3153 if ($useAllTagTypes[2]) {
3154 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3155 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3156 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3158 // search tag in cases
3159 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3160 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
3161 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3162 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3163 LEFT JOIN civicrm_case
3164 ON (civicrm_case_contact.case_id = civicrm_case.id
3165 AND civicrm_case.is_deleted = 0 )
3166 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3167 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3168 // search tag in activities
3169 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3170 $tActTable = "`civicrm_act_tag-" . $value . "`";
3171 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3172 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3174 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3175 = " LEFT JOIN civicrm_activity_contact
3176 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3177 LEFT JOIN civicrm_activity
3178 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3179 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3180 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3181 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3183 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $value . "' OR {$tCaseTable}.name $op '" . $value . "' OR {$tActTable}.name $op '" . $value . "')";
3184 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
3187 $etTable = "`civicrm_entity_tag-" . $value . "`";
3188 $tTable = "`civicrm_tag-" . $value . "`";
3189 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3190 {$etTable}.entity_table = 'civicrm_contact' )
3191 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3193 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3194 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
3199 * Where / qill clause for tag.
3201 * @param array $values
3203 public function tag(&$values) {
3204 list($name, $op, $value, $grouping, $wildcard) = $values;
3206 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, array('onlyActive' => FALSE));
3207 // API/Search Builder format array(operator => array(values))
3208 if (is_array($value)) {
3209 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3211 $value = $value[$op];
3213 if (count($value) > 1) {
3214 $this->_useDistinct
= TRUE;
3216 $value = implode(',', (array) $value);
3219 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3220 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3222 $etTable = "`civicrm_entity_tag-" . $value . "`";
3224 if ($useAllTagTypes[2]) {
3225 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3226 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3228 // search tag in cases
3229 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3230 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3231 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3233 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3234 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3235 LEFT JOIN civicrm_case
3236 ON (civicrm_case_contact.case_id = civicrm_case.id
3237 AND civicrm_case.is_deleted = 0 )
3238 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3239 // search tag in activities
3240 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3241 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3242 = " LEFT JOIN civicrm_activity_contact
3243 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3244 LEFT JOIN civicrm_activity
3245 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3246 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3247 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3250 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3251 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3254 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3258 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3259 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3262 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3263 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3264 $op = str_replace('EMPTY', 'NULL', $op);
3265 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3267 // CRM-16941: for tag tried with != operator we don't show contact who don't have given $value AND also in other tag
3268 elseif ($op == '!=') {
3269 $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') . ")";
3271 elseif ($op == '=' ||
strstr($op, 'IN')) {
3272 $op = ($op == '=') ?
'IN' : $op;
3273 $this->_where
[$grouping][] = "{$etTable}.tag_id $op ( $value )";
3276 $this->_qill
[$grouping][] = ts('Tagged %1 %2', array(1 => $qillop, 2 => $qillVal));
3280 * Where/qill clause for notes
3282 * @param array $values
3284 public function notes(&$values) {
3285 list($name, $op, $value, $grouping, $wildcard) = $values;
3287 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3288 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3289 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3291 $this->_useDistinct
= TRUE;
3293 $this->_tables
['civicrm_note'] = $this->_whereTables
['civicrm_note']
3294 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3296 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3298 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3300 if (strpos($value, '%') === FALSE) {
3301 $value = "%$value%";
3305 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3311 if ($noteOption %
2 == 0) {
3312 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3313 $label = ts('Note: Body Only');
3315 if ($noteOption %
3 == 0) {
3316 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3317 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3319 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3320 list($qillOp, $qillVal) = self
::buildQillForFieldValue(NULL, $name, $n, $op);
3321 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillOp, 3 => $qillVal));
3325 * @param string $name
3331 public function nameNullOrEmptyOp($name, $op, $grouping) {
3335 $this->_where
[$grouping][] = "contact_a.$name $op";
3336 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3340 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3341 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3344 case 'IS NOT EMPTY':
3345 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3346 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3355 * Where / qill clause for sort_name
3357 * @param array $values
3359 public function sortName(&$values) {
3360 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3362 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3363 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3367 $input = $value = trim($value);
3369 if (!strlen($value)) {
3373 $config = CRM_Core_Config
::singleton();
3377 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3380 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3382 $firstChar = substr($value, 0, 1);
3383 $lastChar = substr($value, -1, 1);
3384 $quotes = array("'", '"');
3385 // If string is quoted, strip quotes and otherwise don't alter it
3386 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3387 $value = trim($value, implode('', $quotes));
3389 // Replace spaces with wildcards for a LIKE operation
3390 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3391 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3392 $value = str_replace(' ', '%', $value);
3394 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($value)));
3395 if (strlen($value)) {
3396 $fieldsub = array();
3397 $value = "'" . self
::getWildCardedValue($wildcard, $op, $value) . "'";
3398 if ($fieldName == 'sort_name') {
3399 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3400 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3403 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3404 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3406 $fieldsub[] = " ( $wc $op $value )";
3407 if ($config->includeNickNameInName
) {
3408 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3409 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3410 $fieldsub[] = " ( $wc $op $value )";
3412 if ($config->includeEmailInName
) {
3413 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3415 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3418 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3420 $this->_where
[$grouping][] = $sub;
3421 if ($config->includeEmailInName
) {
3422 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3423 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3426 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3431 * Where/qill clause for greeting fields.
3433 * @param array $values
3435 public function greetings(&$values) {
3436 list($name, $op, $value, $grouping, $wildcard) = $values;
3437 $name .= '_display';
3439 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
3440 $this->_qill
[$grouping][] = ts('Greeting %1 %2', array(1 => $qillop, 2 => $qillVal));
3441 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value, 'String');
3445 * Where / qill clause for email
3447 * @param array $values
3448 * @param string $apiEntity
3450 protected function email(&$values, $apiEntity) {
3451 list($name, $op, $value, $grouping, $wildcard) = $values;
3452 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3454 // CRM-18147: for Contact's GET API, email fieldname got appended with its entity as in {$apiEntiy}_{$name}
3455 // so following code is use build whereClause for contact's primart email id
3456 if (!empty($apiEntity)) {
3457 $dataType = 'String';
3458 if ($name == 'email_id') {
3459 $dataType = 'Integer';
3463 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.is_primary', '=', 1, 'Integer');
3464 $this->_where
[$grouping][] = self
::buildClause("civicrm_email.$name", $op, $value, $dataType);
3468 $n = strtolower(trim($value));
3470 if (substr($n, 0, 1) == '"' &&
3471 substr($n, -1, 1) == '"'
3473 $n = substr($n, 1, -1);
3474 $value = CRM_Core_DAO
::escapeString($n);
3478 $value = self
::getWildCardedValue($wildcard, $op, $n);
3480 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3481 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3484 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3485 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3490 * Where / qill clause for phone number
3492 * @param array $values
3494 public function phone_numeric(&$values) {
3495 list($name, $op, $value, $grouping, $wildcard) = $values;
3496 // Strip non-numeric characters; allow wildcards
3497 $number = preg_replace('/[^\d%]/', '', $value);
3499 if (strpos($number, '%') === FALSE) {
3500 $number = "%$number%";
3503 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3504 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3505 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3510 * Where / qill clause for phone type/location
3512 * @param array $values
3514 public function phone_option_group($values) {
3515 list($name, $op, $value, $grouping, $wildcard) = $values;
3516 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3517 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3518 $optionName = $options[$value];
3519 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3520 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3521 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3525 * Where / qill clause for street_address.
3527 * @param array $values
3529 public function street_address(&$values) {
3530 list($name, $op, $value, $grouping, $wildcard) = $values;
3539 $value = strtolower($n);
3540 if (strpos($value, '%') === FALSE) {
3541 // only add wild card if not there
3542 $value = "%{$value}%";
3545 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3546 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3547 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3550 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3551 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3554 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3558 * Where / qill clause for street_unit.
3560 * @param array $values
3562 public function street_number(&$values) {
3563 list($name, $op, $value, $grouping, $wildcard) = $values;
3571 if (strtolower($n) == 'odd') {
3572 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3573 $this->_qill
[$grouping][] = ts('Street Number is odd');
3575 elseif (strtolower($n) == 'even') {
3576 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3577 $this->_qill
[$grouping][] = ts('Street Number is even');
3580 $value = strtolower($n);
3582 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3583 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3584 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3587 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3591 * Where / qill clause for sorting by character.
3593 * @param array $values
3595 public function sortByCharacter(&$values) {
3596 list($name, $op, $value, $grouping, $wildcard) = $values;
3598 $name = trim($value);
3599 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3600 $this->_where
[$grouping][] = $cond;
3601 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3605 * Where / qill clause for including contact ids.
3607 public function includeContactIDs() {
3608 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3612 $contactIds = array();
3613 foreach ($this->_params
as $id => $values) {
3614 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3615 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3618 CRM_Utils_Type
::validateAll($contactIds, 'Positive');
3619 if (!empty($contactIds)) {
3620 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3625 * Where / qill clause for postal code.
3627 * @param array $values
3629 public function postalCode(&$values) {
3630 // skip if the fields dont have anything to do with postal_code
3631 if (empty($this->_fields
['postal_code'])) {
3635 list($name, $op, $value, $grouping, $wildcard) = $values;
3637 // Handle numeric postal code range searches properly by casting the column as numeric
3638 if (is_numeric($value)) {
3639 $field = "IF (civicrm_address.postal_code REGEXP '^[0-9]{1,10}$', CAST(civicrm_address.postal_code AS UNSIGNED), 0)";
3640 $val = CRM_Utils_Type
::escape($value, 'Integer');
3643 $field = 'civicrm_address.postal_code';
3644 // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string.
3645 if (!is_array($value)) {
3646 $val = CRM_Utils_Type
::escape($value, 'String');
3649 // Do we need to escape values here? I would expect buildClause does.
3654 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3656 if ($name == 'postal_code') {
3657 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3658 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3660 elseif ($name == 'postal_code_low') {
3661 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3662 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3664 elseif ($name == 'postal_code_high') {
3665 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3666 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3671 * Where / qill clause for location type.
3673 * @param array $values
3674 * @param null $status
3678 public function locationType(&$values, $status = NULL) {
3679 list($name, $op, $value, $grouping, $wildcard) = $values;
3681 if (is_array($value)) {
3682 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3683 $this->_tables
['civicrm_address'] = 1;
3684 $this->_whereTables
['civicrm_address'] = 1;
3686 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3688 foreach ($value as $id) {
3689 $names[] = $locationType[$id];
3692 $this->_primaryLocation
= FALSE;
3695 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3698 return implode(' ' . ts('or') . ' ', $names);
3705 * @param bool $fromStateProvince
3707 * @return array|NULL
3709 public function country(&$values, $fromStateProvince = TRUE) {
3710 list($name, $op, $value, $grouping, $wildcard) = $values;
3712 if (!$fromStateProvince) {
3713 $stateValues = $this->getWhereValues('state_province', $grouping);
3714 if (!empty($stateValues)) {
3715 // return back to caller if there are state province values
3716 // since that handles this case
3721 $countryClause = $countryQill = NULL;
3722 if ($values && !empty($value)) {
3723 $this->_tables
['civicrm_address'] = 1;
3724 $this->_whereTables
['civicrm_address'] = 1;
3726 $countryClause = self
::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
3727 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, 'country_id', $value, $op);
3728 $countryQill = ts("%1 %2 %3", array(1 => 'Country', 2 => $qillop, 3 => $qillVal));
3730 if (!$fromStateProvince) {
3731 $this->_where
[$grouping][] = $countryClause;
3732 $this->_qill
[$grouping][] = $countryQill;
3736 if ($fromStateProvince) {
3737 if (!empty($countryClause)) {
3740 " ...AND... " . $countryQill,
3744 return array(NULL, NULL);
3750 * Where / qill clause for county (if present).
3752 * @param array $values
3753 * @param null $status
3757 public function county(&$values, $status = NULL) {
3758 list($name, $op, $value, $grouping, $wildcard) = $values;
3760 if (!is_array($value)) {
3761 // force the county to be an array
3762 $value = array($value);
3765 // check if the values are ids OR names of the counties
3766 $inputFormat = 'id';
3767 foreach ($value as $v) {
3768 if (!is_numeric($v)) {
3769 $inputFormat = 'name';
3777 elseif ($op == '!=') {
3781 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3782 $op = str_replace('EMPTY', 'NULL', $op);
3785 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3786 $clause = "civicrm_address.county_id $op";
3788 elseif ($inputFormat == 'id') {
3789 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3791 $county = CRM_Core_PseudoConstant
::county();
3792 foreach ($value as $id) {
3793 $names[] = CRM_Utils_Array
::value($id, $county);
3797 $inputClause = array();
3798 $county = CRM_Core_PseudoConstant
::county();
3799 foreach ($value as $name) {
3800 $name = trim($name);
3801 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3803 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3806 $this->_tables
['civicrm_address'] = 1;
3807 $this->_whereTables
['civicrm_address'] = 1;
3809 $this->_where
[$grouping][] = $clause;
3811 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3814 return implode(' ' . ts('or') . ' ', $names);
3819 * Where / qill clause for state/province AND country (if present).
3821 * @param array $values
3822 * @param null $status
3826 public function stateProvince(&$values, $status = NULL) {
3827 list($name, $op, $value, $grouping, $wildcard) = $values;
3829 $stateClause = self
::buildClause('civicrm_address.state_province_id', $op, $value, 'Positive');
3830 $this->_tables
['civicrm_address'] = 1;
3831 $this->_whereTables
['civicrm_address'] = 1;
3833 $countryValues = $this->getWhereValues('country', $grouping);
3834 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3835 if ($countryClause) {
3836 $clause = "( $stateClause AND $countryClause )";
3839 $clause = $stateClause;
3842 $this->_where
[$grouping][] = $clause;
3843 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
3845 $this->_qill
[$grouping][] = ts("State/Province %1 %2 %3", array(1 => $qillop, 2 => $qillVal, 3 => $countryQill));
3848 return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill;
3853 * Where / qill clause for change log.
3855 * @param array $values
3857 public function changeLog(&$values) {
3858 list($name, $op, $value, $grouping, $wildcard) = $values;
3860 $targetName = $this->getWhereValues('changed_by', $grouping);
3865 $name = trim($targetName[2]);
3866 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3867 $name = $targetName[4] ?
"%$name%" : $name;
3868 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3869 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3870 $this->_qill
[$grouping][] = ts('Modified By') . " $name";
3876 public function modifiedDates($values) {
3877 $this->_useDistinct
= TRUE;
3879 // CRM-11281, default to added date if not set
3880 $fieldTitle = ts('Added Date');
3881 $fieldName = 'created_date';
3882 foreach (array_keys($this->_params
) as $id) {
3883 if ($this->_params
[$id][0] == 'log_date') {
3884 if ($this->_params
[$id][2] == 2) {
3885 $fieldTitle = ts('Modified Date');
3886 $fieldName = 'modified_date';
3891 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3893 self
::$_openedPanes[ts('Change Log')] = TRUE;
3899 public function demographics(&$values) {
3900 list($name, $op, $value, $grouping, $wildcard) = $values;
3902 if (($name == 'age_low') ||
($name == 'age_high')) {
3903 $this->ageRangeQueryBuilder($values,
3904 'contact_a', 'age', 'birth_date', ts('Age')
3907 elseif (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3909 $this->dateQueryBuilder($values,
3910 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3913 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3915 $this->dateQueryBuilder($values,
3916 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3920 self
::$_openedPanes[ts('Demographics')] = TRUE;
3926 public function privacy(&$values) {
3927 list($name, $op, $value, $grouping, $wildcard) = $values;
3928 //fixed for profile search listing CRM-4633
3929 if (strpbrk($value, "[")) {
3930 $value = "'{$value}'";
3932 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3935 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3937 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3938 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
3939 $title = $field ?
$field['title'] : $name;
3940 $this->_qill
[$grouping][] = "$title $op $value";
3946 public function privacyOptions($values) {
3947 list($name, $op, $value, $grouping, $wildcard) = $values;
3949 if (empty($value) ||
!is_array($value)) {
3953 // get the operator and toggle values
3954 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3957 strtolower($opValues[2] == 'AND')
3962 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3964 if ($toggleValues &&
3965 $toggleValues[2] == 2
3972 foreach ($value as $dontCare => $pOption) {
3973 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
3974 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3975 $title = $field ?
$field['title'] : $pOption;
3976 $qill[] = " $title = 1 ";
3979 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
3980 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
3986 public function preferredCommunication(&$values) {
3987 list($name, $op, $value, $grouping, $wildcard) = $values;
3989 if (!is_array($value)) {
3990 $value = str_replace(array('(', ')'), '', explode(",", $value));
3992 elseif (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3994 $value = $value[$op];
3996 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Contact', $name, $value, $op);
3998 if (self
::caseImportant($op)) {
3999 $value = implode("[[:cntrl:]]|[[:cntrl:]]", (array) $value);
4000 $op = (strstr($op, '!') ||
strstr($op, 'NOT')) ?
'NOT RLIKE' : 'RLIKE';
4001 $value = "[[:cntrl:]]" . $value . "[[:cntrl:]]";
4004 $this->_where
[$grouping][] = self
::buildClause("contact_a.preferred_communication_method", $op, $value);
4005 $this->_qill
[$grouping][] = ts('Preferred Communication Method %1 %2', array(1 => $qillop, 2 => $qillVal));
4009 * Where / qill clause for relationship.
4011 * @param array $values
4013 public function relationship(&$values) {
4014 list($name, $op, $value, $grouping, $wildcard) = $values;
4015 if ($this->_relationshipValuesAdded
) {
4018 // also get values array for relation_target_name
4019 // for relationship search we always do wildcard
4020 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4021 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4022 $relStatus = $this->getWhereValues('relation_status', $grouping);
4023 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4024 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4026 $nameClause = $name = NULL;
4028 $name = trim($targetName[2]);
4029 if (substr($name, 0, 1) == '"' &&
4030 substr($name, -1, 1) == '"'
4032 $name = substr($name, 1, -1);
4033 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4034 $nameClause = "= '$name'";
4037 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4038 $nameClause = "LIKE '%{$name}%'";
4042 $rTypeValues = array();
4043 if (!empty($relationType)) {
4044 $rel = explode('_', $relationType[2]);
4045 self
::$_relType = $rel[1];
4046 $params = array('id' => $rel[0]);
4047 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
4049 if (!empty($rTypeValues) && $rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
4050 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4051 //@todo unless we are dealing with a target group
4052 self
::$_relType = 'reciprocal';
4054 // if we are creating a temp table we build our own where for the relationship table
4055 $relationshipTempTable = NULL;
4056 if (self
::$_relType == 'reciprocal' && empty($targetGroup)) {
4058 self
::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO
::createTempTableName('civicrm_rel');
4060 $where[$grouping][] = " sort_name $nameClause ";
4064 $where = &$this->_where
;
4066 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4070 $allRelationshipType = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE);
4072 if ($nameClause ||
!$targetGroup) {
4073 if (!empty($relationType)) {
4074 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " $name";
4077 $this->_qill
[$grouping][] = $name;
4081 //check to see if the target contact is in specified group
4083 //add contacts from static groups
4084 $this->_tables
['civicrm_relationship_group_contact'] = $this->_whereTables
['civicrm_relationship_group_contact']
4085 = " 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'";
4086 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4087 implode(",", $targetGroup[2]) . ") ) ";
4089 //add contacts from saved searches
4090 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b", $op);
4092 //set the group where clause
4094 $groupWhere[] = "( " . $ssWhere . " )";
4096 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4098 //Get the names of the target groups for the qill
4099 $groupNames = CRM_Core_PseudoConstant
::group();
4100 $qillNames = array();
4101 foreach ($targetGroup[2] as $groupId) {
4102 if (array_key_exists($groupId, $groupNames)) {
4103 $qillNames[] = $groupNames[$groupId];
4106 if (!empty($relationType)) {
4107 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " ( " . implode(", ", $qillNames) . " )";
4110 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4114 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4115 $today = date('Ymd');
4116 //check for active, inactive and all relation status
4117 if ($relStatus[2] == 0) {
4118 $where[$grouping][] = "(
4119 civicrm_relationship.is_active = 1 AND
4120 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4121 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4123 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4125 elseif ($relStatus[2] == 1) {
4126 $where[$grouping][] = "(
4127 civicrm_relationship.is_active = 0 OR
4128 civicrm_relationship.end_date < {$today} OR
4129 civicrm_relationship.start_date > {$today}
4131 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4135 if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
)) {
4138 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4140 //check for permissioned, non-permissioned and all permissioned relations
4141 if ($relPermission[2] == 1) {
4142 $where[$grouping][] = "(
4143 civicrm_relationship.is_permission_a_b = 1
4145 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4147 elseif ($relPermission[2] == 2) {
4148 //non-allowed permission relationship.
4149 $where[$grouping][] = "(
4150 civicrm_relationship.is_permission_a_b = 0
4152 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4155 $this->addRelationshipDateClauses($grouping, $where);
4156 $this->addRelationshipActivePeriodClauses($grouping, $where);
4157 if (!empty($relationType) && !empty($rType) && isset($rType->id
)) {
4158 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
4160 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4161 $this->_useDistinct
= TRUE;
4162 $this->_relationshipValuesAdded
= TRUE;
4163 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4165 // @todo creating a temp table could be expanded to group filter
4166 // as even creating a temp table of all relationships is much much more efficient than
4167 // an OR in the join
4168 if ($relationshipTempTable) {
4170 if (!empty($where[$grouping])) {
4171 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4172 $whereClause = str_replace('contact_b', 'c', $whereClause);
4175 CREATE TEMPORARY TABLE {$relationshipTempTable}
4176 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4177 FROM civicrm_relationship
4178 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4181 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4182 FROM civicrm_relationship
4183 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4186 CRM_Core_DAO
::executeQuery($sql);
4192 * Add start & end date criteria in
4193 * @param string $grouping
4194 * @param array $where
4195 * = array to add where clauses to, in case you are generating a temp table.
4196 * not the main query.
4198 public function addRelationshipDateClauses($grouping, &$where) {
4199 $dateValues = array();
4205 foreach ($dateTypes as $dateField) {
4206 $dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping);
4207 $dateValueHigh = $this->getWhereValues('relation_' . $dateField . '_high', $grouping);
4208 if (!empty($dateValueLow)) {
4209 $date = date('Ymd', strtotime($dateValueLow[2]));
4210 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4211 $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);
4213 if (!empty($dateValueHigh)) {
4214 $date = date('Ymd', strtotime($dateValueHigh[2]));
4215 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4216 $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);
4222 * Add start & end active period criteria in
4223 * @param string $grouping
4224 * @param array $where
4225 * = array to add where clauses to, in case you are generating a temp table.
4226 * not the main query.
4228 public function addRelationshipActivePeriodClauses($grouping, &$where) {
4229 $dateValues = array();
4230 $dateField = 'active_period_date';
4232 $dateValueLow = $this->getWhereValues('relation_active_period_date_low', $grouping);
4233 $dateValueHigh = $this->getWhereValues('relation_active_period_date_high', $grouping);
4234 $dateValueLowFormated = $dateValueHighFormated = NULL;
4235 if (!empty($dateValueLow) && !empty($dateValueHigh)) {
4236 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4237 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4238 $this->_qill
[$grouping][] = (ts('Relationship was active between')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated) . " and " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4240 elseif (!empty($dateValueLow)) {
4241 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4242 $this->_qill
[$grouping][] = (ts('Relationship was active after')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated);
4244 elseif (!empty($dateValueHigh)) {
4245 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4246 $this->_qill
[$grouping][] = (ts('Relationship was active before')) . " " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4249 if ($activePeriodClauses = self
::getRelationshipActivePeriodClauses($dateValueLowFormated, $dateValueHighFormated, TRUE)) {
4250 $where[$grouping][] = $activePeriodClauses;
4255 * Get start & end active period criteria
4257 public static function getRelationshipActivePeriodClauses($from, $to, $forceTableName) {
4258 $tableName = $forceTableName ?
'civicrm_relationship.' : '';
4259 if (!is_null($from) && !is_null($to)) {
4260 return '(((' . $tableName . 'start_date >= ' . $from . ' AND ' . $tableName . 'start_date <= ' . $to . ') OR
4261 (' . $tableName . 'end_date >= ' . $from . ' AND ' . $tableName . 'end_date <= ' . $to . ') OR
4262 (' . $tableName . 'start_date <= ' . $from . ' AND ' . $tableName . 'end_date >= ' . $to . ' )) OR
4263 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4264 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . ') OR
4265 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4267 elseif (!is_null($from)) {
4268 return '((' . $tableName . 'start_date >= ' . $from . ') OR
4269 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4270 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . '))';
4272 elseif (!is_null($to)) {
4273 return '((' . $tableName . 'start_date <= ' . $to . ') OR
4274 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4275 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4280 * Default set of return properties.
4285 * derault return properties
4287 public static function &defaultReturnProperties($mode = 1) {
4288 if (!isset(self
::$_defaultReturnProperties)) {
4289 self
::$_defaultReturnProperties = array();
4292 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4293 // add activity return properties
4294 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4295 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4298 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4301 if (empty(self
::$_defaultReturnProperties[$mode])) {
4302 self
::$_defaultReturnProperties[$mode] = array(
4305 'legal_identifier' => 1,
4306 'external_identifier' => 1,
4307 'contact_type' => 1,
4308 'contact_sub_type' => 1,
4310 'display_name' => 1,
4311 'preferred_mail_format' => 1,
4318 'formal_title' => 1,
4319 'communication_style_id' => 1,
4322 'street_address' => 1,
4323 'supplemental_address_1' => 1,
4324 'supplemental_address_2' => 1,
4325 'supplemental_address_3' => 1,
4328 'postal_code_suffix' => 1,
4329 'state_province' => 1,
4331 'world_region' => 1,
4338 'household_name' => 1,
4339 'organization_name' => 1,
4340 'deceased_date' => 1,
4345 'current_employer' => 1,
4346 // FIXME: should we use defaultHierReturnProperties() for the below?
4347 'do_not_email' => 1,
4350 'do_not_phone' => 1,
4351 'do_not_trade' => 1,
4353 'contact_is_deleted' => 1,
4354 'preferred_communication_method' => 1,
4355 'preferred_language' => 1,
4359 return self
::$_defaultReturnProperties[$mode];
4363 * Get primary condition for a sql clause.
4367 * @return string|NULL
4369 public static function getPrimaryCondition($value) {
4370 if (is_numeric($value)) {
4371 $value = (int ) $value;
4372 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4378 * Wrapper for a simple search query.
4380 * @param array $params
4381 * @param array $returnProperties
4382 * @param bool $count
4386 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4387 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4388 list($select, $from, $where, $having) = $query->query();
4389 $groupBy = ($query->_useGroupBy
) ?
'GROUP BY contact_a.id' : '';
4391 $query = "$select $from $where $groupBy $having";
4396 * These are stub comments as this function needs more explanation - particularly in terms of how it
4397 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4399 * This function was originally written as a wrapper for the api query but is called from multiple places
4400 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4401 * but it is unclear as to whehter that is historical or there is a reason
4402 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4404 * @param array $params
4405 * @param array $returnProperties
4406 * @param null $fields
4407 * @param string $sort
4408 * @param int $offset
4409 * @param int $row_count
4410 * @param bool $smartGroupCache
4411 * ?? update smart group cache?.
4412 * @param bool $count
4413 * Return count obnly.
4414 * @param bool $skipPermissions
4415 * Should permissions be ignored or should the logged in user's permissions be applied.
4417 * This basically correlates to the component.
4418 * @param string $apiEntity
4419 * The api entity being called.
4420 * This sort-of duplicates $mode in a confusing way. Probably not by design.
4424 public static function apiQuery(
4426 $returnProperties = NULL,
4431 $smartGroupCache = TRUE,
4433 $skipPermissions = TRUE,
4434 $mode = CRM_Contact_BAO_Query
::MODE_CONTACTS
,
4438 $query = new CRM_Contact_BAO_Query(
4439 $params, $returnProperties,
4440 NULL, TRUE, FALSE, $mode,
4442 TRUE, $smartGroupCache,
4447 //this should add a check for view deleted if permissions are enabled
4448 if ($skipPermissions) {
4449 $query->_skipDeleteClause
= TRUE;
4451 $query->generatePermissionClause(FALSE, $count);
4453 // note : this modifies _fromClause and _simpleFromClause
4454 $query->includePseudoFieldsJoin($sort);
4456 list($select, $from, $where, $having) = $query->query($count);
4458 $options = $query->_options
;
4459 if (!empty($query->_permissionWhereClause
)) {
4460 if (empty($where)) {
4461 $where = "WHERE $query->_permissionWhereClause";
4464 $where = "$where AND $query->_permissionWhereClause";
4468 $sql = "$select $from $where $having";
4470 // add group by only when API action is not getcount
4471 // otherwise query fetches incorrect count
4472 if ($query->_useGroupBy
&& !$count) {
4473 $sql .= self
::getGroupByFromSelectColumns($query->_select
, 'contact_a.id');
4475 if (!empty($sort)) {
4476 $sort = CRM_Utils_Type
::escape($sort, 'String');
4477 $sql .= " ORDER BY $sort ";
4479 if ($row_count > 0 && $offset >= 0) {
4480 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4481 $row_count = CRM_Utils_Type
::escape($row_count, 'Int');
4482 $sql .= " LIMIT $offset, $row_count ";
4485 $dao = CRM_Core_DAO
::executeQuery($sql);
4487 // @todo derive this from the component class rather than hard-code two options.
4488 $entityIDField = ($mode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) ?
'contribution_id' : 'contact_id';
4491 while ($dao->fetch()) {
4493 $noRows = $dao->rowCount
;
4495 return array($noRows, NULL);
4497 $val = $query->store($dao);
4498 $convertedVals = $query->convertToPseudoNames($dao, TRUE, TRUE);
4500 if (!empty($convertedVals)) {
4501 $val = array_replace_recursive($val, $convertedVals);
4503 $values[$dao->$entityIDField] = $val;
4506 return array($values, $options);
4510 * Get the actual custom field name by stripping off the appended string.
4512 * The string could be _relative, _from, or _to
4514 * @todo use metadata rather than convention to do this.
4516 * @param string $parameterName
4517 * The name of the parameter submitted to the form.
4524 public static function getCustomFieldName($parameterName) {
4525 if (substr($parameterName, -5, 5) == '_from') {
4526 return substr($parameterName, 0, strpos($parameterName, '_from'));
4528 if (substr($parameterName, -9, 9) == '_relative') {
4529 return substr($parameterName, 0, strpos($parameterName, '_relative'));
4531 if (substr($parameterName, -3, 3) == '_to') {
4532 return substr($parameterName, 0, strpos($parameterName, '_to'));
4537 * Convert submitted values for relative custom fields to query object format.
4539 * The query will support the sqlOperator format so convert to that format.
4541 * @param array $formValues
4543 * @param array $params
4544 * Converted parameters for the query object.
4545 * @param string $values
4547 * @param string $fieldName
4548 * Submitted field name. (Matches form field not DB field.)
4550 protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) {
4551 if (empty($values)) {
4552 // e.g we might have relative set & from & to empty. The form flow is a bit funky &
4553 // this function gets called again after they fields have been converted which can get ugly.
4556 $customFieldName = self
::getCustomFieldName($fieldName);
4558 if (substr($fieldName, -9, 9) == '_relative') {
4559 list($from, $to) = CRM_Utils_Date
::getFromTo($values, NULL, NULL);
4562 if ($fieldName == $customFieldName . '_to' && CRM_Utils_Array
::value($customFieldName . '_from', $formValues)) {
4563 // Both to & from are set. We only need to acton one, choosing from.
4567 $from = CRM_Utils_Array
::value($customFieldName . '_from', $formValues, NULL);
4568 $to = CRM_Utils_Array
::value($customFieldName . '_to', $formValues, NULL);
4570 if (self
::isCustomDateField($customFieldName)) {
4571 list($from, $to) = CRM_Utils_Date
::getFromTo(NULL, $from, $to);
4577 $relativeFunction = array('BETWEEN' => array($from, $to));
4580 $relativeFunction = array('>=' => $from);
4584 $relativeFunction = array('<=' => $to);
4596 * Are we dealing with custom field of type date.
4602 public static function isCustomDateField($fieldName) {
4603 if (($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($fieldName)) == FALSE) {
4606 if ('Date' == civicrm_api3('CustomField', 'getvalue', array('id' => $customFieldID, 'return' => 'data_type'))) {
4613 * Has this field already been reformatting to Query object syntax.
4615 * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems
4616 * to come with associated double queries & is possibly damaging performance.
4618 * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns
4621 * @param mixed $values
4622 * Value in formValues for the field.
4626 public static function isAlreadyProcessedForQueryFormat($values) {
4627 if (!is_array($values)) {
4630 if (($operator = CRM_Utils_Array
::value(1, $values)) == FALSE) {
4633 return in_array($operator, CRM_Core_DAO
::acceptedSQLOperators());
4637 * If the state and country are passed remove state.
4639 * Country is implicit from the state, but including both results in
4640 * a poor query as there is no combined index on state AND country.
4644 * @param array $formValues
4646 public static function filterCountryFromValuesIfStateExists(&$formValues) {
4647 if (!empty($formValues['country']) && !empty($formValues['state_province'])) {
4648 // The use of array map sanitises the data by ensuring we are dealing with integers.
4649 $states = implode(', ', array_map('intval', $formValues['state_province']));
4650 $countryList = CRM_Core_DAO
::singleValueQuery(
4651 "SELECT GROUP_CONCAT(country_id) FROM civicrm_state_province WHERE id IN ($states)"
4653 if ($countryList == $formValues['country']) {
4654 unset($formValues['country']);
4660 * For some special cases, grouping by subset of select fields becomes mandatory.
4661 * Hence, full_group_by mode is handled by appending any_value
4662 * keyword to select fields not present in groupBy
4664 * @param array $selectClauses
4665 * @param array $groupBy - Columns already included in GROUP By clause.
4669 public static function appendAnyValueToSelect($selectClauses, $groupBy) {
4670 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4671 $sqlMode = explode(',', CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode'));
4673 // Disable only_full_group_by mode for lower sql versions.
4674 if (version_compare($mysqlVersion, '5.7', '<') ||
(!empty($sqlMode) && !in_array('ONLY_FULL_GROUP_BY', $sqlMode))) {
4675 $key = array_search('ONLY_FULL_GROUP_BY', $sqlMode);
4676 unset($sqlMode[$key]);
4677 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = '" . implode(',', $sqlMode) . "'");
4680 $groupBy = array_map('trim', (array) $groupBy);
4681 $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN)\(/i';
4682 foreach ($selectClauses as $key => &$val) {
4683 list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL);
4684 // append ANY_VALUE() keyword
4685 if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) {
4686 $val = str_replace($selectColumn, "ANY_VALUE({$selectColumn})", $val);
4691 return "SELECT " . implode(', ', $selectClauses) . " ";
4695 * Include Select columns in groupBy clause.
4697 * @param array $selectClauses
4698 * @param array $groupBy - Columns already included in GROUP By clause.
4702 public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NULL) {
4703 $groupBy = (array) $groupBy;
4704 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4705 $sqlMode = CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode');
4707 //return if ONLY_FULL_GROUP_BY is not enabled.
4708 if (!version_compare($mysqlVersion, '5.7', '<') && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
4709 $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN)\(/i';
4710 foreach ($selectClauses as $key => $val) {
4711 $aliasArray = preg_split('/ as /i', $val);
4712 // if more than 1 alias we need to split by ','.
4713 if (count($aliasArray) > 2) {
4714 $aliasArray = preg_split('/,/', $val);
4715 foreach ($aliasArray as $key => $value) {
4716 $alias = current(preg_split('/ as /i', $value));
4717 if (!in_array($alias, $groupBy) && preg_match($regexToExclude, trim($alias)) !== 1) {
4718 $groupBy[] = $alias;
4723 list($selectColumn, $alias) = array_pad($aliasArray, 2, NULL);
4724 $dateRegex = '/^(DATE_FORMAT|DATE_ADD|CASE)/i';
4725 $tableName = current(explode('.', $selectColumn));
4726 $primaryKey = "{$tableName}.id";
4727 // exclude columns which are already included in groupBy and aggregate functions from select
4728 // CRM-18439 - Also exclude the columns which are functionally dependent on columns in $groupBy (MySQL 5.7+)
4729 if (!in_array($selectColumn, $groupBy) && !in_array($primaryKey, $groupBy) && preg_match($regexToExclude, trim($selectColumn)) !== 1) {
4730 if (!empty($alias) && preg_match($dateRegex, trim($selectColumn))) {
4731 $groupBy[] = $alias;
4734 $groupBy[] = $selectColumn;
4741 if (!empty($groupBy)) {
4742 return " GROUP BY " . implode(', ', $groupBy);
4748 * Create and query the db for an contact search.
4750 * @param int $offset
4751 * The offset for the query.
4752 * @param int $rowCount
4753 * The number of rows to return.
4754 * @param string|CRM_Utils_Sort $sort
4755 * The order by string.
4756 * @param bool $count
4757 * Is this a count only query ?.
4758 * @param bool $includeContactIds
4759 * Should we include contact ids?.
4760 * @param bool $sortByChar
4761 * If true returns the distinct array of first characters for search results.
4762 * @param bool $groupContacts
4763 * If true, return only the contact ids.
4764 * @param bool $returnQuery
4765 * Should we return the query as a string.
4766 * @param string $additionalWhereClause
4767 * If the caller wants to further restrict the search (used for components).
4768 * @param null $sortOrder
4769 * @param string $additionalFromClause
4770 * Should be clause with proper joins, effective to reduce where clause load.
4772 * @param bool $skipOrderAndLimit
4774 * @return CRM_Core_DAO
4776 public function searchQuery(
4777 $offset = 0, $rowCount = 0, $sort = NULL,
4778 $count = FALSE, $includeContactIds = FALSE,
4779 $sortByChar = FALSE, $groupContacts = FALSE,
4780 $returnQuery = FALSE,
4781 $additionalWhereClause = NULL, $sortOrder = NULL,
4782 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4785 if ($includeContactIds) {
4786 $this->_includeContactIds
= TRUE;
4787 $this->_whereClause
= $this->whereClause();
4790 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4792 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4793 // and that contact happens to be deleted, set $onlyDeleted to true
4794 foreach ($this->_params
as $values) {
4795 $name = CRM_Utils_Array
::value(0, $values);
4796 $op = CRM_Utils_Array
::value(1, $values);
4797 $value = CRM_Utils_Array
::value(2, $values);
4798 if ($name == 'contact_id' and $op == '=') {
4799 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4800 $onlyDeleted = TRUE;
4806 // building the query string
4807 $groupBy = $groupByCol = NULL;
4809 if (isset($this->_groupByComponentClause
)) {
4810 $groupBy = $this->_groupByComponentClause
;
4811 $groupCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause
));
4812 $groupByCol = explode(', ', $groupCols);
4814 elseif ($this->_useGroupBy
) {
4815 $groupByCol = 'contact_a.id';
4816 $groupBy = ' GROUP BY contact_a.id';
4819 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4820 $groupByCol = 'civicrm_activity.id';
4821 $groupBy = 'GROUP BY civicrm_activity.id ';
4824 $order = $orderBy = $limit = '';
4826 list($order, $additionalFromClause) = $this->prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause);
4828 if ($rowCount > 0 && $offset >= 0) {
4829 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4830 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4831 $limit = " LIMIT $offset, $rowCount ";
4836 $this->_sort
= $sort;
4839 $this->includePseudoFieldsJoin($sort);
4841 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4843 if (!empty($groupByCol)) {
4844 $groupBy = self
::getGroupByFromSelectColumns($this->_select
, $groupByCol);
4847 if ($additionalWhereClause) {
4848 $where = $where . ' AND ' . $additionalWhereClause;
4851 //additional from clause should be w/ proper joins.
4852 if ($additionalFromClause) {
4853 $from .= "\n" . $additionalFromClause;
4856 // if we are doing a transform, do it here
4857 // use the $from, $where and $having to get the contact ID
4858 if ($this->_displayRelationshipType
) {
4859 $this->filterRelatedContacts($from, $where, $having);
4862 if ($skipOrderAndLimit) {
4863 $query = "$select $from $where $having $groupBy";
4866 $query = "$select $from $where $having $groupBy $order $limit";
4873 return CRM_Core_DAO
::singleValueQuery($query);
4876 $dao = CRM_Core_DAO
::executeQuery($query);
4877 if ($groupContacts) {
4879 while ($dao->fetch()) {
4883 return implode(',', $ids);
4890 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4892 * @param string $cacheKey
4893 * @param int $offset
4894 * @param int $rowCount
4895 * @param bool $includeContactIds
4896 * @return CRM_Core_DAO
4898 public function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4899 $this->_includeContactIds
= $includeContactIds;
4900 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4901 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
4902 $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);
4903 $order = " ORDER BY pnc.id";
4904 $groupByCol = array('contact_a.id', 'pnc.id');
4905 $groupBy = self
::getGroupByFromSelectColumns($this->_select
, $groupByCol);
4906 $limit = " LIMIT $offset, $rowCount";
4907 $query = "$select $from $where $groupBy $order $limit";
4909 return CRM_Core_DAO
::executeQuery($query);
4913 * Populate $this->_permissionWhereClause with permission related clause and update other
4914 * query related properties.
4916 * Function calls ACL permission class and hooks to filter the query appropriately
4918 * Note that these 2 params were in the code when extracted from another function
4919 * and a second round extraction would be to make them properties of the class
4921 * @param bool $onlyDeleted
4922 * Only get deleted contacts.
4923 * @param bool $count
4924 * Return Count only.
4926 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4927 if (!$this->_skipPermission
) {
4928 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4929 CRM_Core_Permission
::VIEW
,
4931 $this->_whereTables
,
4934 $this->_skipDeleteClause
4937 // regenerate fromClause since permission might have added tables
4938 if ($this->_permissionWhereClause
) {
4939 //fix for row count in qill (in contribute/membership find)
4941 $this->_useDistinct
= TRUE;
4944 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4945 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4946 // note : this modifies _fromClause and _simpleFromClause
4947 $this->includePseudoFieldsJoin($this->_sort
);
4951 // add delete clause if needed even if we are skipping permission
4953 if (!$this->_skipDeleteClause
) {
4954 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4955 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4959 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4968 public function setSkipPermission($val) {
4969 $this->_skipPermission
= $val;
4973 * @param null $context
4977 public function &summaryContribution($context = NULL) {
4978 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4982 SELECT COUNT( conts.total_amount ) as total_count,
4983 SUM( conts.total_amount ) as total_amount,
4984 AVG( conts.total_amount ) as total_avg,
4985 conts.currency as currency";
4986 if ($this->_permissionWhereClause
) {
4987 $where .= " AND " . $this->_permissionWhereClause
;
4989 if ($context == 'search') {
4990 $where .= " AND contact_a.is_deleted = 0 ";
4992 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4993 if (!empty($financialTypes)) {
4994 $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
4995 $from .= " LEFT JOIN civicrm_line_item li
4996 ON civicrm_contribution.id = li.contribution_id AND
4997 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
5000 $where .= " AND civicrm_contribution.financial_type_id IN (0)";
5003 // make sure contribution is completed - CRM-4989
5004 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
5007 $summary['total'] = array();
5008 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
5009 $innerQuery = "SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
5010 civicrm_contribution.currency $from $completedWhere";
5011 $query = "$select FROM (
5012 $innerQuery GROUP BY civicrm_contribution.id
5016 $dao = CRM_Core_DAO
::executeQuery($query);
5018 $summary['total']['count'] = 0;
5019 $summary['total']['amount'] = $summary['total']['avg'] = array();
5020 while ($dao->fetch()) {
5021 $summary['total']['count'] +
= $dao->total_count
;
5022 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
5023 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
5026 $orderBy = 'ORDER BY civicrm_contribution_total_amount_count DESC';
5027 $groupBy = 'GROUP BY currency, civicrm_contribution.total_amount';
5028 $modeSQL = "$select, SUBSTRING_INDEX(GROUP_CONCAT(conts.total_amount
5029 ORDER BY conts.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
5030 MAX(conts.civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count
5032 $groupBy $orderBy) as conts
5035 $summary['total']['mode'] = CRM_Contribute_BAO_Contribution
::computeStats('mode', $modeSQL);
5037 $medianSQL = "{$from} {$completedWhere}";
5038 $summary['total']['median'] = CRM_Contribute_BAO_Contribution
::computeStats('median', $medianSQL, 'civicrm_contribution');
5039 $summary['total']['currencyCount'] = count($summary['total']['median']);
5041 if (!empty($summary['total']['amount'])) {
5042 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
5043 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
5044 $summary['total']['mode'] = implode(', ', $summary['total']['mode']);
5045 $summary['total']['median'] = implode(', ', $summary['total']['median']);
5048 $summary['total']['amount'] = $summary['total']['avg'] = $summary['total']['median'] = 0;
5051 // soft credit summary
5052 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
5053 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
5056 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
5057 GROUP BY civicrm_contribution_soft.id
5060 $dao = CRM_Core_DAO
::executeQuery($query);
5061 $summary['soft_credit']['count'] = 0;
5062 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
5063 while ($dao->fetch()) {
5064 $summary['soft_credit']['count'] +
= $dao->total_count
;
5065 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
5066 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
5068 if (!empty($summary['soft_credit']['amount'])) {
5069 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
5070 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
5073 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
5078 //@todo - this could be one query using the IF in mysql - eg
5079 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
5080 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
5081 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
5082 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
5083 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
5084 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
5085 // FROM civicrm_contact contact_a
5086 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
5087 // WHERE ( ... where clause....
5088 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
5092 SELECT COUNT( conts.total_amount ) as cancel_count,
5093 SUM( conts.total_amount ) as cancel_amount,
5094 AVG( conts.total_amount ) as cancel_avg,
5095 conts.currency as currency";
5097 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
5098 if ($context == 'search') {
5099 $where .= " AND contact_a.is_deleted = 0 ";
5102 $query = "$select FROM (
5103 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
5104 GROUP BY civicrm_contribution.id
5108 $dao = CRM_Core_DAO
::executeQuery($query);
5111 if ($dao->fetch()) {
5112 $summary['cancel']['count'] = $dao->cancel_count
;
5113 $summary['cancel']['amount'] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
5114 $summary['cancel']['avg'] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
5118 $summary['cancel']['count'] = 0;
5119 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
5120 while ($dao->fetch()) {
5121 $summary['cancel']['count'] +
= $dao->cancel_count
;
5122 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
5123 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
5125 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
5126 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
5133 * Getter for the qill object.
5137 public function qill() {
5138 return $this->_qill
;
5142 * Default set of return default hier return properties.
5146 public static function &defaultHierReturnProperties() {
5147 if (!isset(self
::$_defaultHierReturnProperties)) {
5148 self
::$_defaultHierReturnProperties = array(
5151 'legal_identifier' => 1,
5152 'external_identifier' => 1,
5153 'contact_type' => 1,
5154 'contact_sub_type' => 1,
5156 'display_name' => 1,
5163 'formal_title' => 1,
5164 'communication_style_id' => 1,
5165 'email_greeting' => 1,
5166 'postal_greeting' => 1,
5170 'preferred_communication_method' => 1,
5171 'do_not_phone' => 1,
5172 'do_not_email' => 1,
5175 'do_not_trade' => 1,
5176 'location' => array(
5178 'location_type' => 1,
5179 'street_address' => 1,
5181 'state_province' => 1,
5183 'postal_code_suffix' => 1,
5186 'phone-Mobile' => 1,
5199 'location_type' => 1,
5200 'street_address' => 1,
5202 'state_province' => 1,
5204 'postal_code_suffix' => 1,
5207 'phone-Mobile' => 1,
5221 return self
::$_defaultHierReturnProperties;
5225 * Build query for a date field.
5227 * @param array $values
5228 * @param string $tableName
5229 * @param string $fieldName
5230 * @param string $dbFieldName
5231 * @param string $fieldTitle
5232 * @param bool $appendTimeStamp
5233 * @param string $dateFormat
5235 public function dateQueryBuilder(
5236 &$values, $tableName, $fieldName,
5237 $dbFieldName, $fieldTitle,
5238 $appendTimeStamp = TRUE,
5239 $dateFormat = 'YmdHis'
5241 list($name, $op, $value, $grouping, $wildcard) = $values;
5243 if ($name == "{$fieldName}_low" ||
5244 $name == "{$fieldName}_high"
5246 if (isset($this->_rangeCache
[$fieldName]) ||
!$value) {
5249 $this->_rangeCache
[$fieldName] = 1;
5251 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
5253 if ($name == $fieldName . '_low') {
5255 $firstPhrase = ts('greater than or equal to');
5256 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5258 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5259 if (!empty($secondValues) && $secondValues[2]) {
5261 $secondPhrase = ts('less than or equal to');
5262 $secondValue = $secondValues[2];
5264 if ($appendTimeStamp && strlen($secondValue) == 10) {
5265 $secondValue .= ' 23:59:59';
5267 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5270 elseif ($name == $fieldName . '_high') {
5272 $firstPhrase = ts('less than or equal to');
5274 if ($appendTimeStamp && strlen($value) == 10) {
5275 $value .= ' 23:59:59';
5277 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5279 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5280 if (!empty($secondValues) && $secondValues[2]) {
5282 $secondPhrase = ts('greater than or equal to');
5283 $secondValue = $secondValues[2];
5284 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5288 if (!$appendTimeStamp) {
5289 $firstDate = substr($firstDate, 0, 8);
5291 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5294 if (!$appendTimeStamp) {
5295 $secondDate = substr($secondDate, 0, 8);
5297 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5300 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5302 $this->_where
[$grouping][] = "
5303 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5304 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5306 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5309 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5310 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5314 if ($name == $fieldName) {
5315 //In Get API, for operators other then '=' the $value is in array(op => value) format
5316 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5318 $value = $value[$op];
5321 $date = $format = NULL;
5322 if (strstr($op, 'IN')) {
5324 foreach ($value as &$date) {
5325 $date = CRM_Utils_Date
::processDate($date, NULL, FALSE, $dateFormat);
5326 if (!$appendTimeStamp) {
5327 $date = substr($date, 0, 8);
5329 $format[] = CRM_Utils_Date
::customFormat($date);
5331 $date = "('" . implode("','", $value) . "')";
5332 $format = implode(', ', $format);
5334 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5335 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5336 if (!$appendTimeStamp) {
5337 $date = substr($date, 0, 8);
5339 $format = CRM_Utils_Date
::customFormat($date);
5344 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5347 $this->_where
[$grouping][] = self
::buildClause("{$tableName}.{$dbFieldName}", $op);
5350 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5352 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
5353 $this->_qill
[$grouping][] = "$fieldTitle $op $format";
5359 * @param string $tableName
5360 * @param string $fieldName
5361 * @param string $dbFieldName
5362 * @param $fieldTitle
5363 * @param null $options
5365 public function numberRangeBuilder(
5367 $tableName, $fieldName,
5368 $dbFieldName, $fieldTitle,
5371 list($name, $op, $value, $grouping, $wildcard) = $values;
5373 if ($name == "{$fieldName}_low" ||
5374 $name == "{$fieldName}_high"
5376 if (isset($this->_rangeCache
[$fieldName])) {
5379 $this->_rangeCache
[$fieldName] = 1;
5381 $secondOP = $secondPhrase = $secondValue = NULL;
5383 if ($name == "{$fieldName}_low") {
5385 $firstPhrase = ts('greater than');
5387 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5388 if (!empty($secondValues)) {
5390 $secondPhrase = ts('less than');
5391 $secondValue = $secondValues[2];
5396 $firstPhrase = ts('less than');
5398 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5399 if (!empty($secondValues)) {
5401 $secondPhrase = ts('greater than');
5402 $secondValue = $secondValues[2];
5407 $this->_where
[$grouping][] = "
5408 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5409 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5411 $displayValue = $options ?
$options[$value] : $value;
5412 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5414 $this->_qill
[$grouping][]
5415 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5418 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5419 $displayValue = $options ?
$options[$value] : $value;
5420 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5422 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5427 if ($name == $fieldName) {
5431 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5433 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5434 $displayValue = $options ?
$options[$value] : $value;
5435 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5442 * @param string $tableName
5443 * @param string $fieldName
5444 * @param string $dbFieldName
5445 * @param $fieldTitle
5446 * @param null $options
5448 public function ageRangeQueryBuilder(
5450 $tableName, $fieldName,
5451 $dbFieldName, $fieldTitle,
5454 list($name, $op, $value, $grouping, $wildcard) = $values;
5456 $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
5457 $asofDate = NULL; // will be treated as current day
5458 if ($asofDateValues) {
5459 $asofDate = CRM_Utils_Date
::processDate($asofDateValues[2]);
5460 $asofDateFormat = CRM_Utils_Date
::customFormat(substr($asofDate, 0, 8));
5461 $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat;
5464 if ($name == "{$fieldName}_low" ||
5465 $name == "{$fieldName}_high"
5467 if (isset($this->_rangeCache
[$fieldName])) {
5470 $this->_rangeCache
[$fieldName] = 1;
5472 $secondOP = $secondPhrase = $secondValue = NULL;
5474 if ($name == "{$fieldName}_low") {
5475 $firstPhrase = ts('greater than or equal to');
5476 // NB: age > X means date of birth < Y
5478 $firstDate = self
::calcDateFromAge($asofDate, $value, 'min');
5480 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5481 if (!empty($secondValues)) {
5483 $secondPhrase = ts('less than or equal to');
5484 $secondValue = $secondValues[2];
5485 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'max');
5490 $firstPhrase = ts('less than or equal to');
5491 $firstDate = self
::calcDateFromAge($asofDate, $value, 'max');
5493 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5494 if (!empty($secondValues)) {
5496 $secondPhrase = ts('greater than or equal to');
5497 $secondValue = $secondValues[2];
5498 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'min');
5503 $this->_where
[$grouping][] = "
5504 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5505 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5507 $displayValue = $options ?
$options[$value] : $value;
5508 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5510 $this->_qill
[$grouping][]
5511 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5514 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5515 $displayValue = $options ?
$options[$value] : $value;
5516 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5518 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5524 * Calculate date from age.
5526 * @param string $asofDate
5528 * @param string $type
5532 public static function calcDateFromAge($asofDate, $age, $type) {
5533 $date = new DateTime($asofDate);
5534 if ($type == "min") {
5535 // minimum age is $age: dob <= date - age "235959"
5536 $date->sub(new DateInterval("P" . $age . "Y"));
5537 return $date->format('Ymd') . "235959";
5540 // max age is $age: dob >= date - (age + 1y) + 1d "000000"
5541 $date->sub(new DateInterval("P" . ($age +
1) . "Y"))->add(new DateInterval("P1D"));
5542 return $date->format('Ymd') . "000000";
5547 * Given the field name, operator, value & its data type
5548 * builds the where Clause for the query
5549 * used for handling 'IS NULL'/'IS NOT NULL' operators
5551 * @param string $field
5555 * @param string $value
5557 * @param string $dataType
5558 * Data type of the field.
5561 * Where clause for the query.
5563 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5565 $clause = "$field $op";
5573 $clause = " (NULLIF($field, '') IS NULL) ";
5576 case 'IS NOT EMPTY':
5577 $clause = " (NULLIF($field, '') IS NOT NULL) ";
5582 // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
5583 if (!empty($value) && (!is_array($value) ||
!array_key_exists($op, $value))) {
5584 $value = array($op => (array) $value);
5588 if (empty($dataType)) {
5589 $dataType = 'String';
5591 if (is_array($value)) {
5592 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5593 // widely used and consistent across the codebase
5594 // adding this here won't accept the search functions which don't submit an array
5595 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, $value, $dataType)) != FALSE) {
5597 return $queryString;
5600 // 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))
5601 // but we got only array(2,5) from the form.
5602 // We could get away with keeping this in 4.6 if we make it such that it throws an enotice in 4.7 so
5603 // people have to de-slopify it.
5604 if (!empty($value[0])) {
5605 if ($op != 'BETWEEN') {
5606 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReport;
5608 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => $value), $dataType)) != FALSE) {
5609 return $queryString;
5614 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReportUsingOldFormat;
5615 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => array_keys($value)), $dataType)) != FALSE) {
5616 return $queryString;
5621 $value = CRM_Utils_Type
::escape($value, $dataType);
5622 // if we don't have a dataType we should assume
5623 if ($dataType == 'String' ||
$dataType == 'Text') {
5624 $value = "'" . strtolower($value) . "'";
5626 return "$clause $value";
5631 * @param bool $reset
5635 public function openedSearchPanes($reset = FALSE) {
5636 if (!$reset ||
empty($this->_whereTables
)) {
5637 return self
::$_openedPanes;
5640 // pane name to table mapper
5641 $panesMapper = array(
5642 ts('Contributions') => 'civicrm_contribution',
5643 ts('Memberships') => 'civicrm_membership',
5644 ts('Events') => 'civicrm_participant',
5645 ts('Relationships') => 'civicrm_relationship',
5646 ts('Activities') => 'civicrm_activity',
5647 ts('Pledges') => 'civicrm_pledge',
5648 ts('Cases') => 'civicrm_case',
5649 ts('Grants') => 'civicrm_grant',
5650 ts('Address Fields') => 'civicrm_address',
5651 ts('Notes') => 'civicrm_note',
5652 ts('Change Log') => 'civicrm_log',
5653 ts('Mailings') => 'civicrm_mailing',
5655 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5657 foreach (array_keys($this->_whereTables
) as $table) {
5658 if ($panName = array_search($table, $panesMapper)) {
5659 self
::$_openedPanes[$panName] = TRUE;
5663 return self
::$_openedPanes;
5669 public function setOperator($operator) {
5670 $validOperators = array('AND', 'OR');
5671 if (!in_array($operator, $validOperators)) {
5674 $this->_operator
= $operator;
5680 public function getOperator() {
5681 return $this->_operator
;
5689 public function filterRelatedContacts(&$from, &$where, &$having) {
5690 static $_rTypeProcessed = NULL;
5691 static $_rTypeFrom = NULL;
5692 static $_rTypeWhere = NULL;
5694 if (!$_rTypeProcessed) {
5695 $_rTypeProcessed = TRUE;
5697 // create temp table with contact ids
5698 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5699 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5700 CRM_Core_DAO
::executeQuery($sql);
5703 REPLACE INTO $tableName ( contact_id )
5709 CRM_Core_DAO
::executeQuery($sql);
5711 $qillMessage = ts('Contacts with a Relationship Type of: ');
5712 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5714 if (is_numeric($this->_displayRelationshipType
)) {
5715 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5717 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5718 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5721 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5722 AND displayRelType.is_active = 1
5726 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5727 if ($dirOne == 'a') {
5728 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5730 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5731 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5735 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5737 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5738 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5742 WHERE displayRelType.relationship_type_id = $relType
5743 AND displayRelType.is_active = 1
5746 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5749 if (!empty($this->_permissionWhereClause
)) {
5750 $_rTypeWhere .= "AND $this->_permissionWhereClause";
5753 if (strpos($from, $_rTypeFrom) === FALSE) {
5754 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5755 // this happens when we have an event_type in the quert (CRM-7969)
5756 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5757 $from .= $_rTypeFrom;
5758 $where = $_rTypeWhere;
5765 * See CRM-19811 for why this is database hurty without apparent benefit.
5771 public static function caseImportant($op) {
5773 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5777 * @param $returnProperties
5782 public static function componentPresent(&$returnProperties, $prefix) {
5783 foreach ($returnProperties as $name => $dontCare) {
5784 if (substr($name, 0, strlen($prefix)) == $prefix) {
5792 * Builds the necessary structures for all fields that are similar to option value look-ups.
5794 * @param string $name
5795 * the name of the field.
5797 * the sql operator, this function should handle ALL SQL operators.
5798 * @param string $value
5799 * depends on the operator and who's calling the query builder.
5800 * @param int $grouping
5801 * the index where to place the where clause.
5802 * @param string $daoName
5804 * @param array $field
5805 * an array that contains various properties of the field identified by $name.
5806 * @param string $label
5807 * The label for this field element.
5808 * @param string $dataType
5809 * The data type for this element.
5810 * @param bool $useIDsOnly
5812 public function optionValueQuery(
5820 $dataType = 'String',
5824 $pseudoFields = array(
5831 'communication_style_id',
5835 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5836 if ($tableName == 'civicrm_contact') {
5837 $wc = "contact_a.$fieldName";
5840 $wc = "$tableName.id";
5844 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
5845 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5847 if (in_array($name, $pseudoFields)) {
5848 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5849 $wc = "contact_a.{$name}_id";
5851 $dataType = 'Positive';
5852 $value = (!$value) ?
0 : $value;
5854 if ($name == "world_region") {
5855 $field['name'] = $name;
5858 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue($daoName, $field['name'], $value, $op);
5859 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillop, 3 => $qillVal));
5860 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5864 * Check and explode a user defined numeric string into an array
5865 * this was the protocol used by search builder in the old old days before we had
5866 * super nice js widgets to do the hard work
5868 * @param string $string
5869 * @param string $dataType
5870 * The dataType we should check for the values, default integer.
5872 * @return bool|array
5873 * false if string does not match the pattern
5874 * array of numeric values if string does match the pattern
5876 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5877 $string = trim($string);
5878 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5882 $string = substr($string, 1, -1);
5883 $values = explode(',', $string);
5884 if (empty($values)) {
5888 $returnValues = array();
5889 foreach ($values as $v) {
5890 if ($dataType == 'Integer' && !is_numeric($v)) {
5893 elseif ($dataType == 'String' && !is_string($v)) {
5896 $returnValues[] = trim($v);
5899 if (empty($returnValues)) {
5903 return $returnValues;
5907 * Convert the pseudo constants id's to their names
5909 * @param CRM_Core_DAO $dao
5910 * @param bool $return
5911 * @param bool $usedForAPI
5913 * @return array|NULL
5915 public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) {
5916 if (empty($this->_pseudoConstantsSelect
)) {
5920 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5921 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5925 if (is_object($dao) && property_exists($dao, $value['idCol'])) {
5926 $val = $dao->{$value['idCol']};
5927 if ($key == 'groups') {
5928 $dao->groups
= $this->convertGroupIDStringToLabelString($dao, $val);
5932 if (CRM_Utils_System
::isNull($val)) {
5935 elseif (!empty($value['pseudoconstant'])) {
5936 // If pseudoconstant is set that is kind of defacto for 'we have a bit more info about this'
5937 // and we can use the metadata to figure it out.
5938 // ideally this bit of IF will absorb & replace all the rest in time as we move to
5939 // more metadata based choices.
5940 if (strpos($val, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
5941 $dbValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($val, CRM_Core_DAO
::VALUE_SEPARATOR
));
5942 foreach ($dbValues as $pseudoValue) {
5943 $convertedValues[] = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $pseudoValue);
5946 $dao->$key = ($usedForAPI) ?
$convertedValues : implode(', ', $convertedValues);
5947 $realFieldName = CRM_Utils_Array
::value('field_name', $this->_pseudoConstantsSelect
[$key]);
5948 if ($usedForAPI && $realFieldName) {
5949 // normally we would see 2 fields returned for pseudoConstants. An exception is
5950 // preferred_communication_method where there is no id-variant.
5951 // For the api we prioritise getting the real data returned.
5952 // over the resolved version
5953 $dao->$realFieldName = $dbValues;
5958 // This is basically the same as the default but since we have the bao we can use
5959 // a cached function.
5960 $dao->$key = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $val);
5963 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5965 $idColumn = "{$key}_id";
5966 $dao->$idColumn = $val;
5968 if ($key == 'state_province_name') {
5969 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::stateProvince($val);
5972 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5975 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5976 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5978 // @todo handle this in the section above for pseudoconstants.
5979 elseif (in_array($value['pseudoField'], array('participant_role_id', 'participant_role'))) {
5980 // @todo define bao on this & merge into the above condition.
5981 $viewValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val);
5983 if ($value['pseudoField'] == 'participant_role') {
5984 $pseudoOptions = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'role_id');
5985 foreach ($viewValues as $k => $v) {
5986 $viewValues[$k] = $pseudoOptions[$v];
5989 $dao->$key = ($usedForAPI && count($viewValues) > 1) ?
$viewValues : implode(', ', $viewValues);
5992 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5993 $dao->$key = $labels[$val];
5996 // return converted values in array format
5998 if (strpos($key, '-') !== FALSE) {
5999 $keyVal = explode('-', $key);
6000 $current = &$values;
6001 $lastElement = array_pop($keyVal);
6002 foreach ($keyVal as $v) {
6003 if (!array_key_exists($v, $current)) {
6004 $current[$v] = array();
6006 $current = &$current[$v];
6008 $current[$lastElement] = $dao->$key;
6011 $values[$key] = $dao->$key;
6018 'gender_id' => 'gender',
6019 'prefix_id' => 'individual_prefix',
6020 'suffix_id' => 'individual_suffix',
6021 'communication_style_id' => 'communication_style',
6022 ) as $realField => $labelField) {
6023 // This is a temporary routine for handling these fields while
6024 // we figure out how to handled them based on metadata in
6025 /// export and search builder. CRM-19815, CRM-19830.
6026 if (isset($dao->$realField) && is_numeric($dao->$realField) && isset($dao->$labelField)) {
6027 $dao->$realField = $dao->$labelField;
6035 * Include pseudo fields LEFT JOIN.
6036 * @param string|array $sort can be a object or string
6038 * @return array|NULL
6040 public function includePseudoFieldsJoin($sort) {
6041 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
6044 $sort = is_string($sort) ?
$sort : $sort->orderBy();
6047 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
6048 if (!empty($value['table'])) {
6049 $regex = "/({$value['table']}\.|{$name})/";
6050 if (preg_match($regex, $sort)) {
6051 $this->_elemnt
[$value['element']] = 1;
6052 $this->_select
[$value['element']] = $value['select'];
6053 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
6054 $present[$value['table']] = $value['join'];
6058 $presentSimpleFrom = $present;
6060 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
6061 array_key_exists('civicrm_country', $presentSimpleFrom)
6063 unset($presentSimpleFrom['civicrm_country']);
6065 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
6066 array_key_exists('civicrm_country', $present)
6068 unset($present['civicrm_country']);
6071 $presentClause = $presentSimpleFromClause = NULL;
6072 if (!empty($present)) {
6073 $presentClause = implode(' ', $present);
6075 if (!empty($presentSimpleFrom)) {
6076 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
6079 $this->_fromClause
= $this->_fromClause
. $presentClause;
6080 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
6082 return array($presentClause, $presentSimpleFromClause);
6086 * Build qill for field.
6088 * Qill refers to the query detail visible on the UI.
6090 * @param string $daoName
6091 * @param string $fieldName
6092 * @param mixed $fieldValue
6094 * @param array $pseudoExtraParam
6096 * Type of the field per CRM_Utils_Type
6100 public static function buildQillForFieldValue(
6105 $pseudoExtraParam = array(),
6106 $type = CRM_Utils_Type
::T_STRING
6108 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
6110 //API usually have fieldValue format as array(operator => array(values)),
6111 //so we need to separate operator out of fieldValue param
6112 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
6113 $op = key($fieldValue);
6114 $fieldValue = $fieldValue[$op];
6117 // if Operator chosen is NULL/EMPTY then
6118 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
6119 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), '');
6122 if ($fieldName == 'activity_type_id') {
6123 $pseudoOptions = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
6125 elseif ($fieldName == 'country_id') {
6126 $pseudoOptions = CRM_Core_PseudoConstant
::country();
6128 elseif ($fieldName == 'county_id') {
6129 $pseudoOptions = CRM_Core_PseudoConstant
::county();
6131 elseif ($fieldName == 'world_region') {
6132 $pseudoOptions = CRM_Core_PseudoConstant
::worldRegion();
6134 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
6135 $checkPermission = CRM_Utils_Array
::value('check_permission', $pseudoExtraParam, TRUE);
6136 $pseudoOptions = CRM_Event_BAO_Event
::getEvents(0, $fieldValue, TRUE, $checkPermission, TRUE);
6138 elseif ($fieldName == 'contribution_product_id') {
6139 $pseudoOptions = CRM_Contribute_PseudoConstant
::products();
6141 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
6142 $pseudoOptions = CRM_Core_PseudoConstant
::group();
6144 elseif ($daoName == 'CRM_Batch_BAO_EntityBatch' && $fieldName == 'batch_id') {
6145 $pseudoOptions = CRM_Contribute_PseudoConstant
::batch();
6148 $pseudoOptions = CRM_Core_PseudoConstant
::get($daoName, $fieldName, $pseudoExtraParam);
6151 if (is_array($fieldValue)) {
6152 $qillString = array();
6153 if (!empty($pseudoOptions)) {
6154 foreach ((array) $fieldValue as $val) {
6155 $qillString[] = CRM_Utils_Array
::value($val, $pseudoOptions, $val);
6157 $fieldValue = implode(', ', $qillString);
6160 if ($type == CRM_Utils_Type
::T_DATE
) {
6161 foreach ($fieldValue as $index => $value) {
6162 $fieldValue[$index] = CRM_Utils_Date
::customFormat($value);
6166 // @todo - this is a bit specific (one operator).
6167 // However it is covered by a unit test so can be altered later with
6169 if ($op == 'BETWEEN') {
6170 $separator = ' AND ';
6172 $fieldValue = implode($separator, $fieldValue);
6175 elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) {
6176 $fieldValue = $pseudoOptions[$fieldValue];
6178 elseif ($type === CRM_Utils_Type
::T_DATE
) {
6179 $fieldValue = CRM_Utils_Date
::customFormat($fieldValue);
6182 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), $fieldValue);
6186 * Alter value to reflect wildcard settings.
6188 * The form will have tried to guess whether this is a good field to wildcard but there is
6189 * also a site-wide setting that specifies whether it is OK to append the wild card to the beginning
6190 * or only the end of the string
6192 * @param bool $wildcard
6193 * This is a bool made on an assessment 'elsewhere' on whether this is a good field to wildcard.
6195 * Generally '=' or 'LIKE'.
6196 * @param string $value
6197 * The search string.
6201 public static function getWildCardedValue($wildcard, $op, $value) {
6202 if ($wildcard && $op == 'LIKE') {
6203 if (CRM_Core_Config
::singleton()->includeWildCardInName
&& (substr($value, 0, 1) != '%')) {
6216 * Process special fields of Search Form in OK (Operator in Key) format
6218 * @param array $formValues
6219 * @param array $specialFields
6220 * Special params to be processed
6221 * @param array $changeNames
6222 * Array of fields whose name should be changed
6224 public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = array()) {
6225 // Array of special fields whose value are considered only for NULL or EMPTY operators
6226 $nullableFields = array('contribution_batch_id');
6228 foreach ($specialFields as $element) {
6229 $value = CRM_Utils_Array
::value($element, $formValues);
6231 if (is_array($value)) {
6232 if (in_array($element, array_keys($changeNames))) {
6233 unset($formValues[$element]);
6234 $element = $changeNames[$element];
6236 $formValues[$element] = array('IN' => $value);
6238 elseif (in_array($value, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
6239 $formValues[$element] = array($value => 1);
6241 elseif (!in_array($element, $nullableFields)) {
6242 // if wildcard is already present return searchString as it is OR append and/or prepend with wildcard
6243 $isWilcard = strstr($value, '%') ?
FALSE : CRM_Core_Config
::singleton()->includeWildCardInName
;
6244 $formValues[$element] = array('LIKE' => self
::getWildCardedValue($isWilcard, 'LIKE', $value));
6251 * Parse and assimilate the various sort options.
6253 * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`,
6254 * `email`), the related table may be joined automatically.
6256 * At time of writing, this code is deeply flawed and should be rewritten. For the moment,
6257 * it's been extracted to a standalone function.
6259 * @param string|CRM_Utils_Sort $sort
6260 * The order by string.
6261 * @param bool $sortByChar
6262 * If true returns the distinct array of first characters for search results.
6263 * @param null $sortOrder
6264 * Who knows? Hu knows. He who knows Hu knows who.
6265 * @param string $additionalFromClause
6266 * Should be clause with proper joins, effective to reduce where clause load.
6268 * list(string $orderByClause, string $additionalFromClause).
6270 protected function prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause) {
6272 $orderByArray = array();
6273 $config = CRM_Core_Config
::singleton();
6274 if ($config->includeOrderByClause ||
6275 isset($this->_distinctComponentClause
)
6278 if (is_string($sort)) {
6282 $orderBy = trim($sort->orderBy());
6284 // Deliberately remove the backticks again, as they mess up the evil
6285 // string munging below. This balanced by re-escaping before use.
6286 $orderBy = str_replace('`', '', $orderBy);
6288 if (!empty($orderBy)) {
6289 // this is special case while searching for
6290 // change log CRM-1718
6291 if (preg_match('/sort_name/i', $orderBy)) {
6292 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
6295 $order = " ORDER BY $orderBy";
6298 $order .= " $sortOrder";
6301 // always add contact_a.id to the ORDER clause
6302 // so the order is deterministic
6303 if (strpos('contact_a.id', $order) === FALSE) {
6304 $order .= ", contact_a.id";
6308 elseif ($sortByChar) {
6309 $orderByArray = array("UPPER(LEFT(contact_a.sort_name, 1)) asc");
6312 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
6315 if (!$order && empty($orderByArray)) {
6316 return array($order, $additionalFromClause);
6318 // Remove this here & add it at the end for simplicity.
6319 $order = trim(str_replace('ORDER BY', '', $order));
6321 // hack for order clause
6322 if (!empty($orderByArray)) {
6323 $order = implode(', ', $orderByArray);
6326 $orderByArray = explode(',', $order);
6328 foreach ($orderByArray as $orderByClause) {
6329 $orderByClauseParts = explode(' ', trim($orderByClause));
6330 $field = $orderByClauseParts[0];
6331 $direction = isset($orderByClauseParts[1]) ?
$orderByClauseParts[1] : 'asc';
6336 $this->_tables
["civicrm_address"] = $this->_whereTables
["civicrm_address"] = 1;
6337 $order = str_replace($field, "civicrm_address.{$field}", $order);
6341 case 'state_province':
6342 $this->_tables
["civicrm_{$field}"] = $this->_whereTables
["civicrm_{$field}"] = 1;
6343 if (is_array($this->_returnProperties
) && empty($this->_returnProperties
)) {
6344 $additionalFromClause .= " LEFT JOIN civicrm_{$field} ON civicrm_{$field}.id = civicrm_address.{$field}_id";
6346 $order = str_replace($field, "civicrm_{$field}.name", $order);
6350 $this->_tables
["civicrm_email"] = $this->_whereTables
["civicrm_email"] = 1;
6351 $order = str_replace($field, "civicrm_email.{$field}", $order);
6355 foreach ($this->_pseudoConstantsSelect
as $key => $pseudoConstantMetadata) {
6356 // By replacing the join to the option value table with the mysql construct
6357 // ORDER BY field('contribution_status_id', 2,1,4)
6358 // we can remove a join. In the case of the option value join it is
6359 /// a join known to cause slow queries.
6360 // @todo cover other pseudoconstant types. Limited to option group ones in the
6361 // first instance for scope reasons. They require slightly different handling as the column (label)
6362 // is not declared for them.
6363 // @todo so far only integer fields are being handled. If we add string fields we need to look at
6365 if (isset($pseudoConstantMetadata['pseudoconstant'])
6366 && isset($pseudoConstantMetadata['pseudoconstant']['optionGroupName'])
6367 && $field === CRM_Utils_Array
::value('optionGroupName', $pseudoConstantMetadata['pseudoconstant'])
6369 $sortedOptions = $pseudoConstantMetadata['bao']::buildOptions($pseudoConstantMetadata['pseudoField'], NULL, array(
6370 'orderColumn' => 'label',
6372 $order = str_replace("$field $direction", "field({$pseudoConstantMetadata['pseudoField']}," . implode(',', array_keys($sortedOptions)) . ") $direction", $order);
6374 //CRM-12565 add "`" around $field if it is a pseudo constant
6375 // This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
6376 if (!empty($pseudoConstantMetadata['element']) && $pseudoConstantMetadata['element'] == $field) {
6377 $order = str_replace($field, "`{$field}`", $order);
6383 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6384 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6386 // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
6387 // clause. But this magic helper which forgivingly reescapes ORDER BY.
6388 // Note: $sortByChar implies that $order was hard-coded/trusted, so it can do funky things.
6390 return array(' ORDER BY ' . $order, $additionalFromClause);
6393 $order = CRM_Utils_Type
::escape($order, 'MysqlOrderBy');
6394 return array(' ORDER BY ' . $order, $additionalFromClause);
6399 * Convert a string of group IDs to a string of group labels.
6401 * The original string may include duplicates and groups the user does not have
6402 * permission to see.
6404 * @param CRM_Core_DAO $dao
6405 * @param string $val
6409 public function convertGroupIDStringToLabelString(&$dao, $val) {
6410 $groupIDs = explode(',', $val);
6411 // Note that groups that the user does not have permission to will be excluded (good).
6412 $groups = array_intersect_key(CRM_Core_PseudoConstant
::group(), array_flip($groupIDs));
6413 return implode(', ', $groups);
6418 * Set the qill and where properties for a field.
6420 * This function is intended as a short-term function to encourage refactoring
6421 * & re-use - but really we should just have less special-casing.
6423 * @param string $name
6425 * @param string|array $value
6426 * @param string $grouping
6427 * @param string $field
6429 public function setQillAndWhere($name, $op, $value, $grouping, $field) {
6430 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
6431 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
6432 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(
6433 1 => $field['title'],
6440 * Has the pseudoconstant of the field been requested.
6442 * For example if the field is payment_instrument_id then it
6443 * has been requested if either payment_instrument_id or payment_instrument
6444 * have been requested. Payment_instrument is the option groun name field value.
6446 * @param array $field
6447 * @param string $fieldName
6448 * The unique name of the field - ie. the one it will be aliased to in the query.
6452 private function pseudoConstantNameIsInReturnProperties($field, $fieldName = NULL) {
6453 if (!isset($field['pseudoconstant']['optionGroupName'])) {
6457 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
6460 if (CRM_Utils_Array
::value($fieldName, $this->_returnProperties
)) {
6463 // Is this still required - the above goes off the unique name. Test with things like
6464 // communication_prefferences & prefix_id.
6465 if (CRM_Utils_Array
::value($field['name'], $this->_returnProperties
)) {