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_website':
2755 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2759 $locationTypeName = '';
2760 if (strpos($name, '-address') != 0) {
2761 $locationTypeName = 'address';
2763 elseif (strpos($name, '-phone') != 0) {
2764 $locationTypeName = 'phone';
2766 elseif (strpos($name, '-email') != 0) {
2767 $locationTypeName = 'email';
2769 elseif (strpos($name, '-im') != 0) {
2770 $locationTypeName = 'im';
2772 elseif (strpos($name, '-openid') != 0) {
2773 $locationTypeName = 'openid';
2776 if ($locationTypeName) {
2777 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2778 $parts = explode('-', $name);
2779 $locationID = array_search($parts[0], CRM_Core_BAO_Address
::buildOptions('location_type_id', 'get', array('name' => $parts[0])));
2780 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2783 $from .= CRM_Core_Component
::from($name, $mode, $side);
2785 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2794 * WHERE / QILL clause for deleted_contacts
2796 * @param array $values
2798 public function deletedContacts($values) {
2799 list($_, $_, $value, $grouping, $_) = $values;
2801 // *prepend* to the relevant grouping as this is quite an important factor
2802 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2807 * Where / qill clause for contact_type
2811 public function contactType(&$values) {
2812 list($name, $op, $value, $grouping, $wildcard) = $values;
2814 $subTypes = array();
2817 // account for search builder mapping multiple values
2818 if (!is_array($value)) {
2819 $values = self
::parseSearchBuilderString($value, 'String');
2820 if (is_array($values)) {
2821 $value = array_flip($values);
2825 if (is_array($value)) {
2826 foreach ($value as $k => $v) {
2831 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2832 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2835 if (!empty($subType)) {
2836 $subTypes[$subType] = 1;
2838 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2843 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2844 $contactType = $contactTypeANDSubType[0];
2845 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2846 if (!empty($subType)) {
2847 $subTypes[$subType] = 1;
2849 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2853 if (!empty($clause)) {
2855 if ($op == 'IN' ||
$op == 'NOT IN') {
2856 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2859 $type = array_pop($clause);
2860 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2863 $this->_qill
[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2865 if (!empty($subTypes)) {
2866 $this->includeContactSubTypes($subTypes, $grouping);
2872 * Where / qill clause for contact_sub_type.
2874 * @param array $values
2876 public function contactSubType(&$values) {
2877 list($name, $op, $value, $grouping, $wildcard) = $values;
2878 $this->includeContactSubTypes($value, $grouping, $op);
2886 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2888 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2890 $value = $value[$op];
2894 $alias = "contact_a.contact_sub_type";
2895 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
2897 $op = str_replace('IN', 'LIKE', $op);
2898 $op = str_replace('=', 'LIKE', $op);
2899 $op = str_replace('!', 'NOT ', $op);
2901 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2902 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
2904 elseif (is_array($value)) {
2905 foreach ($value as $k => $v) {
2906 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($v, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2910 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2913 if (!empty($clause)) {
2914 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2916 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', array(1 => $qillOperators[$op])) . implode(' ' . ts('or') . ' ', array_keys($clause));
2920 * Where / qill clause for groups.
2924 public function group($values) {
2925 list($name, $op, $value, $grouping, $wildcard) = $values;
2927 // If the $value is in OK (operator as key) array format we need to extract the key as operator and value first
2928 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2930 $value = $value[$op];
2933 // Replace pseudo operators from search builder
2934 $op = str_replace('EMPTY', 'NULL', $op);
2936 if (strpos($op, 'NULL')) {
2940 if (count($value) > 1) {
2941 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
2942 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $op)));
2944 $this->_useDistinct
= TRUE;
2947 if (isset($value)) {
2948 $value = CRM_Utils_Array
::value($op, $value, $value);
2951 if ($name == 'group_type') {
2952 $value = array_keys($this->getGroupsFromTypeCriteria($value));
2955 $regularGroupIDs = $smartGroupIDs = array();
2956 foreach ((array) $value as $id) {
2957 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
2958 $smartGroupIDs[] = $id;
2961 $regularGroupIDs[] = $id;
2965 $isNotOp = ($op == 'NOT IN' ||
$op == '!=');
2968 $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
2970 is_array($gcsValues[2])
2972 foreach ($gcsValues[2] as $k => $v) {
2974 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2979 $statii[] = "'Added'";
2981 $groupClause = array();
2982 if (count($regularGroupIDs) ||
empty($value)) {
2983 // include child groups IDs if any
2984 $childGroupIds = (array) CRM_Contact_BAO_Group
::getChildGroupIds($regularGroupIDs);
2985 foreach ($childGroupIds as $key => $id) {
2986 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
2987 $smartGroupIDs[] = $id;
2988 unset($childGroupIds[$key]);
2991 if (count($childGroupIds)) {
2992 $regularGroupIDs = array_merge($regularGroupIDs, $childGroupIds);
2995 // if $regularGroupIDs is populated with regular child group IDs
2996 // then change the mysql operator to desired
2997 if (count($regularGroupIDs) > 1) {
2998 $op = strpos($op, 'IN') ?
$op : ($op == '!=') ?
'NOT IN' : 'IN';
3000 $groupIds = implode(',', (array) $regularGroupIDs);
3001 $gcTable = "`civicrm_group_contact-{$groupIds}`";
3002 $joinClause = array("contact_a.id = {$gcTable}.contact_id");
3004 if (strpos($op, 'IN') !== FALSE) {
3005 $clause = "{$gcTable}.group_id $op ( $groupIds ) ";
3007 elseif ($op == '!=') {
3008 $clause = "{$gcTable}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact cgc WHERE cgc.group_id = $groupIds )";
3011 $clause = "{$gcTable}.group_id $op $groupIds ";
3013 $groupClause[] = "( {$clause} )";
3016 $joinClause[] = "{$gcTable}.status IN (" . implode(', ', $statii) . ")";
3018 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3021 //CRM-19589: contact(s) removed from a Smart Group, resides in civicrm_group_contact table
3022 if (count($smartGroupIDs)) {
3023 $groupClause[] = " ( " . $this->addGroupContactCache($smartGroupIDs, NULL, "contact_a", $op) . " ) ";
3026 $and = ($op == 'IS NULL') ?
' AND ' : ' OR ';
3027 $this->_where
[$grouping][] = ' ( ' . implode($and, $groupClause) . ' ) ';
3029 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
3030 $this->_qill
[$grouping][] = ts("Group(s) %1 %2", array(1 => $qillop, 2 => $qillVal));
3031 if (strpos($op, 'NULL') === FALSE) {
3032 $this->_qill
[$grouping][] = ts("Group Status %1", array(1 => implode(' ' . ts('or') . ' ', $statii)));
3037 * Function translates selection of group type into a list of groups.
3042 public function getGroupsFromTypeCriteria($value) {
3043 $groupIds = array();
3044 foreach ((array) $value as $groupTypeValue) {
3045 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
3046 $groupIds = ($groupIds +
$groupList);
3052 * @param array $groups
3053 * @param string $tableAlias
3054 * @param string $joinTable
3057 * @return null|string
3059 public function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a", $op) {
3060 $isNullOp = (strpos($op, 'NULL') !== FALSE);
3061 $groupsIds = $groups;
3062 if (!$isNullOp && !$groups) {
3065 elseif (strpos($op, 'IN') !== FALSE) {
3066 $groups = array($op => $groups);
3068 elseif (is_array($groups) && count($groups)) {
3069 $groups = array('IN' => $groups);
3072 // Find all the groups that are part of a saved search.
3073 $smartGroupClause = self
::buildClause("id", $op, $groups, 'Int');
3075 SELECT id, cache_date, saved_search_id, children
3077 WHERE $smartGroupClause
3078 AND ( saved_search_id != 0
3079 OR saved_search_id IS NOT NULL
3080 OR children IS NOT NULL )
3083 $group = CRM_Core_DAO
::executeQuery($sql);
3085 while ($group->fetch()) {
3086 $this->_useDistinct
= TRUE;
3087 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
3088 CRM_Contact_BAO_GroupContactCache
::load($group);
3091 if ($group->N
== 0) {
3096 $tableAlias = "`civicrm_group_contact_cache_";
3097 $tableAlias .= ($isNullOp) ?
"a`" : implode(',', (array) $groupsIds) . "`";
3100 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.id = {$tableAlias}.contact_id ";
3101 return self
::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
3105 * Where / qill clause for cms users
3109 public function ufUser(&$values) {
3110 list($name, $op, $value, $grouping, $wildcard) = $values;
3113 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3115 $this->_qill
[$grouping][] = ts('CMS User');
3117 elseif ($value == 0) {
3118 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3120 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3121 $this->_qill
[$grouping][] = ts('Not a CMS User');
3126 * All tag search specific.
3128 * @param array $values
3130 public function tagSearch(&$values) {
3131 list($name, $op, $value, $grouping, $wildcard) = $values;
3134 $value = "%{$value}%";
3136 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3137 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3139 $etTable = "`civicrm_entity_tag-" . $value . "`";
3140 $tTable = "`civicrm_tag-" . $value . "`";
3142 if ($useAllTagTypes[2]) {
3143 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3144 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3145 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3147 // search tag in cases
3148 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3149 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
3150 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3151 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3152 LEFT JOIN civicrm_case
3153 ON (civicrm_case_contact.case_id = civicrm_case.id
3154 AND civicrm_case.is_deleted = 0 )
3155 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3156 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3157 // search tag in activities
3158 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3159 $tActTable = "`civicrm_act_tag-" . $value . "`";
3160 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3161 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3163 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3164 = " LEFT JOIN civicrm_activity_contact
3165 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3166 LEFT JOIN civicrm_activity
3167 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3168 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3169 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3170 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3172 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $value . "' OR {$tCaseTable}.name $op '" . $value . "' OR {$tActTable}.name $op '" . $value . "')";
3173 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
3176 $etTable = "`civicrm_entity_tag-" . $value . "`";
3177 $tTable = "`civicrm_tag-" . $value . "`";
3178 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3179 {$etTable}.entity_table = 'civicrm_contact' )
3180 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3182 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3183 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
3188 * Where / qill clause for tag.
3190 * @param array $values
3192 public function tag(&$values) {
3193 list($name, $op, $value, $grouping, $wildcard) = $values;
3195 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, array('onlyActive' => FALSE));
3196 // API/Search Builder format array(operator => array(values))
3197 if (is_array($value)) {
3198 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3200 $value = $value[$op];
3202 if (count($value) > 1) {
3203 $this->_useDistinct
= TRUE;
3205 $value = implode(',', (array) $value);
3208 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3209 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3211 $etTable = "`civicrm_entity_tag-" . $value . "`";
3213 if ($useAllTagTypes[2]) {
3214 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3215 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3217 // search tag in cases
3218 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3219 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3220 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3222 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3223 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3224 LEFT JOIN civicrm_case
3225 ON (civicrm_case_contact.case_id = civicrm_case.id
3226 AND civicrm_case.is_deleted = 0 )
3227 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3228 // search tag in activities
3229 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3230 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3231 = " LEFT JOIN civicrm_activity_contact
3232 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3233 LEFT JOIN civicrm_activity
3234 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3235 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3236 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3239 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3240 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3243 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3247 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3248 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3251 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3252 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3253 $op = str_replace('EMPTY', 'NULL', $op);
3254 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3256 // CRM-16941: for tag tried with != operator we don't show contact who don't have given $value AND also in other tag
3257 elseif ($op == '!=') {
3258 $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') . ")";
3260 elseif ($op == '=' ||
strstr($op, 'IN')) {
3261 $op = ($op == '=') ?
'IN' : $op;
3262 $this->_where
[$grouping][] = "{$etTable}.tag_id $op ( $value )";
3265 $this->_qill
[$grouping][] = ts('Tagged %1 %2', array(1 => $qillop, 2 => $qillVal));
3269 * Where/qill clause for notes
3271 * @param array $values
3273 public function notes(&$values) {
3274 list($name, $op, $value, $grouping, $wildcard) = $values;
3276 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3277 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3278 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3280 $this->_useDistinct
= TRUE;
3282 $this->_tables
['civicrm_note'] = $this->_whereTables
['civicrm_note']
3283 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3285 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3287 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3289 if (strpos($value, '%') === FALSE) {
3290 $value = "%$value%";
3294 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3300 if ($noteOption %
2 == 0) {
3301 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3302 $label = ts('Note: Body Only');
3304 if ($noteOption %
3 == 0) {
3305 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3306 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3308 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3309 list($qillOp, $qillVal) = self
::buildQillForFieldValue(NULL, $name, $n, $op);
3310 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillOp, 3 => $qillVal));
3314 * @param string $name
3320 public function nameNullOrEmptyOp($name, $op, $grouping) {
3324 $this->_where
[$grouping][] = "contact_a.$name $op";
3325 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3329 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3330 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3333 case 'IS NOT EMPTY':
3334 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3335 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3344 * Where / qill clause for sort_name
3346 * @param array $values
3348 public function sortName(&$values) {
3349 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3351 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3352 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3356 $input = $value = trim($value);
3358 if (!strlen($value)) {
3362 $config = CRM_Core_Config
::singleton();
3366 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3369 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3371 $firstChar = substr($value, 0, 1);
3372 $lastChar = substr($value, -1, 1);
3373 $quotes = array("'", '"');
3374 // If string is quoted, strip quotes and otherwise don't alter it
3375 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3376 $value = trim($value, implode('', $quotes));
3378 // Replace spaces with wildcards for a LIKE operation
3379 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3380 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3381 $value = str_replace(' ', '%', $value);
3383 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($value)));
3384 if (strlen($value)) {
3385 $fieldsub = array();
3386 $value = "'" . self
::getWildCardedValue($wildcard, $op, $value) . "'";
3387 if ($fieldName == 'sort_name') {
3388 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3389 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3392 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3393 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3395 $fieldsub[] = " ( $wc $op $value )";
3396 if ($config->includeNickNameInName
) {
3397 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3398 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3399 $fieldsub[] = " ( $wc $op $value )";
3401 if ($config->includeEmailInName
) {
3402 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3404 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3407 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3409 $this->_where
[$grouping][] = $sub;
3410 if ($config->includeEmailInName
) {
3411 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3412 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3415 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3420 * Where/qill clause for greeting fields.
3422 * @param array $values
3424 public function greetings(&$values) {
3425 list($name, $op, $value, $grouping, $wildcard) = $values;
3426 $name .= '_display';
3428 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
3429 $this->_qill
[$grouping][] = ts('Greeting %1 %2', array(1 => $qillop, 2 => $qillVal));
3430 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value, 'String');
3434 * Where / qill clause for email
3436 * @param array $values
3437 * @param string $apiEntity
3439 protected function email(&$values, $apiEntity) {
3440 list($name, $op, $value, $grouping, $wildcard) = $values;
3441 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3443 // CRM-18147: for Contact's GET API, email fieldname got appended with its entity as in {$apiEntiy}_{$name}
3444 // so following code is use build whereClause for contact's primart email id
3445 if (!empty($apiEntity)) {
3446 $dataType = 'String';
3447 if ($name == 'email_id') {
3448 $dataType = 'Integer';
3452 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.is_primary', '=', 1, 'Integer');
3453 $this->_where
[$grouping][] = self
::buildClause("civicrm_email.$name", $op, $value, $dataType);
3457 $n = strtolower(trim($value));
3459 if (substr($n, 0, 1) == '"' &&
3460 substr($n, -1, 1) == '"'
3462 $n = substr($n, 1, -1);
3463 $value = CRM_Core_DAO
::escapeString($n);
3467 $value = self
::getWildCardedValue($wildcard, $op, $n);
3469 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3470 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3473 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3474 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3479 * Where / qill clause for phone number
3481 * @param array $values
3483 public function phone_numeric(&$values) {
3484 list($name, $op, $value, $grouping, $wildcard) = $values;
3485 // Strip non-numeric characters; allow wildcards
3486 $number = preg_replace('/[^\d%]/', '', $value);
3488 if (strpos($number, '%') === FALSE) {
3489 $number = "%$number%";
3492 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3493 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3494 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3499 * Where / qill clause for phone type/location
3501 * @param array $values
3503 public function phone_option_group($values) {
3504 list($name, $op, $value, $grouping, $wildcard) = $values;
3505 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3506 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3507 $optionName = $options[$value];
3508 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3509 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3510 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3514 * Where / qill clause for street_address.
3516 * @param array $values
3518 public function street_address(&$values) {
3519 list($name, $op, $value, $grouping, $wildcard) = $values;
3528 $value = strtolower($n);
3529 if (strpos($value, '%') === FALSE) {
3530 // only add wild card if not there
3531 $value = "%{$value}%";
3534 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3535 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3536 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3539 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3540 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3543 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3547 * Where / qill clause for street_unit.
3549 * @param array $values
3551 public function street_number(&$values) {
3552 list($name, $op, $value, $grouping, $wildcard) = $values;
3560 if (strtolower($n) == 'odd') {
3561 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3562 $this->_qill
[$grouping][] = ts('Street Number is odd');
3564 elseif (strtolower($n) == 'even') {
3565 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3566 $this->_qill
[$grouping][] = ts('Street Number is even');
3569 $value = strtolower($n);
3571 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3572 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3573 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3576 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3580 * Where / qill clause for sorting by character.
3582 * @param array $values
3584 public function sortByCharacter(&$values) {
3585 list($name, $op, $value, $grouping, $wildcard) = $values;
3587 $name = trim($value);
3588 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3589 $this->_where
[$grouping][] = $cond;
3590 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3594 * Where / qill clause for including contact ids.
3596 public function includeContactIDs() {
3597 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3601 $contactIds = array();
3602 foreach ($this->_params
as $id => $values) {
3603 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3604 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3607 CRM_Utils_Type
::validateAll($contactIds, 'Positive');
3608 if (!empty($contactIds)) {
3609 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3614 * Where / qill clause for postal code.
3616 * @param array $values
3618 public function postalCode(&$values) {
3619 // skip if the fields dont have anything to do with postal_code
3620 if (empty($this->_fields
['postal_code'])) {
3624 list($name, $op, $value, $grouping, $wildcard) = $values;
3626 // Handle numeric postal code range searches properly by casting the column as numeric
3627 if (is_numeric($value)) {
3628 $field = "IF (civicrm_address.postal_code REGEXP '^[0-9]+$', CAST(civicrm_address.postal_code AS UNSIGNED), 0)";
3629 $val = CRM_Utils_Type
::escape($value, 'Integer');
3632 $field = 'civicrm_address.postal_code';
3633 // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string.
3634 if (!is_array($value)) {
3635 $val = CRM_Utils_Type
::escape($value, 'String');
3638 // Do we need to escape values here? I would expect buildClause does.
3643 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3645 if ($name == 'postal_code') {
3646 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3647 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3649 elseif ($name == 'postal_code_low') {
3650 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3651 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3653 elseif ($name == 'postal_code_high') {
3654 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3655 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3660 * Where / qill clause for location type.
3662 * @param array $values
3663 * @param null $status
3667 public function locationType(&$values, $status = NULL) {
3668 list($name, $op, $value, $grouping, $wildcard) = $values;
3670 if (is_array($value)) {
3671 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3672 $this->_tables
['civicrm_address'] = 1;
3673 $this->_whereTables
['civicrm_address'] = 1;
3675 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3677 foreach ($value as $id) {
3678 $names[] = $locationType[$id];
3681 $this->_primaryLocation
= FALSE;
3684 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3687 return implode(' ' . ts('or') . ' ', $names);
3694 * @param bool $fromStateProvince
3696 * @return array|NULL
3698 public function country(&$values, $fromStateProvince = TRUE) {
3699 list($name, $op, $value, $grouping, $wildcard) = $values;
3701 if (!$fromStateProvince) {
3702 $stateValues = $this->getWhereValues('state_province', $grouping);
3703 if (!empty($stateValues)) {
3704 // return back to caller if there are state province values
3705 // since that handles this case
3710 $countryClause = $countryQill = NULL;
3711 if ($values && !empty($value)) {
3712 $this->_tables
['civicrm_address'] = 1;
3713 $this->_whereTables
['civicrm_address'] = 1;
3715 $countryClause = self
::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
3716 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, 'country_id', $value, $op);
3717 $countryQill = ts("%1 %2 %3", array(1 => 'Country', 2 => $qillop, 3 => $qillVal));
3719 if (!$fromStateProvince) {
3720 $this->_where
[$grouping][] = $countryClause;
3721 $this->_qill
[$grouping][] = $countryQill;
3725 if ($fromStateProvince) {
3726 if (!empty($countryClause)) {
3729 " ...AND... " . $countryQill,
3733 return array(NULL, NULL);
3739 * Where / qill clause for county (if present).
3741 * @param array $values
3742 * @param null $status
3746 public function county(&$values, $status = NULL) {
3747 list($name, $op, $value, $grouping, $wildcard) = $values;
3749 if (!is_array($value)) {
3750 // force the county to be an array
3751 $value = array($value);
3754 // check if the values are ids OR names of the counties
3755 $inputFormat = 'id';
3756 foreach ($value as $v) {
3757 if (!is_numeric($v)) {
3758 $inputFormat = 'name';
3766 elseif ($op == '!=') {
3770 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3771 $op = str_replace('EMPTY', 'NULL', $op);
3774 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3775 $clause = "civicrm_address.county_id $op";
3777 elseif ($inputFormat == 'id') {
3778 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3780 $county = CRM_Core_PseudoConstant
::county();
3781 foreach ($value as $id) {
3782 $names[] = CRM_Utils_Array
::value($id, $county);
3786 $inputClause = array();
3787 $county = CRM_Core_PseudoConstant
::county();
3788 foreach ($value as $name) {
3789 $name = trim($name);
3790 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3792 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3795 $this->_tables
['civicrm_address'] = 1;
3796 $this->_whereTables
['civicrm_address'] = 1;
3798 $this->_where
[$grouping][] = $clause;
3800 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3803 return implode(' ' . ts('or') . ' ', $names);
3808 * Where / qill clause for state/province AND country (if present).
3810 * @param array $values
3811 * @param null $status
3815 public function stateProvince(&$values, $status = NULL) {
3816 list($name, $op, $value, $grouping, $wildcard) = $values;
3818 $stateClause = self
::buildClause('civicrm_address.state_province_id', $op, $value, 'Positive');
3819 $this->_tables
['civicrm_address'] = 1;
3820 $this->_whereTables
['civicrm_address'] = 1;
3822 $countryValues = $this->getWhereValues('country', $grouping);
3823 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3824 if ($countryClause) {
3825 $clause = "( $stateClause AND $countryClause )";
3828 $clause = $stateClause;
3831 $this->_where
[$grouping][] = $clause;
3832 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
3834 $this->_qill
[$grouping][] = ts("State/Province %1 %2 %3", array(1 => $qillop, 2 => $qillVal, 3 => $countryQill));
3837 return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill;
3842 * Where / qill clause for change log.
3844 * @param array $values
3846 public function changeLog(&$values) {
3847 list($name, $op, $value, $grouping, $wildcard) = $values;
3849 $targetName = $this->getWhereValues('changed_by', $grouping);
3854 $name = trim($targetName[2]);
3855 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3856 $name = $targetName[4] ?
"%$name%" : $name;
3857 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3858 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3859 $this->_qill
[$grouping][] = ts('Modified By') . " $name";
3865 public function modifiedDates($values) {
3866 $this->_useDistinct
= TRUE;
3868 // CRM-11281, default to added date if not set
3869 $fieldTitle = ts('Added Date');
3870 $fieldName = 'created_date';
3871 foreach (array_keys($this->_params
) as $id) {
3872 if ($this->_params
[$id][0] == 'log_date') {
3873 if ($this->_params
[$id][2] == 2) {
3874 $fieldTitle = ts('Modified Date');
3875 $fieldName = 'modified_date';
3880 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3882 self
::$_openedPanes[ts('Change Log')] = TRUE;
3888 public function demographics(&$values) {
3889 list($name, $op, $value, $grouping, $wildcard) = $values;
3891 if (($name == 'age_low') ||
($name == 'age_high')) {
3892 $this->ageRangeQueryBuilder($values,
3893 'contact_a', 'age', 'birth_date', ts('Age')
3896 elseif (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3898 $this->dateQueryBuilder($values,
3899 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3902 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3904 $this->dateQueryBuilder($values,
3905 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3909 self
::$_openedPanes[ts('Demographics')] = TRUE;
3915 public function privacy(&$values) {
3916 list($name, $op, $value, $grouping, $wildcard) = $values;
3917 //fixed for profile search listing CRM-4633
3918 if (strpbrk($value, "[")) {
3919 $value = "'{$value}'";
3921 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3924 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3926 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3927 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
3928 $title = $field ?
$field['title'] : $name;
3929 $this->_qill
[$grouping][] = "$title $op $value";
3935 public function privacyOptions($values) {
3936 list($name, $op, $value, $grouping, $wildcard) = $values;
3938 if (empty($value) ||
!is_array($value)) {
3942 // get the operator and toggle values
3943 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3946 strtolower($opValues[2] == 'AND')
3951 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3953 if ($toggleValues &&
3954 $toggleValues[2] == 2
3961 foreach ($value as $dontCare => $pOption) {
3962 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
3963 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3964 $title = $field ?
$field['title'] : $pOption;
3965 $qill[] = " $title = 1 ";
3968 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
3969 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
3975 public function preferredCommunication(&$values) {
3976 list($name, $op, $value, $grouping, $wildcard) = $values;
3978 if (!is_array($value)) {
3979 $value = str_replace(array('(', ')'), '', explode(",", $value));
3981 elseif (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3983 $value = $value[$op];
3985 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Contact', $name, $value, $op);
3987 if (self
::caseImportant($op)) {
3988 $value = implode("[[:cntrl:]]|[[:cntrl:]]", (array) $value);
3989 $op = (strstr($op, '!') ||
strstr($op, 'NOT')) ?
'NOT RLIKE' : 'RLIKE';
3990 $value = "[[:cntrl:]]" . $value . "[[:cntrl:]]";
3993 $this->_where
[$grouping][] = self
::buildClause("contact_a.preferred_communication_method", $op, $value);
3994 $this->_qill
[$grouping][] = ts('Preferred Communication Method %1 %2', array(1 => $qillop, 2 => $qillVal));
3998 * Where / qill clause for relationship.
4000 * @param array $values
4002 public function relationship(&$values) {
4003 list($name, $op, $value, $grouping, $wildcard) = $values;
4004 if ($this->_relationshipValuesAdded
) {
4007 // also get values array for relation_target_name
4008 // for relationship search we always do wildcard
4009 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4010 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4011 $relStatus = $this->getWhereValues('relation_status', $grouping);
4012 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4013 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4015 $nameClause = $name = NULL;
4017 $name = trim($targetName[2]);
4018 if (substr($name, 0, 1) == '"' &&
4019 substr($name, -1, 1) == '"'
4021 $name = substr($name, 1, -1);
4022 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4023 $nameClause = "= '$name'";
4026 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4027 $nameClause = "LIKE '%{$name}%'";
4031 $rTypeValues = array();
4032 if (!empty($relationType)) {
4033 $rel = explode('_', $relationType[2]);
4034 self
::$_relType = $rel[1];
4035 $params = array('id' => $rel[0]);
4036 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
4038 if (!empty($rTypeValues) && $rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
4039 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4040 //@todo unless we are dealing with a target group
4041 self
::$_relType = 'reciprocal';
4043 // if we are creating a temp table we build our own where for the relationship table
4044 $relationshipTempTable = NULL;
4045 if (self
::$_relType == 'reciprocal' && empty($targetGroup)) {
4047 self
::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO
::createTempTableName('civicrm_rel');
4049 $where[$grouping][] = " sort_name $nameClause ";
4053 $where = &$this->_where
;
4055 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4059 $allRelationshipType = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE);
4061 if ($nameClause ||
!$targetGroup) {
4062 if (!empty($relationType)) {
4063 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " $name";
4066 $this->_qill
[$grouping][] = $name;
4070 //check to see if the target contact is in specified group
4072 //add contacts from static groups
4073 $this->_tables
['civicrm_relationship_group_contact'] = $this->_whereTables
['civicrm_relationship_group_contact']
4074 = " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = contact_b.id AND civicrm_relationship_group_contact.status = 'Added'";
4075 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4076 implode(",", $targetGroup[2]) . ") ) ";
4078 //add contacts from saved searches
4079 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b", $op);
4081 //set the group where clause
4083 $groupWhere[] = "( " . $ssWhere . " )";
4085 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4087 //Get the names of the target groups for the qill
4088 $groupNames = CRM_Core_PseudoConstant
::group();
4089 $qillNames = array();
4090 foreach ($targetGroup[2] as $groupId) {
4091 if (array_key_exists($groupId, $groupNames)) {
4092 $qillNames[] = $groupNames[$groupId];
4095 if (!empty($relationType)) {
4096 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " ( " . implode(", ", $qillNames) . " )";
4099 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4103 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4104 $today = date('Ymd');
4105 //check for active, inactive and all relation status
4106 if ($relStatus[2] == 0) {
4107 $where[$grouping][] = "(
4108 civicrm_relationship.is_active = 1 AND
4109 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4110 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4112 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4114 elseif ($relStatus[2] == 1) {
4115 $where[$grouping][] = "(
4116 civicrm_relationship.is_active = 0 OR
4117 civicrm_relationship.end_date < {$today} OR
4118 civicrm_relationship.start_date > {$today}
4120 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4124 if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
)) {
4127 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4129 //check for permissioned, non-permissioned and all permissioned relations
4130 if ($relPermission[2] == 1) {
4131 $where[$grouping][] = "(
4132 civicrm_relationship.is_permission_a_b = 1
4134 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4136 elseif ($relPermission[2] == 2) {
4137 //non-allowed permission relationship.
4138 $where[$grouping][] = "(
4139 civicrm_relationship.is_permission_a_b = 0
4141 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4144 $this->addRelationshipDateClauses($grouping, $where);
4145 $this->addRelationshipActivePeriodClauses($grouping, $where);
4146 if (!empty($relationType) && !empty($rType) && isset($rType->id
)) {
4147 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
4149 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4150 $this->_useDistinct
= TRUE;
4151 $this->_relationshipValuesAdded
= TRUE;
4152 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4154 // @todo creating a temp table could be expanded to group filter
4155 // as even creating a temp table of all relationships is much much more efficient than
4156 // an OR in the join
4157 if ($relationshipTempTable) {
4159 if (!empty($where[$grouping])) {
4160 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4161 $whereClause = str_replace('contact_b', 'c', $whereClause);
4164 CREATE TEMPORARY TABLE {$relationshipTempTable}
4165 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4166 FROM civicrm_relationship
4167 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4170 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4171 FROM civicrm_relationship
4172 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4175 CRM_Core_DAO
::executeQuery($sql);
4181 * Add start & end date criteria in
4182 * @param string $grouping
4183 * @param array $where
4184 * = array to add where clauses to, in case you are generating a temp table.
4185 * not the main query.
4187 public function addRelationshipDateClauses($grouping, &$where) {
4188 $dateValues = array();
4194 foreach ($dateTypes as $dateField) {
4195 $dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping);
4196 $dateValueHigh = $this->getWhereValues('relation_' . $dateField . '_high', $grouping);
4197 if (!empty($dateValueLow)) {
4198 $date = date('Ymd', strtotime($dateValueLow[2]));
4199 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4200 $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);
4202 if (!empty($dateValueHigh)) {
4203 $date = date('Ymd', strtotime($dateValueHigh[2]));
4204 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4205 $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);
4211 * Add start & end active period criteria in
4212 * @param string $grouping
4213 * @param array $where
4214 * = array to add where clauses to, in case you are generating a temp table.
4215 * not the main query.
4217 public function addRelationshipActivePeriodClauses($grouping, &$where) {
4218 $dateValues = array();
4219 $dateField = 'active_period_date';
4221 $dateValueLow = $this->getWhereValues('relation_active_period_date_low', $grouping);
4222 $dateValueHigh = $this->getWhereValues('relation_active_period_date_high', $grouping);
4223 $dateValueLowFormated = $dateValueHighFormated = NULL;
4224 if (!empty($dateValueLow) && !empty($dateValueHigh)) {
4225 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4226 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4227 $this->_qill
[$grouping][] = (ts('Relationship was active between')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated) . " and " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4229 elseif (!empty($dateValueLow)) {
4230 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4231 $this->_qill
[$grouping][] = (ts('Relationship was active after')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated);
4233 elseif (!empty($dateValueHigh)) {
4234 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4235 $this->_qill
[$grouping][] = (ts('Relationship was active before')) . " " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4238 if ($activePeriodClauses = self
::getRelationshipActivePeriodClauses($dateValueLowFormated, $dateValueHighFormated, TRUE)) {
4239 $where[$grouping][] = $activePeriodClauses;
4244 * Get start & end active period criteria
4246 public static function getRelationshipActivePeriodClauses($from, $to, $forceTableName) {
4247 $tableName = $forceTableName ?
'civicrm_relationship.' : '';
4248 if (!is_null($from) && !is_null($to)) {
4249 return '(((' . $tableName . 'start_date >= ' . $from . ' AND ' . $tableName . 'start_date <= ' . $to . ') OR
4250 (' . $tableName . 'end_date >= ' . $from . ' AND ' . $tableName . 'end_date <= ' . $to . ') OR
4251 (' . $tableName . 'start_date <= ' . $from . ' AND ' . $tableName . 'end_date >= ' . $to . ' )) OR
4252 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4253 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . ') OR
4254 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4256 elseif (!is_null($from)) {
4257 return '((' . $tableName . 'start_date >= ' . $from . ') OR
4258 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4259 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . '))';
4261 elseif (!is_null($to)) {
4262 return '((' . $tableName . 'start_date <= ' . $to . ') OR
4263 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4264 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4269 * Default set of return properties.
4274 * derault return properties
4276 public static function &defaultReturnProperties($mode = 1) {
4277 if (!isset(self
::$_defaultReturnProperties)) {
4278 self
::$_defaultReturnProperties = array();
4281 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4282 // add activity return properties
4283 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4284 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4287 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4290 if (empty(self
::$_defaultReturnProperties[$mode])) {
4291 self
::$_defaultReturnProperties[$mode] = array(
4294 'legal_identifier' => 1,
4295 'external_identifier' => 1,
4296 'contact_type' => 1,
4297 'contact_sub_type' => 1,
4299 'display_name' => 1,
4300 'preferred_mail_format' => 1,
4307 'formal_title' => 1,
4308 'communication_style_id' => 1,
4311 'street_address' => 1,
4312 'supplemental_address_1' => 1,
4313 'supplemental_address_2' => 1,
4314 'supplemental_address_3' => 1,
4317 'postal_code_suffix' => 1,
4318 'state_province' => 1,
4320 'world_region' => 1,
4327 'household_name' => 1,
4328 'organization_name' => 1,
4329 'deceased_date' => 1,
4334 'current_employer' => 1,
4335 // FIXME: should we use defaultHierReturnProperties() for the below?
4336 'do_not_email' => 1,
4339 'do_not_phone' => 1,
4340 'do_not_trade' => 1,
4342 'contact_is_deleted' => 1,
4343 'preferred_communication_method' => 1,
4344 'preferred_language' => 1,
4348 return self
::$_defaultReturnProperties[$mode];
4352 * Get primary condition for a sql clause.
4356 * @return string|NULL
4358 public static function getPrimaryCondition($value) {
4359 if (is_numeric($value)) {
4360 $value = (int ) $value;
4361 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4367 * Wrapper for a simple search query.
4369 * @param array $params
4370 * @param array $returnProperties
4371 * @param bool $count
4375 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4376 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4377 list($select, $from, $where, $having) = $query->query();
4378 $groupBy = ($query->_useGroupBy
) ?
'GROUP BY contact_a.id' : '';
4380 $query = "$select $from $where $groupBy $having";
4385 * These are stub comments as this function needs more explanation - particularly in terms of how it
4386 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4388 * This function was originally written as a wrapper for the api query but is called from multiple places
4389 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4390 * but it is unclear as to whehter that is historical or there is a reason
4391 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4393 * @param array $params
4394 * @param array $returnProperties
4395 * @param null $fields
4396 * @param string $sort
4397 * @param int $offset
4398 * @param int $row_count
4399 * @param bool $smartGroupCache
4400 * ?? update smart group cache?.
4401 * @param bool $count
4402 * Return count obnly.
4403 * @param bool $skipPermissions
4404 * Should permissions be ignored or should the logged in user's permissions be applied.
4406 * This basically correlates to the component.
4407 * @param string $apiEntity
4408 * The api entity being called.
4409 * This sort-of duplicates $mode in a confusing way. Probably not by design.
4413 public static function apiQuery(
4415 $returnProperties = NULL,
4420 $smartGroupCache = TRUE,
4422 $skipPermissions = TRUE,
4423 $mode = CRM_Contact_BAO_Query
::MODE_CONTACTS
,
4427 $query = new CRM_Contact_BAO_Query(
4428 $params, $returnProperties,
4429 NULL, TRUE, FALSE, $mode,
4431 TRUE, $smartGroupCache,
4436 //this should add a check for view deleted if permissions are enabled
4437 if ($skipPermissions) {
4438 $query->_skipDeleteClause
= TRUE;
4440 $query->generatePermissionClause(FALSE, $count);
4442 // note : this modifies _fromClause and _simpleFromClause
4443 $query->includePseudoFieldsJoin($sort);
4445 list($select, $from, $where, $having) = $query->query($count);
4447 $options = $query->_options
;
4448 if (!empty($query->_permissionWhereClause
)) {
4449 if (empty($where)) {
4450 $where = "WHERE $query->_permissionWhereClause";
4453 $where = "$where AND $query->_permissionWhereClause";
4457 $sql = "$select $from $where $having";
4459 // add group by only when API action is not getcount
4460 // otherwise query fetches incorrect count
4461 if ($query->_useGroupBy
&& !$count) {
4462 $sql .= self
::getGroupByFromSelectColumns($query->_select
, 'contact_a.id');
4464 if (!empty($sort)) {
4465 $sort = CRM_Utils_Type
::escape($sort, 'String');
4466 $sql .= " ORDER BY $sort ";
4468 if ($row_count > 0 && $offset >= 0) {
4469 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4470 $row_count = CRM_Utils_Type
::escape($row_count, 'Int');
4471 $sql .= " LIMIT $offset, $row_count ";
4474 $dao = CRM_Core_DAO
::executeQuery($sql);
4476 // @todo derive this from the component class rather than hard-code two options.
4477 $entityIDField = ($mode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) ?
'contribution_id' : 'contact_id';
4480 while ($dao->fetch()) {
4482 $noRows = $dao->rowCount
;
4484 return array($noRows, NULL);
4486 $val = $query->store($dao);
4487 $convertedVals = $query->convertToPseudoNames($dao, TRUE, TRUE);
4489 if (!empty($convertedVals)) {
4490 $val = array_replace_recursive($val, $convertedVals);
4492 $values[$dao->$entityIDField] = $val;
4495 return array($values, $options);
4499 * Get the actual custom field name by stripping off the appended string.
4501 * The string could be _relative, _from, or _to
4503 * @todo use metadata rather than convention to do this.
4505 * @param string $parameterName
4506 * The name of the parameter submitted to the form.
4513 public static function getCustomFieldName($parameterName) {
4514 if (substr($parameterName, -5, 5) == '_from') {
4515 return substr($parameterName, 0, strpos($parameterName, '_from'));
4517 if (substr($parameterName, -9, 9) == '_relative') {
4518 return substr($parameterName, 0, strpos($parameterName, '_relative'));
4520 if (substr($parameterName, -3, 3) == '_to') {
4521 return substr($parameterName, 0, strpos($parameterName, '_to'));
4526 * Convert submitted values for relative custom fields to query object format.
4528 * The query will support the sqlOperator format so convert to that format.
4530 * @param array $formValues
4532 * @param array $params
4533 * Converted parameters for the query object.
4534 * @param string $values
4536 * @param string $fieldName
4537 * Submitted field name. (Matches form field not DB field.)
4539 protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) {
4540 if (empty($values)) {
4541 // e.g we might have relative set & from & to empty. The form flow is a bit funky &
4542 // this function gets called again after they fields have been converted which can get ugly.
4545 $customFieldName = self
::getCustomFieldName($fieldName);
4547 if (substr($fieldName, -9, 9) == '_relative') {
4548 list($from, $to) = CRM_Utils_Date
::getFromTo($values, NULL, NULL);
4551 if ($fieldName == $customFieldName . '_to' && CRM_Utils_Array
::value($customFieldName . '_from', $formValues)) {
4552 // Both to & from are set. We only need to acton one, choosing from.
4556 $from = CRM_Utils_Array
::value($customFieldName . '_from', $formValues, NULL);
4557 $to = CRM_Utils_Array
::value($customFieldName . '_to', $formValues, NULL);
4559 if (self
::isCustomDateField($customFieldName)) {
4560 list($from, $to) = CRM_Utils_Date
::getFromTo(NULL, $from, $to);
4566 $relativeFunction = array('BETWEEN' => array($from, $to));
4569 $relativeFunction = array('>=' => $from);
4573 $relativeFunction = array('<=' => $to);
4585 * Are we dealing with custom field of type date.
4591 public static function isCustomDateField($fieldName) {
4592 if (($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($fieldName)) == FALSE) {
4595 if ('Date' == civicrm_api3('CustomField', 'getvalue', array('id' => $customFieldID, 'return' => 'data_type'))) {
4602 * Has this field already been reformatting to Query object syntax.
4604 * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems
4605 * to come with associated double queries & is possibly damaging performance.
4607 * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns
4610 * @param mixed $values
4611 * Value in formValues for the field.
4615 public static function isAlreadyProcessedForQueryFormat($values) {
4616 if (!is_array($values)) {
4619 if (($operator = CRM_Utils_Array
::value(1, $values)) == FALSE) {
4622 return in_array($operator, CRM_Core_DAO
::acceptedSQLOperators());
4626 * If the state and country are passed remove state.
4628 * Country is implicit from the state, but including both results in
4629 * a poor query as there is no combined index on state AND country.
4633 * @param array $formValues
4635 public static function filterCountryFromValuesIfStateExists(&$formValues) {
4636 if (!empty($formValues['country']) && !empty($formValues['state_province'])) {
4637 // The use of array map sanitises the data by ensuring we are dealing with integers.
4638 $states = implode(', ', array_map('intval', $formValues['state_province']));
4639 $countryList = CRM_Core_DAO
::singleValueQuery(
4640 "SELECT GROUP_CONCAT(country_id) FROM civicrm_state_province WHERE id IN ($states)"
4642 if ($countryList == $formValues['country']) {
4643 unset($formValues['country']);
4649 * For some special cases, grouping by subset of select fields becomes mandatory.
4650 * Hence, full_group_by mode is handled by appending any_value
4651 * keyword to select fields not present in groupBy
4653 * @param array $selectClauses
4654 * @param array $groupBy - Columns already included in GROUP By clause.
4658 public static function appendAnyValueToSelect($selectClauses, $groupBy) {
4659 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4660 $sqlMode = explode(',', CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode'));
4662 // Disable only_full_group_by mode for lower sql versions.
4663 if (version_compare($mysqlVersion, '5.7', '<') ||
(!empty($sqlMode) && !in_array('ONLY_FULL_GROUP_BY', $sqlMode))) {
4664 $key = array_search('ONLY_FULL_GROUP_BY', $sqlMode);
4665 unset($sqlMode[$key]);
4666 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = '" . implode(',', $sqlMode) . "'");
4669 $groupBy = array_map('trim', (array) $groupBy);
4670 $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN)\(/i';
4671 foreach ($selectClauses as $key => &$val) {
4672 list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL);
4673 // append ANY_VALUE() keyword
4674 if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) {
4675 $val = str_replace($selectColumn, "ANY_VALUE({$selectColumn})", $val);
4680 return "SELECT " . implode(', ', $selectClauses) . " ";
4684 * Include Select columns in groupBy clause.
4686 * @param array $selectClauses
4687 * @param array $groupBy - Columns already included in GROUP By clause.
4691 public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NULL) {
4692 $groupBy = (array) $groupBy;
4693 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4694 $sqlMode = CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode');
4696 //return if ONLY_FULL_GROUP_BY is not enabled.
4697 if (!version_compare($mysqlVersion, '5.7', '<') && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
4698 $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN)\(/i';
4699 foreach ($selectClauses as $key => $val) {
4700 $aliasArray = preg_split('/ as /i', $val);
4701 // if more than 1 alias we need to split by ','.
4702 if (count($aliasArray) > 2) {
4703 $aliasArray = preg_split('/,/', $val);
4704 foreach ($aliasArray as $key => $value) {
4705 $alias = current(preg_split('/ as /i', $value));
4706 if (!in_array($alias, $groupBy) && preg_match($regexToExclude, trim($alias)) !== 1) {
4707 $groupBy[] = $alias;
4712 list($selectColumn, $alias) = array_pad($aliasArray, 2, NULL);
4713 $dateRegex = '/^(DATE_FORMAT|DATE_ADD|CASE)/i';
4714 $tableName = current(explode('.', $selectColumn));
4715 $primaryKey = "{$tableName}.id";
4716 // exclude columns which are already included in groupBy and aggregate functions from select
4717 // CRM-18439 - Also exclude the columns which are functionally dependent on columns in $groupBy (MySQL 5.7+)
4718 if (!in_array($selectColumn, $groupBy) && !in_array($primaryKey, $groupBy) && preg_match($regexToExclude, trim($selectColumn)) !== 1) {
4719 if (!empty($alias) && preg_match($dateRegex, trim($selectColumn))) {
4720 $groupBy[] = $alias;
4723 $groupBy[] = $selectColumn;
4730 if (!empty($groupBy)) {
4731 return " GROUP BY " . implode(', ', $groupBy);
4737 * Create and query the db for an contact search.
4739 * @param int $offset
4740 * The offset for the query.
4741 * @param int $rowCount
4742 * The number of rows to return.
4743 * @param string|CRM_Utils_Sort $sort
4744 * The order by string.
4745 * @param bool $count
4746 * Is this a count only query ?.
4747 * @param bool $includeContactIds
4748 * Should we include contact ids?.
4749 * @param bool $sortByChar
4750 * If true returns the distinct array of first characters for search results.
4751 * @param bool $groupContacts
4752 * If true, return only the contact ids.
4753 * @param bool $returnQuery
4754 * Should we return the query as a string.
4755 * @param string $additionalWhereClause
4756 * If the caller wants to further restrict the search (used for components).
4757 * @param null $sortOrder
4758 * @param string $additionalFromClause
4759 * Should be clause with proper joins, effective to reduce where clause load.
4761 * @param bool $skipOrderAndLimit
4763 * @return CRM_Core_DAO
4765 public function searchQuery(
4766 $offset = 0, $rowCount = 0, $sort = NULL,
4767 $count = FALSE, $includeContactIds = FALSE,
4768 $sortByChar = FALSE, $groupContacts = FALSE,
4769 $returnQuery = FALSE,
4770 $additionalWhereClause = NULL, $sortOrder = NULL,
4771 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4774 if ($includeContactIds) {
4775 $this->_includeContactIds
= TRUE;
4776 $this->_whereClause
= $this->whereClause();
4779 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4781 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4782 // and that contact happens to be deleted, set $onlyDeleted to true
4783 foreach ($this->_params
as $values) {
4784 $name = CRM_Utils_Array
::value(0, $values);
4785 $op = CRM_Utils_Array
::value(1, $values);
4786 $value = CRM_Utils_Array
::value(2, $values);
4787 if ($name == 'contact_id' and $op == '=') {
4788 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4789 $onlyDeleted = TRUE;
4795 // building the query string
4796 $groupBy = $groupByCol = NULL;
4798 if (isset($this->_groupByComponentClause
)) {
4799 $groupBy = $this->_groupByComponentClause
;
4800 $groupCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause
));
4801 $groupByCol = explode(', ', $groupCols);
4803 elseif ($this->_useGroupBy
) {
4804 $groupByCol = 'contact_a.id';
4805 $groupBy = ' GROUP BY contact_a.id';
4808 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4809 $groupByCol = 'civicrm_activity.id';
4810 $groupBy = 'GROUP BY civicrm_activity.id ';
4813 $order = $orderBy = $limit = '';
4815 list($order, $additionalFromClause) = $this->prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause);
4817 if ($rowCount > 0 && $offset >= 0) {
4818 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4819 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4820 $limit = " LIMIT $offset, $rowCount ";
4825 $this->_sort
= $sort;
4828 $this->includePseudoFieldsJoin($sort);
4830 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4832 if (!empty($groupByCol)) {
4833 $groupBy = self
::getGroupByFromSelectColumns($this->_select
, $groupByCol);
4836 if ($additionalWhereClause) {
4837 $where = $where . ' AND ' . $additionalWhereClause;
4840 //additional from clause should be w/ proper joins.
4841 if ($additionalFromClause) {
4842 $from .= "\n" . $additionalFromClause;
4845 // if we are doing a transform, do it here
4846 // use the $from, $where and $having to get the contact ID
4847 if ($this->_displayRelationshipType
) {
4848 $this->filterRelatedContacts($from, $where, $having);
4851 if ($skipOrderAndLimit) {
4852 $query = "$select $from $where $having $groupBy";
4855 $query = "$select $from $where $having $groupBy $order $limit";
4862 return CRM_Core_DAO
::singleValueQuery($query);
4865 $dao = CRM_Core_DAO
::executeQuery($query);
4866 if ($groupContacts) {
4868 while ($dao->fetch()) {
4872 return implode(',', $ids);
4879 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4881 * @param string $cacheKey
4882 * @param int $offset
4883 * @param int $rowCount
4884 * @param bool $includeContactIds
4885 * @return CRM_Core_DAO
4887 public function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4888 $this->_includeContactIds
= $includeContactIds;
4889 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4890 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
4891 $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);
4892 $order = " ORDER BY pnc.id";
4893 $groupByCol = array('contact_a.id', 'pnc.id');
4894 $groupBy = self
::getGroupByFromSelectColumns($this->_select
, $groupByCol);
4895 $limit = " LIMIT $offset, $rowCount";
4896 $query = "$select $from $where $groupBy $order $limit";
4898 return CRM_Core_DAO
::executeQuery($query);
4902 * Populate $this->_permissionWhereClause with permission related clause and update other
4903 * query related properties.
4905 * Function calls ACL permission class and hooks to filter the query appropriately
4907 * Note that these 2 params were in the code when extracted from another function
4908 * and a second round extraction would be to make them properties of the class
4910 * @param bool $onlyDeleted
4911 * Only get deleted contacts.
4912 * @param bool $count
4913 * Return Count only.
4915 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4916 if (!$this->_skipPermission
) {
4917 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4918 CRM_Core_Permission
::VIEW
,
4920 $this->_whereTables
,
4923 $this->_skipDeleteClause
4926 // regenerate fromClause since permission might have added tables
4927 if ($this->_permissionWhereClause
) {
4928 //fix for row count in qill (in contribute/membership find)
4930 $this->_useDistinct
= TRUE;
4933 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4934 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4935 // note : this modifies _fromClause and _simpleFromClause
4936 $this->includePseudoFieldsJoin($this->_sort
);
4940 // add delete clause if needed even if we are skipping permission
4942 if (!$this->_skipDeleteClause
) {
4943 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4944 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4948 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4957 public function setSkipPermission($val) {
4958 $this->_skipPermission
= $val;
4962 * @param null $context
4966 public function &summaryContribution($context = NULL) {
4967 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4971 SELECT COUNT( conts.total_amount ) as total_count,
4972 SUM( conts.total_amount ) as total_amount,
4973 AVG( conts.total_amount ) as total_avg,
4974 conts.currency as currency";
4975 if ($this->_permissionWhereClause
) {
4976 $where .= " AND " . $this->_permissionWhereClause
;
4978 if ($context == 'search') {
4979 $where .= " AND contact_a.is_deleted = 0 ";
4981 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4982 if (!empty($financialTypes)) {
4983 $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
4984 $from .= " LEFT JOIN civicrm_line_item li
4985 ON civicrm_contribution.id = li.contribution_id AND
4986 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
4989 $where .= " AND civicrm_contribution.financial_type_id IN (0)";
4992 // make sure contribution is completed - CRM-4989
4993 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4996 $summary['total'] = array();
4997 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4998 $innerQuery = "SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
4999 civicrm_contribution.currency $from $completedWhere";
5000 $query = "$select FROM (
5001 $innerQuery GROUP BY civicrm_contribution.id
5005 $dao = CRM_Core_DAO
::executeQuery($query);
5007 $summary['total']['count'] = 0;
5008 $summary['total']['amount'] = $summary['total']['avg'] = array();
5009 while ($dao->fetch()) {
5010 $summary['total']['count'] +
= $dao->total_count
;
5011 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
5012 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
5015 $orderBy = 'ORDER BY civicrm_contribution_total_amount_count DESC';
5016 $groupBy = 'GROUP BY currency, civicrm_contribution.total_amount';
5017 $modeSQL = "$select, SUBSTRING_INDEX(GROUP_CONCAT(conts.total_amount
5018 ORDER BY conts.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
5019 MAX(conts.civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count
5021 $groupBy $orderBy) as conts
5024 $summary['total']['mode'] = CRM_Contribute_BAO_Contribution
::computeStats('mode', $modeSQL);
5026 $medianSQL = "{$from} {$completedWhere}";
5027 $summary['total']['median'] = CRM_Contribute_BAO_Contribution
::computeStats('median', $medianSQL, 'civicrm_contribution');
5028 $summary['total']['currencyCount'] = count($summary['total']['median']);
5030 if (!empty($summary['total']['amount'])) {
5031 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
5032 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
5033 $summary['total']['mode'] = implode(', ', $summary['total']['mode']);
5034 $summary['total']['median'] = implode(', ', $summary['total']['median']);
5037 $summary['total']['amount'] = $summary['total']['avg'] = $summary['total']['median'] = 0;
5040 // soft credit summary
5041 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
5042 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
5045 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
5046 GROUP BY civicrm_contribution_soft.id
5049 $dao = CRM_Core_DAO
::executeQuery($query);
5050 $summary['soft_credit']['count'] = 0;
5051 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
5052 while ($dao->fetch()) {
5053 $summary['soft_credit']['count'] +
= $dao->total_count
;
5054 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
5055 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
5057 if (!empty($summary['soft_credit']['amount'])) {
5058 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
5059 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
5062 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
5067 //@todo - this could be one query using the IF in mysql - eg
5068 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
5069 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
5070 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
5071 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
5072 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
5073 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
5074 // FROM civicrm_contact contact_a
5075 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
5076 // WHERE ( ... where clause....
5077 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
5081 SELECT COUNT( conts.total_amount ) as cancel_count,
5082 SUM( conts.total_amount ) as cancel_amount,
5083 AVG( conts.total_amount ) as cancel_avg,
5084 conts.currency as currency";
5086 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
5087 if ($context == 'search') {
5088 $where .= " AND contact_a.is_deleted = 0 ";
5091 $query = "$select FROM (
5092 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
5093 GROUP BY civicrm_contribution.id
5097 $dao = CRM_Core_DAO
::executeQuery($query);
5100 if ($dao->fetch()) {
5101 $summary['cancel']['count'] = $dao->cancel_count
;
5102 $summary['cancel']['amount'] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
5103 $summary['cancel']['avg'] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
5107 $summary['cancel']['count'] = 0;
5108 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
5109 while ($dao->fetch()) {
5110 $summary['cancel']['count'] +
= $dao->cancel_count
;
5111 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
5112 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
5114 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
5115 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
5122 * Getter for the qill object.
5126 public function qill() {
5127 return $this->_qill
;
5131 * Default set of return default hier return properties.
5135 public static function &defaultHierReturnProperties() {
5136 if (!isset(self
::$_defaultHierReturnProperties)) {
5137 self
::$_defaultHierReturnProperties = array(
5140 'legal_identifier' => 1,
5141 'external_identifier' => 1,
5142 'contact_type' => 1,
5143 'contact_sub_type' => 1,
5145 'display_name' => 1,
5152 'formal_title' => 1,
5153 'communication_style_id' => 1,
5154 'email_greeting' => 1,
5155 'postal_greeting' => 1,
5159 'preferred_communication_method' => 1,
5160 'do_not_phone' => 1,
5161 'do_not_email' => 1,
5164 'do_not_trade' => 1,
5165 'location' => array(
5167 'location_type' => 1,
5168 'street_address' => 1,
5170 'state_province' => 1,
5172 'postal_code_suffix' => 1,
5175 'phone-Mobile' => 1,
5188 'location_type' => 1,
5189 'street_address' => 1,
5191 'state_province' => 1,
5193 'postal_code_suffix' => 1,
5196 'phone-Mobile' => 1,
5210 return self
::$_defaultHierReturnProperties;
5214 * Build query for a date field.
5216 * @param array $values
5217 * @param string $tableName
5218 * @param string $fieldName
5219 * @param string $dbFieldName
5220 * @param string $fieldTitle
5221 * @param bool $appendTimeStamp
5223 public function dateQueryBuilder(
5224 &$values, $tableName, $fieldName,
5225 $dbFieldName, $fieldTitle,
5226 $appendTimeStamp = TRUE
5228 list($name, $op, $value, $grouping, $wildcard) = $values;
5230 if ($name == "{$fieldName}_low" ||
5231 $name == "{$fieldName}_high"
5233 if (isset($this->_rangeCache
[$fieldName]) ||
!$value) {
5236 $this->_rangeCache
[$fieldName] = 1;
5238 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
5240 if ($name == $fieldName . '_low') {
5242 $firstPhrase = ts('greater than or equal to');
5243 $firstDate = CRM_Utils_Date
::processDate($value);
5245 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5246 if (!empty($secondValues) && $secondValues[2]) {
5248 $secondPhrase = ts('less than or equal to');
5249 $secondValue = $secondValues[2];
5251 if ($appendTimeStamp && strlen($secondValue) == 10) {
5252 $secondValue .= ' 23:59:59';
5254 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5257 elseif ($name == $fieldName . '_high') {
5259 $firstPhrase = ts('less than or equal to');
5261 if ($appendTimeStamp && strlen($value) == 10) {
5262 $value .= ' 23:59:59';
5264 $firstDate = CRM_Utils_Date
::processDate($value);
5266 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5267 if (!empty($secondValues) && $secondValues[2]) {
5269 $secondPhrase = ts('greater than or equal to');
5270 $secondValue = $secondValues[2];
5271 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5275 if (!$appendTimeStamp) {
5276 $firstDate = substr($firstDate, 0, 8);
5278 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5281 if (!$appendTimeStamp) {
5282 $secondDate = substr($secondDate, 0, 8);
5284 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5287 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5289 $this->_where
[$grouping][] = "
5290 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5291 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5293 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5296 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5297 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5301 if ($name == $fieldName) {
5302 //In Get API, for operators other then '=' the $value is in array(op => value) format
5303 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5305 $value = $value[$op];
5308 $date = $format = NULL;
5309 if (strstr($op, 'IN')) {
5311 foreach ($value as &$date) {
5312 $date = CRM_Utils_Date
::processDate($date);
5313 if (!$appendTimeStamp) {
5314 $date = substr($date, 0, 8);
5316 $format[] = CRM_Utils_Date
::customFormat($date);
5318 $date = "('" . implode("','", $value) . "')";
5319 $format = implode(', ', $format);
5321 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5322 $date = CRM_Utils_Date
::processDate($value);
5323 if (!$appendTimeStamp) {
5324 $date = substr($date, 0, 8);
5326 $format = CRM_Utils_Date
::customFormat($date);
5331 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5334 $this->_where
[$grouping][] = self
::buildClause("{$tableName}.{$dbFieldName}", $op);
5337 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5339 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
5340 $this->_qill
[$grouping][] = "$fieldTitle $op $format";
5346 * @param string $tableName
5347 * @param string $fieldName
5348 * @param string $dbFieldName
5349 * @param $fieldTitle
5350 * @param null $options
5352 public function numberRangeBuilder(
5354 $tableName, $fieldName,
5355 $dbFieldName, $fieldTitle,
5358 list($name, $op, $value, $grouping, $wildcard) = $values;
5360 if ($name == "{$fieldName}_low" ||
5361 $name == "{$fieldName}_high"
5363 if (isset($this->_rangeCache
[$fieldName])) {
5366 $this->_rangeCache
[$fieldName] = 1;
5368 $secondOP = $secondPhrase = $secondValue = NULL;
5370 if ($name == "{$fieldName}_low") {
5372 $firstPhrase = ts('greater than');
5374 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5375 if (!empty($secondValues)) {
5377 $secondPhrase = ts('less than');
5378 $secondValue = $secondValues[2];
5383 $firstPhrase = ts('less than');
5385 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5386 if (!empty($secondValues)) {
5388 $secondPhrase = ts('greater than');
5389 $secondValue = $secondValues[2];
5394 $this->_where
[$grouping][] = "
5395 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5396 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5398 $displayValue = $options ?
$options[$value] : $value;
5399 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5401 $this->_qill
[$grouping][]
5402 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5405 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5406 $displayValue = $options ?
$options[$value] : $value;
5407 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5409 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5414 if ($name == $fieldName) {
5418 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5420 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5421 $displayValue = $options ?
$options[$value] : $value;
5422 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5429 * @param string $tableName
5430 * @param string $fieldName
5431 * @param string $dbFieldName
5432 * @param $fieldTitle
5433 * @param null $options
5435 public function ageRangeQueryBuilder(
5437 $tableName, $fieldName,
5438 $dbFieldName, $fieldTitle,
5441 list($name, $op, $value, $grouping, $wildcard) = $values;
5443 $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
5444 $asofDate = NULL; // will be treated as current day
5445 if ($asofDateValues) {
5446 $asofDate = CRM_Utils_Date
::processDate($asofDateValues[2]);
5447 $asofDateFormat = CRM_Utils_Date
::customFormat(substr($asofDate, 0, 8));
5448 $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat;
5451 if ($name == "{$fieldName}_low" ||
5452 $name == "{$fieldName}_high"
5454 if (isset($this->_rangeCache
[$fieldName])) {
5457 $this->_rangeCache
[$fieldName] = 1;
5459 $secondOP = $secondPhrase = $secondValue = NULL;
5461 if ($name == "{$fieldName}_low") {
5462 $firstPhrase = ts('greater than or equal to');
5463 // NB: age > X means date of birth < Y
5465 $firstDate = self
::calcDateFromAge($asofDate, $value, 'min');
5467 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5468 if (!empty($secondValues)) {
5470 $secondPhrase = ts('less than or equal to');
5471 $secondValue = $secondValues[2];
5472 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'max');
5477 $firstPhrase = ts('less than or equal to');
5478 $firstDate = self
::calcDateFromAge($asofDate, $value, 'max');
5480 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5481 if (!empty($secondValues)) {
5483 $secondPhrase = ts('greater than or equal to');
5484 $secondValue = $secondValues[2];
5485 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'min');
5490 $this->_where
[$grouping][] = "
5491 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5492 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5494 $displayValue = $options ?
$options[$value] : $value;
5495 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5497 $this->_qill
[$grouping][]
5498 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5501 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5502 $displayValue = $options ?
$options[$value] : $value;
5503 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5505 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5511 * Calculate date from age.
5513 * @param string $asofDate
5515 * @param string $type
5519 public static function calcDateFromAge($asofDate, $age, $type) {
5520 $date = new DateTime($asofDate);
5521 if ($type == "min") {
5522 // minimum age is $age: dob <= date - age "235959"
5523 $date->sub(new DateInterval("P" . $age . "Y"));
5524 return $date->format('Ymd') . "235959";
5527 // max age is $age: dob >= date - (age + 1y) + 1d "000000"
5528 $date->sub(new DateInterval("P" . ($age +
1) . "Y"))->add(new DateInterval("P1D"));
5529 return $date->format('Ymd') . "000000";
5534 * Given the field name, operator, value & its data type
5535 * builds the where Clause for the query
5536 * used for handling 'IS NULL'/'IS NOT NULL' operators
5538 * @param string $field
5542 * @param string $value
5544 * @param string $dataType
5545 * Data type of the field.
5548 * Where clause for the query.
5550 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5552 $clause = "$field $op";
5560 $clause = " (NULLIF($field, '') IS NULL) ";
5563 case 'IS NOT EMPTY':
5564 $clause = " (NULLIF($field, '') IS NOT NULL) ";
5569 // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
5570 if (!empty($value) && (!is_array($value) ||
!array_key_exists($op, $value))) {
5571 $value = array($op => (array) $value);
5575 if (empty($dataType)) {
5576 $dataType = 'String';
5578 if (is_array($value)) {
5579 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5580 // widely used and consistent across the codebase
5581 // adding this here won't accept the search functions which don't submit an array
5582 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, $value, $dataType)) != FALSE) {
5584 return $queryString;
5587 // 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))
5588 // but we got only array(2,5) from the form.
5589 // We could get away with keeping this in 4.6 if we make it such that it throws an enotice in 4.7 so
5590 // people have to de-slopify it.
5591 if (!empty($value[0])) {
5592 if ($op != 'BETWEEN') {
5593 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReport;
5595 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => $value), $dataType)) != FALSE) {
5596 return $queryString;
5601 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReportUsingOldFormat;
5602 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => array_keys($value)), $dataType)) != FALSE) {
5603 return $queryString;
5608 $value = CRM_Utils_Type
::escape($value, $dataType);
5609 // if we don't have a dataType we should assume
5610 if ($dataType == 'String' ||
$dataType == 'Text') {
5611 $value = "'" . strtolower($value) . "'";
5613 return "$clause $value";
5618 * @param bool $reset
5622 public function openedSearchPanes($reset = FALSE) {
5623 if (!$reset ||
empty($this->_whereTables
)) {
5624 return self
::$_openedPanes;
5627 // pane name to table mapper
5628 $panesMapper = array(
5629 ts('Contributions') => 'civicrm_contribution',
5630 ts('Memberships') => 'civicrm_membership',
5631 ts('Events') => 'civicrm_participant',
5632 ts('Relationships') => 'civicrm_relationship',
5633 ts('Activities') => 'civicrm_activity',
5634 ts('Pledges') => 'civicrm_pledge',
5635 ts('Cases') => 'civicrm_case',
5636 ts('Grants') => 'civicrm_grant',
5637 ts('Address Fields') => 'civicrm_address',
5638 ts('Notes') => 'civicrm_note',
5639 ts('Change Log') => 'civicrm_log',
5640 ts('Mailings') => 'civicrm_mailing',
5642 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5644 foreach (array_keys($this->_whereTables
) as $table) {
5645 if ($panName = array_search($table, $panesMapper)) {
5646 self
::$_openedPanes[$panName] = TRUE;
5650 return self
::$_openedPanes;
5656 public function setOperator($operator) {
5657 $validOperators = array('AND', 'OR');
5658 if (!in_array($operator, $validOperators)) {
5661 $this->_operator
= $operator;
5667 public function getOperator() {
5668 return $this->_operator
;
5676 public function filterRelatedContacts(&$from, &$where, &$having) {
5677 static $_rTypeProcessed = NULL;
5678 static $_rTypeFrom = NULL;
5679 static $_rTypeWhere = NULL;
5681 if (!$_rTypeProcessed) {
5682 $_rTypeProcessed = TRUE;
5684 // create temp table with contact ids
5685 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5686 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5687 CRM_Core_DAO
::executeQuery($sql);
5690 REPLACE INTO $tableName ( contact_id )
5696 CRM_Core_DAO
::executeQuery($sql);
5698 $qillMessage = ts('Contacts with a Relationship Type of: ');
5699 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5701 if (is_numeric($this->_displayRelationshipType
)) {
5702 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5704 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5705 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5708 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5709 AND displayRelType.is_active = 1
5713 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5714 if ($dirOne == 'a') {
5715 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5717 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5718 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5722 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5724 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5725 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5729 WHERE displayRelType.relationship_type_id = $relType
5730 AND displayRelType.is_active = 1
5733 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5736 if (!empty($this->_permissionWhereClause
)) {
5737 $_rTypeWhere .= "AND $this->_permissionWhereClause";
5740 if (strpos($from, $_rTypeFrom) === FALSE) {
5741 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5742 // this happens when we have an event_type in the quert (CRM-7969)
5743 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5744 $from .= $_rTypeFrom;
5745 $where = $_rTypeWhere;
5752 * See CRM-19811 for why this is database hurty without apparent benefit.
5758 public static function caseImportant($op) {
5760 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5764 * @param $returnProperties
5769 public static function componentPresent(&$returnProperties, $prefix) {
5770 foreach ($returnProperties as $name => $dontCare) {
5771 if (substr($name, 0, strlen($prefix)) == $prefix) {
5779 * Builds the necessary structures for all fields that are similar to option value look-ups.
5781 * @param string $name
5782 * the name of the field.
5784 * the sql operator, this function should handle ALL SQL operators.
5785 * @param string $value
5786 * depends on the operator and who's calling the query builder.
5787 * @param int $grouping
5788 * the index where to place the where clause.
5789 * @param string $daoName
5791 * @param array $field
5792 * an array that contains various properties of the field identified by $name.
5793 * @param string $label
5794 * The label for this field element.
5795 * @param string $dataType
5796 * The data type for this element.
5797 * @param bool $useIDsOnly
5799 public function optionValueQuery(
5807 $dataType = 'String',
5811 $pseudoFields = array(
5818 'communication_style_id',
5822 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5823 if ($tableName == 'civicrm_contact') {
5824 $wc = "contact_a.$fieldName";
5827 $wc = "$tableName.id";
5831 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
5832 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5834 if (in_array($name, $pseudoFields)) {
5835 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5836 $wc = "contact_a.{$name}_id";
5838 $dataType = 'Positive';
5839 $value = (!$value) ?
0 : $value;
5841 if ($name == "world_region") {
5842 $field['name'] = $name;
5845 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue($daoName, $field['name'], $value, $op);
5846 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillop, 3 => $qillVal));
5847 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5851 * Check and explode a user defined numeric string into an array
5852 * this was the protocol used by search builder in the old old days before we had
5853 * super nice js widgets to do the hard work
5855 * @param string $string
5856 * @param string $dataType
5857 * The dataType we should check for the values, default integer.
5859 * @return bool|array
5860 * false if string does not match the pattern
5861 * array of numeric values if string does match the pattern
5863 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5864 $string = trim($string);
5865 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5869 $string = substr($string, 1, -1);
5870 $values = explode(',', $string);
5871 if (empty($values)) {
5875 $returnValues = array();
5876 foreach ($values as $v) {
5877 if ($dataType == 'Integer' && !is_numeric($v)) {
5880 elseif ($dataType == 'String' && !is_string($v)) {
5883 $returnValues[] = trim($v);
5886 if (empty($returnValues)) {
5890 return $returnValues;
5894 * Convert the pseudo constants id's to their names
5896 * @param CRM_Core_DAO $dao
5897 * @param bool $return
5898 * @param bool $usedForAPI
5900 * @return array|NULL
5902 public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) {
5903 if (empty($this->_pseudoConstantsSelect
)) {
5907 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5908 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5912 if (is_object($dao) && property_exists($dao, $value['idCol'])) {
5913 $val = $dao->{$value['idCol']};
5914 if ($key == 'groups') {
5915 $dao->groups
= $this->convertGroupIDStringToLabelString($dao, $val);
5919 if (CRM_Utils_System
::isNull($val)) {
5922 elseif (!empty($value['pseudoconstant'])) {
5923 // If pseudoconstant is set that is kind of defacto for 'we have a bit more info about this'
5924 // and we can use the metadata to figure it out.
5925 // ideally this bit of IF will absorb & replace all the rest in time as we move to
5926 // more metadata based choices.
5927 if (strpos($val, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
5928 $dbValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($val, CRM_Core_DAO
::VALUE_SEPARATOR
));
5929 foreach ($dbValues as $pseudoValue) {
5930 $convertedValues[] = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $pseudoValue);
5933 $dao->$key = ($usedForAPI) ?
$convertedValues : implode(', ', $convertedValues);
5934 $realFieldName = CRM_Utils_Array
::value('field_name', $this->_pseudoConstantsSelect
[$key]);
5935 if ($usedForAPI && $realFieldName) {
5936 // normally we would see 2 fields returned for pseudoConstants. An exception is
5937 // preferred_communication_method where there is no id-variant.
5938 // For the api we prioritise getting the real data returned.
5939 // over the resolved version
5940 $dao->$realFieldName = $dbValues;
5945 // This is basically the same as the default but since we have the bao we can use
5946 // a cached function.
5947 $dao->$key = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $val);
5950 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5952 $idColumn = "{$key}_id";
5953 $dao->$idColumn = $val;
5955 if ($key == 'state_province_name') {
5956 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::stateProvince($val);
5959 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5962 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5963 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5965 // @todo handle this in the section above for pseudoconstants.
5966 elseif (in_array($value['pseudoField'], array('participant_role_id', 'participant_role'))) {
5967 // @todo define bao on this & merge into the above condition.
5968 $viewValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val);
5970 if ($value['pseudoField'] == 'participant_role') {
5971 $pseudoOptions = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'role_id');
5972 foreach ($viewValues as $k => $v) {
5973 $viewValues[$k] = $pseudoOptions[$v];
5976 $dao->$key = ($usedForAPI && count($viewValues) > 1) ?
$viewValues : implode(', ', $viewValues);
5979 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5980 $dao->$key = $labels[$val];
5983 // return converted values in array format
5985 if (strpos($key, '-') !== FALSE) {
5986 $keyVal = explode('-', $key);
5987 $current = &$values;
5988 $lastElement = array_pop($keyVal);
5989 foreach ($keyVal as $v) {
5990 if (!array_key_exists($v, $current)) {
5991 $current[$v] = array();
5993 $current = &$current[$v];
5995 $current[$lastElement] = $dao->$key;
5998 $values[$key] = $dao->$key;
6005 'gender_id' => 'gender',
6006 'prefix_id' => 'individual_prefix',
6007 'suffix_id' => 'individual_suffix',
6008 'communication_style_id' => 'communication_style',
6009 ) as $realField => $labelField) {
6010 // This is a temporary routine for handling these fields while
6011 // we figure out how to handled them based on metadata in
6012 /// export and search builder. CRM-19815, CRM-19830.
6013 if (isset($dao->$realField) && is_numeric($dao->$realField) && isset($dao->$labelField)) {
6014 $dao->$realField = $dao->$labelField;
6022 * Include pseudo fields LEFT JOIN.
6023 * @param string|array $sort can be a object or string
6025 * @return array|NULL
6027 public function includePseudoFieldsJoin($sort) {
6028 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
6031 $sort = is_string($sort) ?
$sort : $sort->orderBy();
6034 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
6035 if (!empty($value['table'])) {
6036 $regex = "/({$value['table']}\.|{$name})/";
6037 if (preg_match($regex, $sort)) {
6038 $this->_elemnt
[$value['element']] = 1;
6039 $this->_select
[$value['element']] = $value['select'];
6040 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
6041 $present[$value['table']] = $value['join'];
6045 $presentSimpleFrom = $present;
6047 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
6048 array_key_exists('civicrm_country', $presentSimpleFrom)
6050 unset($presentSimpleFrom['civicrm_country']);
6052 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
6053 array_key_exists('civicrm_country', $present)
6055 unset($present['civicrm_country']);
6058 $presentClause = $presentSimpleFromClause = NULL;
6059 if (!empty($present)) {
6060 $presentClause = implode(' ', $present);
6062 if (!empty($presentSimpleFrom)) {
6063 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
6066 $this->_fromClause
= $this->_fromClause
. $presentClause;
6067 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
6069 return array($presentClause, $presentSimpleFromClause);
6073 * Build qill for field.
6075 * Qill refers to the query detail visible on the UI.
6077 * @param string $daoName
6078 * @param string $fieldName
6079 * @param mixed $fieldValue
6081 * @param array $pseudoExtraParam
6083 * Type of the field per CRM_Utils_Type
6087 public static function buildQillForFieldValue(
6092 $pseudoExtraParam = array(),
6093 $type = CRM_Utils_Type
::T_STRING
6095 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
6097 //API usually have fieldValue format as array(operator => array(values)),
6098 //so we need to separate operator out of fieldValue param
6099 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
6100 $op = key($fieldValue);
6101 $fieldValue = $fieldValue[$op];
6104 // if Operator chosen is NULL/EMPTY then
6105 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
6106 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), '');
6109 if ($fieldName == 'activity_type_id') {
6110 $pseudoOptions = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
6112 elseif ($fieldName == 'country_id') {
6113 $pseudoOptions = CRM_Core_PseudoConstant
::country();
6115 elseif ($fieldName == 'county_id') {
6116 $pseudoOptions = CRM_Core_PseudoConstant
::county();
6118 elseif ($fieldName == 'world_region') {
6119 $pseudoOptions = CRM_Core_PseudoConstant
::worldRegion();
6121 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
6122 $pseudoOptions = CRM_Event_BAO_Event
::getEvents(0, $fieldValue, TRUE, TRUE, TRUE);
6124 elseif ($fieldName == 'contribution_product_id') {
6125 $pseudoOptions = CRM_Contribute_PseudoConstant
::products();
6127 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
6128 $pseudoOptions = CRM_Core_PseudoConstant
::group();
6130 elseif ($daoName == 'CRM_Batch_BAO_EntityBatch' && $fieldName == 'batch_id') {
6131 $pseudoOptions = CRM_Contribute_PseudoConstant
::batch();
6134 $pseudoOptions = CRM_Core_PseudoConstant
::get($daoName, $fieldName, $pseudoExtraParam);
6137 if (is_array($fieldValue)) {
6138 $qillString = array();
6139 if (!empty($pseudoOptions)) {
6140 foreach ((array) $fieldValue as $val) {
6141 $qillString[] = CRM_Utils_Array
::value($val, $pseudoOptions, $val);
6143 $fieldValue = implode(', ', $qillString);
6146 if ($type == CRM_Utils_Type
::T_DATE
) {
6147 foreach ($fieldValue as $index => $value) {
6148 $fieldValue[$index] = CRM_Utils_Date
::customFormat($value);
6152 // @todo - this is a bit specific (one operator).
6153 // However it is covered by a unit test so can be altered later with
6155 if ($op == 'BETWEEN') {
6156 $separator = ' AND ';
6158 $fieldValue = implode($separator, $fieldValue);
6161 elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) {
6162 $fieldValue = $pseudoOptions[$fieldValue];
6164 elseif ($type === CRM_Utils_Type
::T_DATE
) {
6165 $fieldValue = CRM_Utils_Date
::customFormat($fieldValue);
6168 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), $fieldValue);
6172 * Alter value to reflect wildcard settings.
6174 * The form will have tried to guess whether this is a good field to wildcard but there is
6175 * also a site-wide setting that specifies whether it is OK to append the wild card to the beginning
6176 * or only the end of the string
6178 * @param bool $wildcard
6179 * This is a bool made on an assessment 'elsewhere' on whether this is a good field to wildcard.
6181 * Generally '=' or 'LIKE'.
6182 * @param string $value
6183 * The search string.
6187 public static function getWildCardedValue($wildcard, $op, $value) {
6188 if ($wildcard && $op == 'LIKE') {
6189 if (CRM_Core_Config
::singleton()->includeWildCardInName
&& (substr($value, 0, 1) != '%')) {
6202 * Process special fields of Search Form in OK (Operator in Key) format
6204 * @param array $formValues
6205 * @param array $specialFields
6206 * Special params to be processed
6207 * @param array $changeNames
6208 * Array of fields whose name should be changed
6210 public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = array()) {
6211 // Array of special fields whose value are considered only for NULL or EMPTY operators
6212 $nullableFields = array('contribution_batch_id');
6214 foreach ($specialFields as $element) {
6215 $value = CRM_Utils_Array
::value($element, $formValues);
6217 if (is_array($value)) {
6218 if (in_array($element, array_keys($changeNames))) {
6219 unset($formValues[$element]);
6220 $element = $changeNames[$element];
6222 $formValues[$element] = array('IN' => $value);
6224 elseif (in_array($value, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
6225 $formValues[$element] = array($value => 1);
6227 elseif (!in_array($element, $nullableFields)) {
6228 // if wildcard is already present return searchString as it is OR append and/or prepend with wildcard
6229 $isWilcard = strstr($value, '%') ?
FALSE : CRM_Core_Config
::singleton()->includeWildCardInName
;
6230 $formValues[$element] = array('LIKE' => self
::getWildCardedValue($isWilcard, 'LIKE', $value));
6237 * Parse and assimilate the various sort options.
6239 * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`,
6240 * `email`), the related table may be joined automatically.
6242 * At time of writing, this code is deeply flawed and should be rewritten. For the moment,
6243 * it's been extracted to a standalone function.
6245 * @param string|CRM_Utils_Sort $sort
6246 * The order by string.
6247 * @param bool $sortByChar
6248 * If true returns the distinct array of first characters for search results.
6249 * @param null $sortOrder
6250 * Who knows? Hu knows. He who knows Hu knows who.
6251 * @param string $additionalFromClause
6252 * Should be clause with proper joins, effective to reduce where clause load.
6254 * list(string $orderByClause, string $additionalFromClause).
6256 protected function prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause) {
6258 $orderByArray = array();
6259 $config = CRM_Core_Config
::singleton();
6260 if ($config->includeOrderByClause ||
6261 isset($this->_distinctComponentClause
)
6264 if (is_string($sort)) {
6268 $orderBy = trim($sort->orderBy());
6270 // Deliberately remove the backticks again, as they mess up the evil
6271 // string munging below. This balanced by re-escaping before use.
6272 $orderBy = str_replace('`', '', $orderBy);
6274 if (!empty($orderBy)) {
6275 // this is special case while searching for
6276 // change log CRM-1718
6277 if (preg_match('/sort_name/i', $orderBy)) {
6278 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
6281 $order = " ORDER BY $orderBy";
6284 $order .= " $sortOrder";
6287 // always add contact_a.id to the ORDER clause
6288 // so the order is deterministic
6289 if (strpos('contact_a.id', $order) === FALSE) {
6290 $order .= ", contact_a.id";
6294 elseif ($sortByChar) {
6295 $orderByArray = array("UPPER(LEFT(contact_a.sort_name, 1)) asc");
6298 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
6301 if (!$order && empty($orderByArray)) {
6302 return array($order, $additionalFromClause);
6304 // Remove this here & add it at the end for simplicity.
6305 $order = trim(str_replace('ORDER BY', '', $order));
6307 // hack for order clause
6308 if (!empty($orderByArray)) {
6309 $order = implode(', ', $orderByArray);
6312 $orderByArray = explode(',', $order);
6314 foreach ($orderByArray as $orderByClause) {
6315 $orderByClauseParts = explode(' ', trim($orderByClause));
6316 $field = $orderByClauseParts[0];
6317 $direction = isset($orderByClauseParts[1]) ?
$orderByClauseParts[1] : 'asc';
6322 $this->_tables
["civicrm_address"] = $this->_whereTables
["civicrm_address"] = 1;
6323 $order = str_replace($field, "civicrm_address.{$field}", $order);
6327 case 'state_province':
6328 $this->_tables
["civicrm_{$field}"] = $this->_whereTables
["civicrm_{$field}"] = 1;
6329 if (is_array($this->_returnProperties
) && empty($this->_returnProperties
)) {
6330 $additionalFromClause .= " LEFT JOIN civicrm_{$field} ON civicrm_{$field}.id = civicrm_address.{$field}_id";
6332 $order = str_replace($field, "civicrm_{$field}.name", $order);
6336 $this->_tables
["civicrm_email"] = $this->_whereTables
["civicrm_email"] = 1;
6337 $order = str_replace($field, "civicrm_email.{$field}", $order);
6341 foreach ($this->_pseudoConstantsSelect
as $key => $pseudoConstantMetadata) {
6342 // By replacing the join to the option value table with the mysql construct
6343 // ORDER BY field('contribution_status_id', 2,1,4)
6344 // we can remove a join. In the case of the option value join it is
6345 /// a join known to cause slow queries.
6346 // @todo cover other pseudoconstant types. Limited to option group ones in the
6347 // first instance for scope reasons. They require slightly different handling as the column (label)
6348 // is not declared for them.
6349 // @todo so far only integer fields are being handled. If we add string fields we need to look at
6351 if (isset($pseudoConstantMetadata['pseudoconstant'])
6352 && isset($pseudoConstantMetadata['pseudoconstant']['optionGroupName'])
6353 && $field === CRM_Utils_Array
::value('optionGroupName', $pseudoConstantMetadata['pseudoconstant'])
6355 $sortedOptions = $pseudoConstantMetadata['bao']::buildOptions($pseudoConstantMetadata['pseudoField'], NULL, array(
6356 'orderColumn' => 'label',
6358 $order = str_replace("$field $direction", "field({$pseudoConstantMetadata['pseudoField']}," . implode(',', array_keys($sortedOptions)) . ") $direction", $order);
6360 //CRM-12565 add "`" around $field if it is a pseudo constant
6361 // This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
6362 if (!empty($pseudoConstantMetadata['element']) && $pseudoConstantMetadata['element'] == $field) {
6363 $order = str_replace($field, "`{$field}`", $order);
6369 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6370 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6372 // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
6373 // clause. But this magic helper which forgivingly reescapes ORDER BY.
6374 // Note: $sortByChar implies that $order was hard-coded/trusted, so it can do funky things.
6376 return array(' ORDER BY ' . $order, $additionalFromClause);
6379 $order = CRM_Utils_Type
::escape($order, 'MysqlOrderBy');
6380 return array(' ORDER BY ' . $order, $additionalFromClause);
6385 * Convert a string of group IDs to a string of group labels.
6387 * The original string may include duplicates and groups the user does not have
6388 * permission to see.
6390 * @param CRM_Core_DAO $dao
6391 * @param string $val
6395 public function convertGroupIDStringToLabelString(&$dao, $val) {
6396 $groupIDs = explode(',', $val);
6397 // Note that groups that the user does not have permission to will be excluded (good).
6398 $groups = array_intersect_key(CRM_Core_PseudoConstant
::group(), array_flip($groupIDs));
6399 return implode(', ', $groups);
6404 * Set the qill and where properties for a field.
6406 * This function is intended as a short-term function to encourage refactoring
6407 * & re-use - but really we should just have less special-casing.
6409 * @param string $name
6411 * @param string|array $value
6412 * @param string $grouping
6413 * @param string $field
6415 public function setQillAndWhere($name, $op, $value, $grouping, $field) {
6416 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
6417 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
6418 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(
6419 1 => $field['title'],
6426 * Has the pseudoconstant of the field been requested.
6428 * For example if the field is payment_instrument_id then it
6429 * has been requested if either payment_instrument_id or payment_instrument
6430 * have been requested. Payment_instrument is the option groun name field value.
6432 * @param array $field
6433 * @param string $fieldName
6434 * The unique name of the field - ie. the one it will be aliased to in the query.
6438 private function pseudoConstantNameIsInReturnProperties($field, $fieldName = NULL) {
6439 if (!isset($field['pseudoconstant']['optionGroupName'])) {
6443 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
6446 if (CRM_Utils_Array
::value($fieldName, $this->_returnProperties
)) {
6449 // Is this still required - the above goes off the unique name. Test with things like
6450 // communication_prefferences & prefix_id.
6451 if (CRM_Utils_Array
::value($field['name'], $this->_returnProperties
)) {