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);
683 // if this is a hierarchical name, we ignore it
684 $names = explode('-', $name);
685 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
689 // make an exception for special cases, to add the field in select clause
690 $makeException = FALSE;
692 //special handling for groups/tags
693 if (in_array($name, array('groups', 'tags', 'notes'))
694 && isset($this->_returnProperties
[substr($name, 0, -1)])
696 // @todo instead of setting make exception to get us into
697 // an if clause that has handling for these fields buried with in it
698 // move the handling to here.
699 $makeException = TRUE;
702 // since note has 3 different options we need special handling
703 // note / note_subject / note_body
704 if ($name == 'notes') {
705 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
706 if (isset($this->_returnProperties
[$noteField])) {
707 $makeException = TRUE;
713 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
715 !empty($this->_paramLookup
[$name])
716 ||
!empty($this->_returnProperties
[$name])
717 ||
$this->pseudoConstantNameIsInReturnProperties($field)
721 // add to cfIDs array if not present
722 if (!array_key_exists($cfID, $this->_cfIDs
)) {
723 $this->_cfIDs
[$cfID] = array();
726 elseif (isset($field['where'])) {
727 list($tableName, $fieldName) = explode('.', $field['where'], 2);
728 if (isset($tableName)) {
729 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
730 $this->_tables
['civicrm_address'] = 1;
731 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
732 $this->_element
['address_id'] = 1;
735 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
736 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
738 if ($tableName == 'im_provider') {
739 CRM_Core_OptionValue
::select($this);
742 if (in_array($tableName,
743 array('email_greeting', 'postal_greeting', 'addressee'))) {
744 $this->_element
["{$name}_id"] = 1;
745 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
746 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
747 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
748 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
750 if ($tableName == 'email_greeting') {
752 $this->_pseudoConstantsSelect
[$name]['join']
753 = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
754 $this->_pseudoConstantsSelect
[$name]['join'] .=
755 " 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 ) ";
757 elseif ($tableName == 'postal_greeting') {
759 $this->_pseudoConstantsSelect
[$name]['join']
760 = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
761 $this->_pseudoConstantsSelect
[$name]['join'] .=
762 " 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 ) ";
764 elseif ($tableName == 'addressee') {
766 $this->_pseudoConstantsSelect
[$name]['join']
767 = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
768 $this->_pseudoConstantsSelect
[$name]['join'] .=
769 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
771 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
774 $greetField = "{$name}_display";
775 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
776 $this->_element
[$greetField] = 1;
778 $greetField = "{$name}_custom";
779 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
780 $this->_element
[$greetField] = 1;
784 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
785 $this->_tables
[$tableName] = 1;
788 // also get the id of the tableName
789 $tName = substr($tableName, 8);
790 if (in_array($tName, array('country', 'state_province', 'county'))) {
791 if ($tName == 'state_province') {
792 $this->_pseudoConstantsSelect
['state_province_name'] = array(
793 'pseudoField' => "{$tName}",
794 'idCol' => "{$tName}_id",
795 'bao' => 'CRM_Core_BAO_Address',
796 'table' => "civicrm_{$tName}",
797 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
800 $this->_pseudoConstantsSelect
[$tName] = array(
801 'pseudoField' => 'state_province_abbreviation',
802 'idCol' => "{$tName}_id",
803 'table' => "civicrm_{$tName}",
804 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
808 $this->_pseudoConstantsSelect
[$name] = array(
809 'pseudoField' => "{$tName}_id",
810 'idCol' => "{$tName}_id",
811 'bao' => 'CRM_Core_BAO_Address',
812 'table' => "civicrm_{$tName}",
813 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
817 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
818 $this->_element
["{$tName}_id"] = 1;
820 elseif ($tName != 'contact') {
821 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
822 $this->_element
["{$tName}_id"] = 1;
825 //special case for phone
826 if ($name == 'phone') {
827 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
828 $this->_element
['phone_type_id'] = 1;
831 // if IM then select provider_id also
832 // to get "IM Service Provider" in a file to be exported, CRM-3140
834 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
835 $this->_element
['provider_id'] = 1;
838 if ($tName == 'contact' && $fieldName == 'organization_name') {
839 // special case, when current employer is set for Individual contact
840 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
842 elseif ($tName == 'contact' && $fieldName === 'id') {
843 // Handled elsewhere, explicitly ignore. Possibly for all tables...
845 elseif (in_array($tName, array('country', 'county'))) {
846 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
847 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
849 elseif ($tName == 'state_province') {
850 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
851 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
853 elseif (strpos($name, 'contribution_soft_credit') !== FALSE) {
854 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled($this->_params
)) {
855 $this->_select
[$name] = "{$field['where']} as `$name`";
859 // If we have an option group defined then rather than joining the option value table in
860 // (which is an unindexed join) we render the option value on output.
861 // @todo - extend this to other pseudoconstants.
862 if ($this->pseudoConstantNameIsInReturnProperties($field)) {
863 $pseudoFieldName = $field['pseudoconstant']['optionGroupName'];
864 $this->_pseudoConstantsSelect
[$pseudoFieldName] = array(
865 'pseudoField' => $field['name'],
866 'idCol' => $field['name'],
867 'field_name' => $field['name'],
868 'bao' => $field['bao'],
869 'pseudoconstant' => $field['pseudoconstant'],
871 $this->_tables
[$tableName] = 1;
872 $this->_element
[$pseudoFieldName] = 1;
874 $this->_select
[$name] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$name`");
876 if (!in_array($tName, array('state_province', 'country', 'county'))) {
877 $this->_element
[$name] = 1;
882 elseif ($name === 'tags') {
883 //@todo move this handling outside the big IF & ditch $makeException
884 $this->_useGroupBy
= TRUE;
885 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
886 $this->_element
[$name] = 1;
887 $this->_tables
['civicrm_tag'] = 1;
888 $this->_tables
['civicrm_entity_tag'] = 1;
890 elseif ($name === 'groups') {
891 //@todo move this handling outside the big IF & ditch $makeException
892 $this->_useGroupBy
= TRUE;
893 // Duplicates will be created here but better to sort them out in php land.
894 $this->_select
[$name] = "
896 GROUP_CONCAT(DISTINCT IF(civicrm_group_contact.status = 'Added', civicrm_group_contact.group_id, '')),
897 GROUP_CONCAT(DISTINCT civicrm_group_contact_cache.group_id)
900 $this->_element
[$name] = 1;
901 $this->_tables
['civicrm_group_contact'] = 1;
902 $this->_tables
['civicrm_group_contact_cache'] = 1;
903 $this->_pseudoConstantsSelect
["{$name}"] = array(
904 'pseudoField' => "groups",
908 elseif ($name === 'notes') {
909 //@todo move this handling outside the big IF & ditch $makeException
910 // if note field is subject then return subject else body of the note
911 $noteColumn = 'note';
912 if (isset($noteField) && $noteField == 'note_subject') {
913 $noteColumn = 'subject';
916 $this->_useGroupBy
= TRUE;
917 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
918 $this->_element
[$name] = 1;
919 $this->_tables
['civicrm_note'] = 1;
921 elseif ($name === 'current_employer') {
922 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
923 $this->_element
[$name] = 1;
927 if ($cfID && !empty($field['is_search_range'])) {
928 // this is a custom field with range search enabled, so we better check for two/from values
929 if (!empty($this->_paramLookup
[$name . '_from'])) {
930 if (!array_key_exists($cfID, $this->_cfIDs
)) {
931 $this->_cfIDs
[$cfID] = array();
933 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
934 // search in the cdID array for the same grouping
936 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
937 if ($c[3] == $p[3]) {
938 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
943 $p[2] = array('from' => $p[2]);
944 $this->_cfIDs
[$cfID][] = $p;
948 if (!empty($this->_paramLookup
[$name . '_to'])) {
949 if (!array_key_exists($cfID, $this->_cfIDs
)) {
950 $this->_cfIDs
[$cfID] = array();
952 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
953 // search in the cdID array for the same grouping
955 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
956 if ($c[4] == $p[4]) {
957 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
962 $p[2] = array('to' => $p[2]);
963 $this->_cfIDs
[$cfID][] = $p;
970 // add location as hierarchical elements
971 $this->addHierarchicalElements();
973 // add multiple field like website
974 $this->addMultipleElements();
977 CRM_Core_Component
::alterQuery($this, 'select');
979 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
981 if (!empty($this->_cfIDs
)) {
982 // @todo This function is the select function but instead of running 'select' it
983 // is running the whole query.
984 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
985 $this->_customQuery
->query();
986 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
987 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
988 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
989 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
990 $this->_options
= $this->_customQuery
->_options
;
995 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
997 public function addHierarchicalElements() {
998 if (empty($this->_returnProperties
['location'])) {
1001 if (!is_array($this->_returnProperties
['location'])) {
1005 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1006 $processed = array();
1009 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
1010 $addressCustomFieldIds = array();
1012 foreach ($this->_returnProperties
['location'] as $name => $elements) {
1013 $lCond = self
::getPrimaryCondition($name);
1016 $locationTypeId = array_search($name, $locationTypes);
1017 if ($locationTypeId === FALSE) {
1020 $lCond = "location_type_id = $locationTypeId";
1021 $this->_useDistinct
= TRUE;
1023 //commented for CRM-3256
1024 $this->_useGroupBy
= TRUE;
1027 $name = str_replace(' ', '_', $name);
1029 $tName = "$name-location_type";
1030 $ltName = "`$name-location_type`";
1031 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1032 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
1033 $this->_element
["{$tName}_id"] = 1;
1034 $this->_element
["{$tName}"] = 1;
1036 $locationTypeName = $tName;
1037 $locationTypeJoin = array();
1039 $addAddress = FALSE;
1041 foreach ($elements as $elementFullName => $dontCare) {
1043 $elementName = $elementCmpName = $elementFullName;
1045 if (substr($elementCmpName, 0, 5) == 'phone') {
1046 $elementCmpName = 'phone';
1049 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
1050 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
1051 $addressCustomFieldIds[$cfID][$name] = 1;
1054 //add address table only once
1055 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
1057 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
1059 $tName = "$name-address";
1060 $aName = "`$name-address`";
1061 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1062 $this->_element
["{$tName}_id"] = 1;
1063 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
1064 $this->_tables
[$tName] = $addressJoin;
1065 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1066 $processed[$aName] = 1;
1070 $cond = $elementType = '';
1071 if (strpos($elementName, '-') !== FALSE) {
1072 // this is either phone, email or IM
1073 list($elementName, $elementType) = explode('-', $elementName);
1075 if (($elementName != 'phone') && ($elementName != 'im')) {
1076 $cond = self
::getPrimaryCondition($elementType);
1078 // CRM-13011 : If location type is primary, do not restrict search to the phone
1079 // type id - we want the primary phone, regardless of what type it is.
1080 // Otherwise, restrict to the specified phone type for the given field.
1081 if ((!$cond) && ($elementName == 'phone')) {
1082 $cond = "phone_type_id = '$elementType'";
1084 elseif ((!$cond) && ($elementName == 'im')) {
1085 // IM service provider id, CRM-3140
1086 $cond = "provider_id = '$elementType'";
1088 $elementType = '-' . $elementType;
1091 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
1093 // hack for profile, add location id
1096 // fix for CRM-882( to handle phone types )
1097 !is_numeric($elementType)
1099 if (is_numeric($name)) {
1100 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1103 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1106 elseif (is_numeric($name)) {
1107 //this for phone type to work
1108 if (in_array($elementName, array('phone', 'phone_ext'))) {
1109 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1112 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1116 //this is for phone type to work for profile edit
1117 if (in_array($elementName, array('phone', 'phone_ext'))) {
1118 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1121 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1126 // Check if there is a value, if so also add to where Clause
1128 if ($this->_params
) {
1130 if (isset($locationTypeId)) {
1131 $nm .= "-$locationTypeId";
1133 if (!is_numeric($elementType)) {
1134 $nm .= "$elementType";
1137 foreach ($this->_params
as $id => $values) {
1138 if ((is_array($values) && $values[0] == $nm) ||
1139 (in_array($elementName, array('phone', 'im'))
1140 && (strpos($values[0], $nm) !== FALSE)
1150 if ($field && isset($field['where'])) {
1151 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1152 $pf = substr($tableName, 8);
1153 $tName = $name . '-' . $pf . $elementType;
1154 if (isset($tableName)) {
1155 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1156 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1159 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1162 $this->_element
["{$tName}_id"] = 1;
1163 if (substr($tName, -15) == '-state_province') {
1164 // FIXME: hack to fix CRM-1900
1165 $a = Civi
::settings()->get('address_format');
1167 if (substr_count($a, 'state_province_name') > 0) {
1168 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1169 'pseudoField' => "{$pf}_id",
1170 'idCol' => "{$tName}_id",
1171 'bao' => 'CRM_Core_BAO_Address',
1173 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1176 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1177 'pseudoField' => 'state_province_abbreviation',
1178 'idCol' => "{$tName}_id",
1180 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1184 if (substr($elementFullName, 0, 2) == 'im') {
1185 $provider = "{$name}-{$elementFullName}-provider_id";
1186 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1187 $this->_element
[$provider] = 1;
1189 if ($pf == 'country' ||
$pf == 'county') {
1190 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1191 'pseudoField' => "{$pf}_id",
1192 'idCol' => "{$tName}_id",
1193 'bao' => 'CRM_Core_BAO_Address',
1195 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1198 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1202 if (in_array($pf, array('state_province', 'country', 'county'))) {
1203 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1206 $this->_element
["{$name}-{$elementFullName}"] = 1;
1209 if (empty($processed["`$tName`"])) {
1210 $processed["`$tName`"] = 1;
1211 $newName = $tableName . '_' . $index;
1212 switch ($tableName) {
1213 case 'civicrm_phone':
1214 case 'civicrm_email':
1216 case 'civicrm_openid':
1218 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1219 if ($tableName != 'civicrm_phone') {
1220 $this->_tables
[$tName] .= " AND `$tName`.$lCond";
1222 elseif (is_numeric($name)) {
1223 $this->_select
[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1226 // this special case to add phone type
1228 $phoneTypeCondition = " AND `$tName`.$cond ";
1229 //gross hack to pickup corrupted data also, CRM-7603
1230 if (strpos($cond, 'phone_type_id') !== FALSE) {
1231 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1232 if (!empty($lCond)) {
1233 $phoneTypeCondition .= " AND ( `$tName`.$lCond ) ";
1236 $this->_tables
[$tName] .= $phoneTypeCondition;
1239 //build locationType join
1240 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1243 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1247 case 'civicrm_state_province':
1248 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1249 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1250 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1252 $this->_whereTables
["{$name}-address"] = $addressJoin;
1256 case 'civicrm_country':
1257 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1258 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1259 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1261 $this->_whereTables
["{$name}-address"] = $addressJoin;
1265 case 'civicrm_county':
1266 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1267 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1268 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1270 $this->_whereTables
["{$name}-address"] = $addressJoin;
1276 $this->_whereTables
["{$name}-address"] = $addressJoin;
1285 // add location type join
1286 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1287 $this->_tables
[$locationTypeName] = $ltypeJoin;
1289 // table should be present in $this->_whereTables,
1290 // to add its condition in location type join, CRM-3939.
1291 if ($addWhereCount) {
1292 $locClause = array();
1293 foreach ($this->_whereTables
as $tableName => $clause) {
1294 if (!empty($locationTypeJoin[$tableName])) {
1295 $locClause[] = $locationTypeJoin[$tableName];
1299 if (!empty($locClause)) {
1300 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1305 if (!empty($addressCustomFieldIds)) {
1306 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1307 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1308 foreach ($locTypeName as $name => $dnc) {
1309 $this->_locationSpecificCustomFields
[$cfID] = array($name, array_search($name, $locationTypes));
1310 $fieldName = "$name-custom_{$cfID}";
1311 $tName = "$name-address-custom-{$cfID}";
1312 $aName = "`$name-address-custom-{$cfID}`";
1313 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1314 $this->_element
["{$tName}_id"] = 1;
1315 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1316 $this->_element
[$fieldName] = 1;
1317 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1324 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1326 public function addMultipleElements() {
1327 if (empty($this->_returnProperties
['website'])) {
1330 if (!is_array($this->_returnProperties
['website'])) {
1334 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1335 foreach ($elements as $elementFullName => $dontCare) {
1336 $tName = "website-{$key}-{$elementFullName}";
1337 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1338 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1339 $this->_element
["{$tName}_id"] = 1;
1340 $this->_element
["{$tName}"] = 1;
1342 $type = "website-{$key}-website_type_id";
1343 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1344 $this->_element
[$type] = 1;
1345 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1351 * Generate the query based on what type of query we need.
1353 * @param bool $count
1354 * @param bool $sortByChar
1355 * @param bool $groupContacts
1356 * @param bool $onlyDeleted
1359 * sql query parts as an array
1361 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1362 // build permission clause
1363 $this->generatePermissionClause($onlyDeleted, $count);
1366 if (isset($this->_rowCountClause
)) {
1367 $select = "SELECT {$this->_rowCountClause}";
1369 elseif (isset($this->_distinctComponentClause
)) {
1370 // we add distinct to get the right count for components
1371 // for the more complex result set, we use GROUP BY the same id
1373 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} ) as rowCount";
1376 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1378 $from = $this->_simpleFromClause
;
1379 if ($this->_useDistinct
) {
1380 $this->_useGroupBy
= TRUE;
1383 elseif ($sortByChar) {
1384 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1385 $from = $this->_simpleFromClause
;
1387 elseif ($groupContacts) {
1388 $select = 'SELECT contact_a.id as id';
1389 if ($this->_useDistinct
) {
1390 $this->_useGroupBy
= TRUE;
1392 $from = $this->_simpleFromClause
;
1395 if (!empty($this->_paramLookup
['group'])) {
1397 list($name, $op, $value, $grouping, $wildcard) = $this->_paramLookup
['group'][0];
1399 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
1400 $this->_paramLookup
['group'][0][1] = key($value);
1403 // Presumably the lines below come into manage groups screen.
1404 // make sure there is only one element
1405 // this is used when we are running under smog and need to know
1406 // how the contact was added (CRM-1203)
1407 $groups = (array) CRM_Utils_Array
::value($this->_paramLookup
['group'][0][1], $this->_paramLookup
['group'][0][2], $this->_paramLookup
['group'][0][2]);
1408 if ((count($this->_paramLookup
['group']) == 1) &&
1409 (count($groups) == 1)
1411 $groupId = $groups[0];
1413 //check if group is saved search
1414 $group = new CRM_Contact_BAO_Group();
1415 $group->id
= $groupId;
1418 if (!isset($group->saved_search_id
)) {
1419 $tbName = "`civicrm_group_contact-{$groupId}`";
1420 // CRM-17254 don't retrieve extra fields if contact_id is specifically requested
1421 // as this will add load to an intentionally light query.
1422 // ideally this code would be removed as it appears to be to support CRM-1203
1423 // and passing in the required returnProperties from the url would
1424 // make more sense that globally applying the requirements of one form.
1425 if (($this->_returnProperties
!= array('contact_id'))) {
1426 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1427 $this->_element
['group_contact_id'] = 1;
1428 $this->_select
['status'] = "$tbName.status as status";
1429 $this->_element
['status'] = 1;
1433 $this->_useGroupBy
= TRUE;
1435 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1436 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1438 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1439 $this->_useDistinct
= FALSE;
1440 $this->_useGroupBy
= TRUE;
1444 $select = "SELECT ";
1445 if (isset($this->_distinctComponentClause
)) {
1446 $select .= "{$this->_distinctComponentClause}, ";
1448 $select .= implode(', ', $this->_select
);
1449 $from = $this->_fromClause
;
1453 if (!empty($this->_whereClause
)) {
1454 $where = "WHERE {$this->_whereClause}";
1457 if (!empty($this->_permissionWhereClause
) && empty($this->_displayRelationshipType
)) {
1458 if (empty($where)) {
1459 $where = "WHERE $this->_permissionWhereClause";
1462 $where = "$where AND $this->_permissionWhereClause";
1467 if (!empty($this->_having
)) {
1468 foreach ($this->_having
as $havingSets) {
1469 foreach ($havingSets as $havingSet) {
1470 $havingValue[] = $havingSet;
1473 $having = ' HAVING ' . implode(' AND ', $havingValue);
1476 // if we are doing a transform, do it here
1477 // use the $from, $where and $having to get the contact ID
1478 if ($this->_displayRelationshipType
) {
1479 $this->filterRelatedContacts($from, $where, $having);
1482 return array($select, $from, $where, $having);
1486 * Get where values from the parameters.
1488 * @param string $name
1489 * @param mixed $grouping
1493 public function getWhereValues($name, $grouping) {
1495 foreach ($this->_params
as $values) {
1496 if ($values[0] == $name && $values[3] == $grouping) {
1507 * @param bool $relative
1508 * @param string $from
1511 public static function fixDateValues($relative, &$from, &$to) {
1513 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1518 * Convert values from form-appropriate to query-object appropriate.
1520 * The query object is increasingly supporting the sql-filter syntax which is the most flexible syntax.
1521 * So, ideally we would convert all fields to look like
1524 * // Set the operator for legacy reasons, but it is ignored
1526 * // array in sql filter syntax
1527 * 2 => array('BETWEEN' => array(1,60),
1532 * There are some examples of the syntax in
1533 * https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples/Relationship
1535 * More notes at CRM_Core_DAO::createSQLFilter
1537 * and a list of supported operators in CRM_Core_DAO
1539 * @param array $formValues
1540 * @param int $wildcard
1541 * @param bool $useEquals
1543 * @param string $apiEntity
1545 * @param array $entityReferenceFields
1546 * Field names of any entity reference fields (which will need reformatting to IN syntax).
1550 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL,
1551 $entityReferenceFields = array()) {
1553 if (empty($formValues)) {
1557 self
::filterCountryFromValuesIfStateExists($formValues);
1559 foreach ($formValues as $id => &$val) {
1560 // CRM-19374 - we don't want to change $val in $formValues.
1561 // Assign it to a temp variable which operates while iteration.
1564 if (self
::isAlreadyProcessedForQueryFormat($values)) {
1565 $params[] = $values;
1569 self
::legacyConvertFormValues($id, $values);
1571 // The form uses 1 field to represent two db fields
1572 if ($id == 'contact_type' && $values && (!is_array($values) ||
!array_intersect(array_keys($values), CRM_Core_DAO
::acceptedSQLOperators()))) {
1573 $contactType = array();
1575 foreach ((array) $values as $key => $type) {
1576 $types = explode('__', is_numeric($type) ?
$key : $type);
1577 $contactType[$types[0]] = $types[0];
1578 // Add sub-type if specified
1579 if (!empty($types[1])) {
1580 $subType[$types[1]] = $types[1];
1583 $params[] = array('contact_type', 'IN', $contactType, 0, 0);
1585 $params[] = array('contact_sub_type', 'IN', $subType, 0, 0);
1588 elseif ($id == 'privacy') {
1589 if (is_array($formValues['privacy'])) {
1590 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1591 foreach ($formValues['privacy'] as $key => $value) {
1593 $params[] = array($key, $op, $value, 0, 0);
1598 elseif ($id == 'email_on_hold') {
1599 if ($formValues['email_on_hold']['on_hold']) {
1600 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1603 elseif (substr($id, 0, 7) == 'custom_'
1605 substr($id, -9, 9) == '_relative'
1606 ||
substr($id, -5, 5) == '_from'
1607 ||
substr($id, -3, 3) == '_to'
1610 self
::convertCustomRelativeFields($formValues, $params, $values, $id);
1612 elseif (preg_match('/_date_relative$/', $id) ||
1613 $id == 'event_relative' ||
1614 $id == 'case_from_relative' ||
1615 $id == 'case_to_relative' ||
1616 $id == 'participant_relative'
1618 if ($id == 'event_relative') {
1619 $fromRange = 'event_start_date_low';
1620 $toRange = 'event_end_date_high';
1622 elseif ($id == 'participant_relative') {
1623 $fromRange = 'participant_register_date_low';
1624 $toRange = 'participant_register_date_high';
1626 elseif ($id == 'case_from_relative') {
1627 $fromRange = 'case_from_start_date_low';
1628 $toRange = 'case_from_start_date_high';
1630 elseif ($id == 'case_to_relative') {
1631 $fromRange = 'case_to_end_date_low';
1632 $toRange = 'case_to_end_date_high';
1635 $dateComponent = explode('_date_relative', $id);
1636 $fromRange = "{$dateComponent[0]}_date_low";
1637 $toRange = "{$dateComponent[0]}_date_high";
1640 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1641 // relative dates are not processed correctly as lower date value were ignored,
1642 // to ensure both high and low date value got added IF there is relative date,
1643 // we need to reset $formValues by unset and then adding again via CRM_Contact_BAO_Query::fixDateValues(...)
1644 if (!empty($formValues[$id])) {
1645 unset($formValues[$fromRange]);
1646 unset($formValues[$toRange]);
1648 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1652 elseif (in_array($id, $entityReferenceFields) && !empty($values) && is_string($values) && (strpos($values, ',') !=
1654 $params[] = array($id, 'IN', explode(',', $values), 0, 0);
1657 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
1662 $params[] = $values;
1669 * Function to support legacy format for groups and tags.
1672 * @param array|int $values
1675 public static function legacyConvertFormValues($id, &$values) {
1676 $legacyElements = array(
1681 'membership_type_id',
1682 'membership_status_id',
1684 if (in_array($id, $legacyElements) && is_array($values)) {
1685 // prior to 4.7, formValues for some attributes (e.g. group, tag) are stored in array(id1 => 1, id2 => 1),
1686 // as per the recent Search fixes $values need to be in standard array(id1, id2) format
1687 $values = CRM_Utils_Array
::convertCheckboxFormatToArray($values);
1692 * Fix values from query from/to something no-one cared enough to document.
1695 * @param array $values
1696 * @param int $wildcard
1697 * @param bool $useEquals
1699 * @param string $apiEntity
1701 * @return array|null
1703 public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1704 // skip a few search variables
1705 static $skipWhere = NULL;
1706 static $likeNames = NULL;
1709 // Change camelCase EntityName to lowercase with underscores
1710 $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity);
1712 // check if $value is in OK (Operator as Key) format as used by Get API
1713 if (CRM_Utils_System
::isNull($values)) {
1725 'display_relationship_type',
1729 if (in_array($id, $skipWhere) ||
1730 substr($id, 0, 4) == '_qf_' ||
1731 substr($id, 0, 7) == 'hidden_'
1737 (substr($id, 0, strlen($apiEntity)) != $apiEntity) &&
1738 (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_') &&
1739 (substr($id, 0, 7) != 'custom_')
1741 $id = $apiEntity . '_' . $id;
1745 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1748 // email comes in via advanced search
1749 // so use wildcard always
1750 if ($id == 'email') {
1754 if (!$useEquals && in_array($id, $likeNames)) {
1755 $result = array($id, 'LIKE', $values, 0, 1);
1757 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1758 $result = array($id, 'LIKE', $values, 0, 0);
1760 elseif ($id == 'contact_type' ||
1761 (!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO
::acceptedSQLOperators(), TRUE))
1763 $result = array($id, 'IN', $values, 0, $wildcard);
1766 $result = array($id, '=', $values, 0, $wildcard);
1773 * Get the where clause for a single field.
1775 * @param array $values
1776 * @param string $apiEntity
1778 public function whereClauseSingle(&$values, $apiEntity = NULL) {
1779 // do not process custom fields or prefixed contact ids or component params
1780 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1781 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1782 (substr($values[0], 0, 13) == 'contribution_') ||
1783 (substr($values[0], 0, 6) == 'event_') ||
1784 (substr($values[0], 0, 12) == 'participant_') ||
1785 (substr($values[0], 0, 7) == 'member_') ||
1786 (substr($values[0], 0, 6) == 'grant_') ||
1787 (substr($values[0], 0, 7) == 'pledge_') ||
1788 (substr($values[0], 0, 5) == 'case_') ||
1789 (substr($values[0], 0, 10) == 'financial_') ||
1790 (substr($values[0], 0, 8) == 'payment_') ||
1791 (substr($values[0], 0, 11) == 'membership_')
1796 // skip for hook injected fields / params
1797 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1798 if (array_key_exists($values[0], $extFields)) {
1802 switch ($values[0]) {
1803 case 'deleted_contacts':
1804 $this->deletedContacts($values);
1807 case 'contact_sub_type':
1808 $this->contactSubType($values);
1813 $this->group($values);
1816 // case tag comes from find contacts
1818 $this->tagSearch($values);
1822 case 'contact_tags':
1823 $this->tag($values);
1828 case 'note_subject':
1829 $this->notes($values);
1833 $this->ufUser($values);
1837 case 'display_name':
1838 $this->sortName($values);
1842 case 'postal_greeting':
1843 case 'email_greeting':
1844 $this->greetings($values);
1849 $this->email($values, $apiEntity);
1852 case 'phone_numeric':
1853 $this->phone_numeric($values);
1856 case 'phone_phone_type_id':
1857 case 'phone_location_type_id':
1858 $this->phone_option_group($values);
1861 case 'street_address':
1862 $this->street_address($values);
1865 case 'street_number':
1866 $this->street_number($values);
1869 case 'sortByCharacter':
1870 $this->sortByCharacter($values);
1873 case 'location_type':
1874 $this->locationType($values);
1878 $this->county($values);
1881 case 'state_province':
1882 case 'state_province_id':
1883 case 'state_province_name':
1884 $this->stateProvince($values);
1889 $this->country($values, FALSE);
1893 case 'postal_code_low':
1894 case 'postal_code_high':
1895 $this->postalCode($values);
1898 case 'activity_date':
1899 case 'activity_date_low':
1900 case 'activity_date_high':
1901 case 'activity_role':
1902 case 'activity_status_id':
1903 case 'activity_status':
1904 case 'activity_priority':
1905 case 'activity_priority_id':
1906 case 'followup_parent_id':
1908 case 'source_contact_id':
1909 case 'activity_text':
1910 case 'activity_option':
1911 case 'test_activities':
1912 case 'activity_type_id':
1913 case 'activity_type':
1914 case 'activity_survey_id':
1915 case 'activity_tags':
1916 case 'activity_taglist':
1917 case 'activity_test':
1918 case 'activity_campaign_id':
1919 case 'activity_engagement_level':
1921 case 'activity_result':
1922 case 'source_contact':
1923 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1928 case 'birth_date_low':
1929 case 'birth_date_high':
1930 case 'deceased_date_low':
1931 case 'deceased_date_high':
1932 $this->demographics($values);
1935 case 'age_asof_date':
1936 // handled by demographics
1939 case 'log_date_low':
1940 case 'log_date_high':
1941 $this->modifiedDates($values);
1945 $this->changeLog($values);
1948 case 'do_not_phone':
1949 case 'do_not_email':
1952 case 'do_not_trade':
1954 $this->privacy($values);
1957 case 'privacy_options':
1958 $this->privacyOptions($values);
1961 case 'privacy_operator':
1962 case 'privacy_toggle':
1963 // these are handled by privacy options
1966 case 'preferred_communication_method':
1967 $this->preferredCommunication($values);
1970 case 'relation_type_id':
1971 case 'relation_start_date_high':
1972 case 'relation_start_date_low':
1973 case 'relation_end_date_high':
1974 case 'relation_end_date_low':
1975 case 'relation_target_name':
1976 case 'relation_status':
1977 case 'relation_date_low':
1978 case 'relation_date_high':
1979 $this->relationship($values);
1980 $this->_relationshipValuesAdded
= TRUE;
1983 case 'task_status_id':
1984 $this->task($values);
1988 // since this case is handled with the above
1991 case 'prox_distance':
1992 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1995 case 'prox_street_address':
1997 case 'prox_postal_code':
1998 case 'prox_state_province_id':
1999 case 'prox_country_id':
2000 // handled by the proximity_distance clause
2004 $this->restWhere($values);
2010 * Given a list of conditions in params generate the required where clause.
2012 * @param string $apiEntity
2016 public function whereClause($apiEntity = NULL) {
2017 $this->_where
[0] = array();
2018 $this->_qill
[0] = array();
2020 $this->includeContactIds();
2021 if (!empty($this->_params
)) {
2022 foreach (array_keys($this->_params
) as $id) {
2023 if (empty($this->_params
[$id][0])) {
2026 // check for both id and contact_id
2027 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
2028 $this->_where
[0][] = self
::buildClause("contact_a.id", $this->_params
[$id][1], $this->_params
[$id][2]);
2031 $this->whereClauseSingle($this->_params
[$id], $apiEntity);
2035 CRM_Core_Component
::alterQuery($this, 'where');
2037 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
2040 if ($this->_customQuery
) {
2041 // Added following if condition to avoid the wrong value display for 'my account' / any UF info.
2042 // Hope it wont affect the other part of civicrm.. if it does please remove it.
2043 if (!empty($this->_customQuery
->_where
)) {
2044 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
2047 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
2051 $andClauses = array();
2054 if (!empty($this->_where
)) {
2055 foreach ($this->_where
as $grouping => $values) {
2056 if ($grouping > 0 && !empty($values)) {
2057 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
2062 if (!empty($this->_where
[0])) {
2063 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
2065 if (!empty($clauses)) {
2066 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
2069 if ($validClauses > 1) {
2070 $this->_useDistinct
= TRUE;
2074 return implode(' AND ', $andClauses);
2078 * Generate where clause for any parameters not already handled.
2080 * @param array $values
2084 public function restWhere(&$values) {
2085 $name = CRM_Utils_Array
::value(0, $values);
2086 $op = CRM_Utils_Array
::value(1, $values);
2087 $value = CRM_Utils_Array
::value(2, $values);
2088 $grouping = CRM_Utils_Array
::value(3, $values);
2089 $wildcard = CRM_Utils_Array
::value(4, $values);
2091 if (isset($grouping) && empty($this->_where
[$grouping])) {
2092 $this->_where
[$grouping] = array();
2095 $multipleFields = array('url');
2097 //check if the location type exists for fields
2099 $locType = explode('-', $name);
2101 if (!in_array($locType[0], $multipleFields)) {
2102 //add phone type if exists
2103 if (isset($locType[2]) && $locType[2]) {
2104 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
2108 $field = CRM_Utils_Array
::value($name, $this->_fields
);
2111 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
2120 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2121 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2122 if (isset($locType[1]) && is_numeric($locType[1])) {
2123 $lType = $locationType[$locType[1]];
2126 $field['title'] .= " ($lType)";
2129 if (substr($name, 0, 14) === 'state_province') {
2130 if (isset($locType[1]) && is_numeric($locType[1])) {
2132 $aName = "{$lType}-address";
2133 $where = "`$aName`.state_province_id";
2136 $where = "civicrm_address.state_province_id";
2139 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value);
2140 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
2141 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
2143 elseif (!empty($field['pseudoconstant'])) {
2144 $this->optionValueQuery(
2145 $name, $op, $value, $grouping,
2146 'CRM_Contact_DAO_Contact',
2152 if ($name == 'gender_id') {
2153 self
::$_openedPanes[ts('Demographics')] = TRUE;
2156 elseif (substr($name, 0, 7) === 'country' ||
substr($name, 0, 6) === 'county') {
2157 $name = (substr($name, 0, 7) === 'country') ?
"country_id" : "county_id";
2158 if (isset($locType[1]) && is_numeric($locType[1])) {
2160 $aName = "{$lType}-address";
2161 $where = "`$aName`.$name";
2164 $where = "civicrm_address.$name";
2167 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2169 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
2170 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
2172 elseif ($name === 'world_region') {
2173 $this->optionValueQuery(
2174 $name, $op, $value, $grouping,
2182 elseif ($name === 'is_deceased') {
2183 $this->setQillAndWhere($name, $op, $value, $grouping, $field);
2184 self
::$_openedPanes[ts('Demographics')] = TRUE;
2186 elseif ($name === 'created_date' ||
$name === 'modified_date' ||
$name === 'deceased_date' ||
$name === 'birth_date') {
2187 $appendDateTime = TRUE;
2188 if ($name === 'deceased_date' ||
$name === 'birth_date') {
2189 $appendDateTime = FALSE;
2190 self
::$_openedPanes[ts('Demographics')] = TRUE;
2192 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2194 elseif ($name === 'contact_id') {
2195 if (is_int($value)) {
2196 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2197 $this->_qill
[$grouping][] = "$field[title] $op $value";
2200 elseif ($name === 'name') {
2201 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2204 $value = self
::getWildCardedValue($wildcard, $op, $value);
2206 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
2207 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2208 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2209 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2211 elseif ($name === 'current_employer') {
2214 $value = self
::getWildCardedValue($wildcard, $op, $value);
2216 $ceWhereClause = self
::buildClause("contact_a.organization_name", $op,
2219 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2220 $this->_where
[$grouping][] = $ceWhereClause;
2221 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2223 elseif ($name === 'email_greeting') {
2224 $filterCondition = array('greeting_type' => 'email_greeting');
2225 $this->optionValueQuery(
2226 $name, $op, $value, $grouping,
2227 CRM_Core_PseudoConstant
::greeting($filterCondition),
2229 ts('Email Greeting')
2232 elseif ($name === 'postal_greeting') {
2233 $filterCondition = array('greeting_type' => 'postal_greeting');
2234 $this->optionValueQuery(
2235 $name, $op, $value, $grouping,
2236 CRM_Core_PseudoConstant
::greeting($filterCondition),
2238 ts('Postal Greeting')
2241 elseif ($name === 'addressee') {
2242 $filterCondition = array('greeting_type' => 'addressee');
2243 $this->optionValueQuery(
2244 $name, $op, $value, $grouping,
2245 CRM_Core_PseudoConstant
::greeting($filterCondition),
2250 elseif (substr($name, 0, 4) === 'url-') {
2251 $tName = 'civicrm_website';
2252 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2253 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2256 $value = self
::getWildCardedValue($wildcard, $op, $value);
2259 $this->_where
[$grouping][] = $d = self
::buildClause('civicrm_website.url', $op, $value);
2260 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2262 elseif ($name === 'contact_is_deleted') {
2263 $this->setQillAndWhere('is_deleted', $op, $value, $grouping, $field);
2265 elseif (!empty($field['where'])) {
2267 if (!empty($field['type'])) {
2268 $type = CRM_Utils_Type
::typeToString($field['type']);
2271 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2273 if (isset($locType[1]) &&
2274 is_numeric($locType[1])
2278 //get the location name
2279 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2280 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
2281 $fieldName = "LOWER(`$tName`.$fldName)";
2283 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2284 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2288 if ($tableName == 'civicrm_contact') {
2289 $fieldName = "contact_a.{$fieldName}";
2292 if ($op != 'IN' && !is_numeric($value) && !is_array($value)) {
2293 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
2294 $fieldName = "LOWER({$field['where']})";
2297 $fieldName = "{$field['where']}";
2302 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2303 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(
2304 1 => $field['title'],
2306 3 => (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) ?
$qillVal : "'$qillVal'"));
2308 if (is_array($value)) {
2309 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2310 // for api style operators for functions that hit this point without worrying about regression
2311 // (the previous comments indicated the condition for hitting this point were unknown
2312 // per CRM-14743 we are adding modified_date & created_date operator support
2313 $operations = array_keys($value);
2314 foreach ($operations as $operator) {
2315 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2316 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2317 //so this condition will satisfy the search for now
2318 if (strpos($op, 'IN') !== FALSE) {
2319 $value = array($op => $value);
2321 // we don't know when this might happen
2323 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $operator)));
2327 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($fieldName, $value, $type);
2330 if (!strpos($op, 'IN')) {
2331 $value = $strtolower($value);
2335 $value = self
::getWildCardedValue($wildcard, $op, $value);
2338 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2342 if ($setTables && isset($field['where'])) {
2343 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2344 if (isset($tableName)) {
2345 $this->_tables
[$tableName] = 1;
2346 $this->_whereTables
[$tableName] = 1;
2358 public static function getLocationTableName(&$where, &$locType) {
2359 if (isset($locType[1]) && is_numeric($locType[1])) {
2360 list($tbName, $fldName) = explode(".", $where);
2362 //get the location name
2363 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2364 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2365 if (in_array($locType[0], $specialFields)) {
2366 //hack to fix / special handing for phone_ext
2367 if ($locType[0] == 'phone_ext') {
2368 $locType[0] = 'phone';
2370 if (isset($locType[2]) && $locType[2]) {
2371 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2374 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2377 elseif (in_array($locType[0],
2382 'street_number_suffix',
2384 'supplemental_address_1',
2385 'supplemental_address_2',
2386 'supplemental_address_3',
2389 'postal_code_suffix',
2395 //fix for search by profile with address fields.
2396 $tName = "{$locationType[$locType[1]]}-address";
2398 elseif (in_array($locType[0],
2406 $tName = "{$locationType[$locType[1]]}-email";
2408 elseif ($locType[0] == 'provider_id') {
2409 $tName = "{$locationType[$locType[1]]}-im";
2411 elseif ($locType[0] == 'openid') {
2412 $tName = "{$locationType[$locType[1]]}-openid";
2415 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2417 $tName = str_replace(' ', '_', $tName);
2418 return array($tName, $fldName);
2420 CRM_Core_Error
::fatal();
2424 * Given a result dao, extract the values and return that array
2426 * @param CRM_Core_DAO $dao
2429 * values for this query
2431 public function store($dao) {
2434 foreach ($this->_element
as $key => $dontCare) {
2435 if (property_exists($dao, $key)) {
2436 if (strpos($key, '-') !== FALSE) {
2437 $values = explode('-', $key);
2438 $lastElement = array_pop($values);
2440 $cnt = count($values);
2442 foreach ($values as $v) {
2443 if (!array_key_exists($v, $current)) {
2444 $current[$v] = array();
2446 //bad hack for im_provider
2447 if ($lastElement == 'provider_id') {
2448 if ($count < $cnt) {
2449 $current = &$current[$v];
2452 $lastElement = "{$v}_{$lastElement}";
2456 $current = &$current[$v];
2461 $current[$lastElement] = $dao->$key;
2464 $value[$key] = $dao->$key;
2472 * Getter for tables array.
2476 public function tables() {
2477 return $this->_tables
;
2481 * Sometimes used to create the from clause, but, not reliably, set
2482 * this AND set tables.
2484 * It's unclear the intent - there is a 'simpleFrom' clause which
2485 * takes whereTables into account & a fromClause which doesn't.
2487 * logic may have eroded?
2491 public function whereTables() {
2492 return $this->_whereTables
;
2496 * Generate the where clause (used in match contacts and permissions)
2498 * @param array $params
2499 * @param array $fields
2500 * @param array $tables
2501 * @param $whereTables
2502 * @param bool $strict
2506 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2507 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2511 $tables = array_merge($query->tables(), $tables);
2512 $whereTables = array_merge($query->whereTables(), $whereTables);
2514 return $query->_whereClause
;
2518 * Create the from clause.
2520 * @param array $tables
2521 * Tables that need to be included in this from clause. If null,
2522 * return mimimal from clause (i.e. civicrm_contact).
2523 * @param array $inner
2524 * Tables that should be inner-joined.
2525 * @param array $right
2526 * Tables that should be right-joined.
2527 * @param bool $primaryLocation
2528 * Search on primary location. See note below.
2530 * Determines search mode based on bitwise MODE_* constants.
2531 * @param string|NULL $apiEntity
2532 * Determines search mode based on entity by string.
2534 * The $primaryLocation flag only seems to be used when
2535 * locationType() has been called. This may be a search option
2536 * exposed, or perhaps it's a "search all details" approach which
2537 * predates decoupling of location types and primary fields?
2539 * @see https://issues.civicrm.org/jira/browse/CRM-19967
2544 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1, $apiEntity = NULL) {
2546 $from = ' FROM civicrm_contact contact_a';
2547 if (empty($tables)) {
2551 if (!empty($tables['civicrm_worldregion'])) {
2552 $tables = array_merge(array('civicrm_country' => 1), $tables);
2555 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2556 CRM_Utils_Array
::value('civicrm_county', $tables)
2557 ) && empty($tables['civicrm_address'])
2559 $tables = array_merge(array('civicrm_address' => 1),
2564 // add group_contact and group table is subscription history is present
2565 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2566 $tables = array_merge(array(
2567 'civicrm_group' => 1,
2568 'civicrm_group_contact' => 1,
2574 // to handle table dependencies of components
2575 CRM_Core_Component
::tableNames($tables);
2576 // to handle table dependencies of hook injected tables
2577 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2579 //format the table list according to the weight
2580 $info = CRM_Core_TableHierarchy
::info();
2582 foreach ($tables as $key => $value) {
2584 if (strpos($key, '-') !== FALSE) {
2585 $keyArray = explode('-', $key);
2586 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2588 elseif (strpos($key, '_') !== FALSE) {
2589 $keyArray = explode('_', $key);
2590 if (is_numeric(array_pop($keyArray))) {
2591 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2594 $k = CRM_Utils_Array
::value($key, $info, 99);
2598 $k = CRM_Utils_Array
::value($key, $info, 99);
2600 $tempTable[$k . ".$key"] = $key;
2603 $newTables = array();
2604 foreach ($tempTable as $key) {
2605 $newTables[$key] = $tables[$key];
2608 $tables = $newTables;
2610 foreach ($tables as $name => $value) {
2615 if (!empty($inner[$name])) {
2618 elseif (!empty($right[$name])) {
2626 // if there is already a join statement in value, use value itself
2627 if (strpos($value, 'JOIN')) {
2628 $from .= " $value ";
2631 $from .= " $side JOIN $name ON ( $value ) ";
2635 $searchPrimary = '';
2636 if (Civi
::settings()->get('searchPrimaryDetailsOnly') ||
$apiEntity) {
2637 $searchPrimary = "AND {$name}.is_primary = 1";
2640 case 'civicrm_address':
2641 //CRM-14263 further handling of address joins further down...
2642 if (!$primaryLocation) {
2643 $searchPrimary = '';
2645 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id {$searchPrimary} )";
2648 case 'civicrm_phone':
2649 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id {$searchPrimary}) ";
2652 case 'civicrm_email':
2653 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id {$searchPrimary})";
2657 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id {$searchPrimary}) ";
2661 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2662 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2663 $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)";
2666 case 'civicrm_openid':
2667 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id {$searchPrimary} )";
2670 case 'civicrm_worldregion':
2671 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2672 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2675 case 'civicrm_location_type':
2676 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2679 case 'civicrm_group':
2680 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2683 case 'civicrm_group_contact':
2684 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2687 case 'civicrm_group_contact_cache':
2688 $from .= " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
2691 case 'civicrm_activity':
2692 case 'civicrm_activity_tag':
2693 case 'activity_type':
2694 case 'activity_status':
2696 case 'civicrm_activity_contact':
2697 case 'source_contact':
2698 case 'activity_priority':
2699 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2702 case 'civicrm_entity_tag':
2703 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2704 civicrm_entity_tag.entity_id = contact_a.id ) ";
2707 case 'civicrm_note':
2708 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2709 contact_a.id = civicrm_note.entity_id ) ";
2712 case 'civicrm_subscription_history':
2713 $from .= " $side JOIN civicrm_subscription_history
2714 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2715 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2718 case 'civicrm_relationship':
2719 if (self
::$_relType == 'reciprocal') {
2720 if (self
::$_relationshipTempTable) {
2721 // we have a temptable to join on
2722 $tbl = self
::$_relationshipTempTable;
2723 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2726 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2727 $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)";
2730 elseif (self
::$_relType == 'b') {
2731 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2732 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2735 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2736 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2741 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2742 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2746 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2749 case 'civicrm_grant':
2750 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2753 case 'civicrm_website':
2754 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2758 $locationTypeName = '';
2759 if (strpos($name, '-address') != 0) {
2760 $locationTypeName = 'address';
2762 elseif (strpos($name, '-phone') != 0) {
2763 $locationTypeName = 'phone';
2765 elseif (strpos($name, '-email') != 0) {
2766 $locationTypeName = 'email';
2768 elseif (strpos($name, '-im') != 0) {
2769 $locationTypeName = 'im';
2771 elseif (strpos($name, '-openid') != 0) {
2772 $locationTypeName = 'openid';
2775 if ($locationTypeName) {
2776 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2777 $parts = explode('-', $name);
2778 $locationID = array_search($parts[0], CRM_Core_BAO_Address
::buildOptions('location_type_id', 'get', array('name' => $parts[0])));
2779 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2782 $from .= CRM_Core_Component
::from($name, $mode, $side);
2784 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2793 * WHERE / QILL clause for deleted_contacts
2795 * @param array $values
2797 public function deletedContacts($values) {
2798 list($_, $_, $value, $grouping, $_) = $values;
2800 // *prepend* to the relevant grouping as this is quite an important factor
2801 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2806 * Where / qill clause for contact_type
2810 public function contactType(&$values) {
2811 list($name, $op, $value, $grouping, $wildcard) = $values;
2813 $subTypes = array();
2816 // account for search builder mapping multiple values
2817 if (!is_array($value)) {
2818 $values = self
::parseSearchBuilderString($value, 'String');
2819 if (is_array($values)) {
2820 $value = array_flip($values);
2824 if (is_array($value)) {
2825 foreach ($value as $k => $v) {
2830 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2831 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2834 if (!empty($subType)) {
2835 $subTypes[$subType] = 1;
2837 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2842 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2843 $contactType = $contactTypeANDSubType[0];
2844 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2845 if (!empty($subType)) {
2846 $subTypes[$subType] = 1;
2848 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2852 if (!empty($clause)) {
2854 if ($op == 'IN' ||
$op == 'NOT IN') {
2855 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2858 $type = array_pop($clause);
2859 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2862 $this->_qill
[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2864 if (!empty($subTypes)) {
2865 $this->includeContactSubTypes($subTypes, $grouping);
2871 * Where / qill clause for contact_sub_type.
2873 * @param array $values
2875 public function contactSubType(&$values) {
2876 list($name, $op, $value, $grouping, $wildcard) = $values;
2877 $this->includeContactSubTypes($value, $grouping, $op);
2885 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2887 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2889 $value = $value[$op];
2893 $alias = "contact_a.contact_sub_type";
2894 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
2896 $op = str_replace('IN', 'LIKE', $op);
2897 $op = str_replace('=', 'LIKE', $op);
2898 $op = str_replace('!', 'NOT ', $op);
2900 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2901 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
2903 elseif (is_array($value)) {
2904 foreach ($value as $k => $v) {
2905 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($v, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2909 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2912 if (!empty($clause)) {
2913 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2915 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', array(1 => $qillOperators[$op])) . implode(' ' . ts('or') . ' ', array_keys($clause));
2919 * Where / qill clause for groups.
2923 public function group($values) {
2924 list($name, $op, $value, $grouping, $wildcard) = $values;
2926 // If the $value is in OK (operator as key) array format we need to extract the key as operator and value first
2927 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2929 $value = $value[$op];
2932 // Replace pseudo operators from search builder
2933 $op = str_replace('EMPTY', 'NULL', $op);
2935 if (strpos($op, 'NULL')) {
2939 if (count($value) > 1) {
2940 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
2941 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $op)));
2943 $this->_useDistinct
= TRUE;
2946 if (isset($value)) {
2947 $value = CRM_Utils_Array
::value($op, $value, $value);
2950 if ($name == 'group_type') {
2951 $value = array_keys($this->getGroupsFromTypeCriteria($value));
2954 $regularGroupIDs = $smartGroupIDs = array();
2955 foreach ((array) $value as $id) {
2956 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
2957 $smartGroupIDs[] = $id;
2960 $regularGroupIDs[] = $id;
2964 $isNotOp = ($op == 'NOT IN' ||
$op == '!=');
2967 $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
2969 is_array($gcsValues[2])
2971 foreach ($gcsValues[2] as $k => $v) {
2973 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2978 $statii[] = "'Added'";
2980 $groupClause = array();
2981 if (count($regularGroupIDs) ||
empty($value)) {
2982 $groupIds = implode(',', (array) $regularGroupIDs);
2983 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2984 $joinClause = array("contact_a.id = {$gcTable}.contact_id");
2986 $joinClause[] = "{$gcTable}.status IN (" . implode(', ', $statii) . ")";
2988 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
2989 if (strpos($op, 'IN') !== FALSE) {
2990 $clause = "{$gcTable}.group_id $op ( $groupIds ) %s ";
2992 elseif ($op == '!=') {
2993 $clause = "{$gcTable}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact cgc WHERE cgc.group_id = $groupIds %s)";
2996 $clause = "{$gcTable}.group_id $op $groupIds %s ";
2999 // include child groups IDs if any
3000 $childGroupIds = CRM_Contact_BAO_Group
::getChildGroupIds($regularGroupIDs);
3002 if (count($childGroupIds)) {
3003 $gcTable = ($op == '!=') ?
'cgc' : $gcTable;
3004 $childClause = " OR {$gcTable}.group_id IN (" . implode(',', $childGroupIds) . ") ";
3006 $groupClause[] = '(' . sprintf($clause, $childClause) . ')';
3009 //CRM-19589: contact(s) removed from a Smart Group, resides in civicrm_group_contact table
3010 if (count($smartGroupIDs)) {
3011 $groupClause[] = " ( " . $this->addGroupContactCache($smartGroupIDs, NULL, "contact_a", $op) . " ) ";
3014 $and = ($op == 'IS NULL') ?
' AND ' : ' OR ';
3015 $this->_where
[$grouping][] = ' ( ' . implode($and, $groupClause) . ' ) ';
3017 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
3018 $this->_qill
[$grouping][] = ts("Group(s) %1 %2", array(1 => $qillop, 2 => $qillVal));
3019 if (strpos($op, 'NULL') === FALSE) {
3020 $this->_qill
[$grouping][] = ts("Group Status %1", array(1 => implode(' ' . ts('or') . ' ', $statii)));
3025 * Function translates selection of group type into a list of groups.
3030 public function getGroupsFromTypeCriteria($value) {
3031 $groupIds = array();
3032 foreach ((array) $value as $groupTypeValue) {
3033 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
3034 $groupIds = ($groupIds +
$groupList);
3040 * @param array $groups
3041 * @param string $tableAlias
3042 * @param string $joinTable
3045 * @return null|string
3047 public function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a", $op) {
3048 $isNullOp = (strpos($op, 'NULL') !== FALSE);
3049 $groupsIds = $groups;
3050 if (!$isNullOp && !$groups) {
3053 elseif (strpos($op, 'IN') !== FALSE) {
3054 $groups = array($op => $groups);
3056 elseif (is_array($groups) && count($groups)) {
3057 $groups = array('IN' => $groups);
3060 // Find all the groups that are part of a saved search.
3061 $smartGroupClause = self
::buildClause("id", $op, $groups, 'Int');
3063 SELECT id, cache_date, saved_search_id, children
3065 WHERE $smartGroupClause
3066 AND ( saved_search_id != 0
3067 OR saved_search_id IS NOT NULL
3068 OR children IS NOT NULL )
3071 $group = CRM_Core_DAO
::executeQuery($sql);
3073 while ($group->fetch()) {
3074 $this->_useDistinct
= TRUE;
3075 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
3076 CRM_Contact_BAO_GroupContactCache
::load($group);
3079 if ($group->N
== 0) {
3084 $tableAlias = "`civicrm_group_contact_cache_";
3085 $tableAlias .= ($isNullOp) ?
"a`" : implode(',', (array) $groupsIds) . "`";
3088 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.id = {$tableAlias}.contact_id ";
3089 return self
::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
3093 * Where / qill clause for cms users
3097 public function ufUser(&$values) {
3098 list($name, $op, $value, $grouping, $wildcard) = $values;
3101 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3103 $this->_qill
[$grouping][] = ts('CMS User');
3105 elseif ($value == 0) {
3106 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3108 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3109 $this->_qill
[$grouping][] = ts('Not a CMS User');
3114 * All tag search specific.
3116 * @param array $values
3118 public function tagSearch(&$values) {
3119 list($name, $op, $value, $grouping, $wildcard) = $values;
3122 $value = "%{$value}%";
3124 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3125 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3127 $etTable = "`civicrm_entity_tag-" . $value . "`";
3128 $tTable = "`civicrm_tag-" . $value . "`";
3130 if ($useAllTagTypes[2]) {
3131 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3132 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3133 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3135 // search tag in cases
3136 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3137 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
3138 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3139 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3140 LEFT JOIN civicrm_case
3141 ON (civicrm_case_contact.case_id = civicrm_case.id
3142 AND civicrm_case.is_deleted = 0 )
3143 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3144 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3145 // search tag in activities
3146 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3147 $tActTable = "`civicrm_act_tag-" . $value . "`";
3148 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3149 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3151 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3152 = " LEFT JOIN civicrm_activity_contact
3153 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3154 LEFT JOIN civicrm_activity
3155 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3156 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3157 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3158 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3160 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $value . "' OR {$tCaseTable}.name $op '" . $value . "' OR {$tActTable}.name $op '" . $value . "')";
3161 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
3164 $etTable = "`civicrm_entity_tag-" . $value . "`";
3165 $tTable = "`civicrm_tag-" . $value . "`";
3166 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3167 {$etTable}.entity_table = 'civicrm_contact' )
3168 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3170 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3171 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
3176 * Where / qill clause for tag.
3178 * @param array $values
3180 public function tag(&$values) {
3181 list($name, $op, $value, $grouping, $wildcard) = $values;
3183 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, array('onlyActive' => FALSE));
3184 // API/Search Builder format array(operator => array(values))
3185 if (is_array($value)) {
3186 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3188 $value = $value[$op];
3190 if (count($value) > 1) {
3191 $this->_useDistinct
= TRUE;
3193 $value = implode(',', (array) $value);
3196 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3197 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3199 $etTable = "`civicrm_entity_tag-" . $value . "`";
3201 if ($useAllTagTypes[2]) {
3202 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3203 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3205 // search tag in cases
3206 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3207 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3208 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3210 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3211 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3212 LEFT JOIN civicrm_case
3213 ON (civicrm_case_contact.case_id = civicrm_case.id
3214 AND civicrm_case.is_deleted = 0 )
3215 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3216 // search tag in activities
3217 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3218 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3219 = " LEFT JOIN civicrm_activity_contact
3220 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3221 LEFT JOIN civicrm_activity
3222 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3223 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3224 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3227 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3228 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3231 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3235 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3236 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3239 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3240 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3241 $op = str_replace('EMPTY', 'NULL', $op);
3242 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3244 // CRM-16941: for tag tried with != operator we don't show contact who don't have given $value AND also in other tag
3245 elseif ($op == '!=') {
3246 $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') . ")";
3248 elseif ($op == '=' ||
strstr($op, 'IN')) {
3249 $op = ($op == '=') ?
'IN' : $op;
3250 $this->_where
[$grouping][] = "{$etTable}.tag_id $op ( $value )";
3253 $this->_qill
[$grouping][] = ts('Tagged %1 %2', array(1 => $qillop, 2 => $qillVal));
3257 * Where/qill clause for notes
3259 * @param array $values
3261 public function notes(&$values) {
3262 list($name, $op, $value, $grouping, $wildcard) = $values;
3264 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3265 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3266 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3268 $this->_useDistinct
= TRUE;
3270 $this->_tables
['civicrm_note'] = $this->_whereTables
['civicrm_note']
3271 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3273 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3275 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3277 if (strpos($value, '%') === FALSE) {
3278 $value = "%$value%";
3282 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3288 if ($noteOption %
2 == 0) {
3289 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3290 $label = ts('Note: Body Only');
3292 if ($noteOption %
3 == 0) {
3293 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3294 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3296 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3297 list($qillOp, $qillVal) = self
::buildQillForFieldValue(NULL, $name, $n, $op);
3298 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillOp, 3 => $qillVal));
3302 * @param string $name
3308 public function nameNullOrEmptyOp($name, $op, $grouping) {
3312 $this->_where
[$grouping][] = "contact_a.$name $op";
3313 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3317 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3318 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3321 case 'IS NOT EMPTY':
3322 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3323 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3332 * Where / qill clause for sort_name
3334 * @param array $values
3336 public function sortName(&$values) {
3337 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3339 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3340 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3344 $input = $value = trim($value);
3346 if (!strlen($value)) {
3350 $config = CRM_Core_Config
::singleton();
3354 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3357 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3359 $firstChar = substr($value, 0, 1);
3360 $lastChar = substr($value, -1, 1);
3361 $quotes = array("'", '"');
3362 // If string is quoted, strip quotes and otherwise don't alter it
3363 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3364 $value = trim($value, implode('', $quotes));
3366 // Replace spaces with wildcards for a LIKE operation
3367 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3368 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3369 $value = str_replace(' ', '%', $value);
3371 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($value)));
3372 if (strlen($value)) {
3373 $fieldsub = array();
3374 $value = "'" . self
::getWildCardedValue($wildcard, $op, $value) . "'";
3375 if ($fieldName == 'sort_name') {
3376 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3377 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3380 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3381 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3383 $fieldsub[] = " ( $wc $op $value )";
3384 if ($config->includeNickNameInName
) {
3385 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3386 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3387 $fieldsub[] = " ( $wc $op $value )";
3389 if ($config->includeEmailInName
) {
3390 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3392 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3395 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3397 $this->_where
[$grouping][] = $sub;
3398 if ($config->includeEmailInName
) {
3399 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3400 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3403 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3408 * Where/qill clause for greeting fields.
3410 * @param array $values
3412 public function greetings(&$values) {
3413 list($name, $op, $value, $grouping, $wildcard) = $values;
3414 $name .= '_display';
3416 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
3417 $this->_qill
[$grouping][] = ts('Greeting %1 %2', array(1 => $qillop, 2 => $qillVal));
3418 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value, 'String');
3422 * Where / qill clause for email
3424 * @param array $values
3425 * @param string $apiEntity
3427 protected function email(&$values, $apiEntity) {
3428 list($name, $op, $value, $grouping, $wildcard) = $values;
3429 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3431 // CRM-18147: for Contact's GET API, email fieldname got appended with its entity as in {$apiEntiy}_{$name}
3432 // so following code is use build whereClause for contact's primart email id
3433 if (!empty($apiEntity)) {
3434 $dataType = 'String';
3435 if ($name == 'email_id') {
3436 $dataType = 'Integer';
3440 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.is_primary', '=', 1, 'Integer');
3441 $this->_where
[$grouping][] = self
::buildClause("civicrm_email.$name", $op, $value, $dataType);
3445 $n = strtolower(trim($value));
3447 if (substr($n, 0, 1) == '"' &&
3448 substr($n, -1, 1) == '"'
3450 $n = substr($n, 1, -1);
3451 $value = CRM_Core_DAO
::escapeString($n);
3455 $value = self
::getWildCardedValue($wildcard, $op, $n);
3457 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3458 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3461 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3462 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3467 * Where / qill clause for phone number
3469 * @param array $values
3471 public function phone_numeric(&$values) {
3472 list($name, $op, $value, $grouping, $wildcard) = $values;
3473 // Strip non-numeric characters; allow wildcards
3474 $number = preg_replace('/[^\d%]/', '', $value);
3476 if (strpos($number, '%') === FALSE) {
3477 $number = "%$number%";
3480 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3481 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3482 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3487 * Where / qill clause for phone type/location
3489 * @param array $values
3491 public function phone_option_group($values) {
3492 list($name, $op, $value, $grouping, $wildcard) = $values;
3493 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3494 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3495 $optionName = $options[$value];
3496 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3497 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3498 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3502 * Where / qill clause for street_address.
3504 * @param array $values
3506 public function street_address(&$values) {
3507 list($name, $op, $value, $grouping, $wildcard) = $values;
3516 $value = strtolower($n);
3517 if (strpos($value, '%') === FALSE) {
3518 // only add wild card if not there
3519 $value = "%{$value}%";
3522 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3523 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3524 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3527 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3528 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3531 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3535 * Where / qill clause for street_unit.
3537 * @param array $values
3539 public function street_number(&$values) {
3540 list($name, $op, $value, $grouping, $wildcard) = $values;
3548 if (strtolower($n) == 'odd') {
3549 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3550 $this->_qill
[$grouping][] = ts('Street Number is odd');
3552 elseif (strtolower($n) == 'even') {
3553 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3554 $this->_qill
[$grouping][] = ts('Street Number is even');
3557 $value = strtolower($n);
3559 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3560 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3561 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3564 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3568 * Where / qill clause for sorting by character.
3570 * @param array $values
3572 public function sortByCharacter(&$values) {
3573 list($name, $op, $value, $grouping, $wildcard) = $values;
3575 $name = trim($value);
3576 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3577 $this->_where
[$grouping][] = $cond;
3578 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3582 * Where / qill clause for including contact ids.
3584 public function includeContactIDs() {
3585 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3589 $contactIds = array();
3590 foreach ($this->_params
as $id => $values) {
3591 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3592 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3595 CRM_Utils_Type
::validateAll($contactIds, 'Positive');
3596 if (!empty($contactIds)) {
3597 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3602 * Where / qill clause for postal code.
3604 * @param array $values
3606 public function postalCode(&$values) {
3607 // skip if the fields dont have anything to do with postal_code
3608 if (empty($this->_fields
['postal_code'])) {
3612 list($name, $op, $value, $grouping, $wildcard) = $values;
3614 // Handle numeric postal code range searches properly by casting the column as numeric
3615 if (is_numeric($value)) {
3616 $field = "IF (civicrm_address.postal_code REGEXP '^[0-9]+$', CAST(civicrm_address.postal_code AS UNSIGNED), 0)";
3617 $val = CRM_Utils_Type
::escape($value, 'Integer');
3620 $field = 'civicrm_address.postal_code';
3621 // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string.
3622 if (!is_array($value)) {
3623 $val = CRM_Utils_Type
::escape($value, 'String');
3626 // Do we need to escape values here? I would expect buildClause does.
3631 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3633 if ($name == 'postal_code') {
3634 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3635 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3637 elseif ($name == 'postal_code_low') {
3638 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3639 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3641 elseif ($name == 'postal_code_high') {
3642 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3643 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3648 * Where / qill clause for location type.
3650 * @param array $values
3651 * @param null $status
3655 public function locationType(&$values, $status = NULL) {
3656 list($name, $op, $value, $grouping, $wildcard) = $values;
3658 if (is_array($value)) {
3659 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3660 $this->_tables
['civicrm_address'] = 1;
3661 $this->_whereTables
['civicrm_address'] = 1;
3663 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3665 foreach ($value as $id) {
3666 $names[] = $locationType[$id];
3669 $this->_primaryLocation
= FALSE;
3672 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3675 return implode(' ' . ts('or') . ' ', $names);
3682 * @param bool $fromStateProvince
3684 * @return array|NULL
3686 public function country(&$values, $fromStateProvince = TRUE) {
3687 list($name, $op, $value, $grouping, $wildcard) = $values;
3689 if (!$fromStateProvince) {
3690 $stateValues = $this->getWhereValues('state_province', $grouping);
3691 if (!empty($stateValues)) {
3692 // return back to caller if there are state province values
3693 // since that handles this case
3698 $countryClause = $countryQill = NULL;
3699 if ($values && !empty($value)) {
3700 $this->_tables
['civicrm_address'] = 1;
3701 $this->_whereTables
['civicrm_address'] = 1;
3703 $countryClause = self
::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
3704 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, 'country_id', $value, $op);
3705 $countryQill = ts("%1 %2 %3", array(1 => 'Country', 2 => $qillop, 3 => $qillVal));
3707 if (!$fromStateProvince) {
3708 $this->_where
[$grouping][] = $countryClause;
3709 $this->_qill
[$grouping][] = $countryQill;
3713 if ($fromStateProvince) {
3714 if (!empty($countryClause)) {
3717 " ...AND... " . $countryQill,
3721 return array(NULL, NULL);
3727 * Where / qill clause for county (if present).
3729 * @param array $values
3730 * @param null $status
3734 public function county(&$values, $status = NULL) {
3735 list($name, $op, $value, $grouping, $wildcard) = $values;
3737 if (!is_array($value)) {
3738 // force the county to be an array
3739 $value = array($value);
3742 // check if the values are ids OR names of the counties
3743 $inputFormat = 'id';
3744 foreach ($value as $v) {
3745 if (!is_numeric($v)) {
3746 $inputFormat = 'name';
3754 elseif ($op == '!=') {
3758 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3759 $op = str_replace('EMPTY', 'NULL', $op);
3762 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3763 $clause = "civicrm_address.county_id $op";
3765 elseif ($inputFormat == 'id') {
3766 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3768 $county = CRM_Core_PseudoConstant
::county();
3769 foreach ($value as $id) {
3770 $names[] = CRM_Utils_Array
::value($id, $county);
3774 $inputClause = array();
3775 $county = CRM_Core_PseudoConstant
::county();
3776 foreach ($value as $name) {
3777 $name = trim($name);
3778 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3780 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3783 $this->_tables
['civicrm_address'] = 1;
3784 $this->_whereTables
['civicrm_address'] = 1;
3786 $this->_where
[$grouping][] = $clause;
3788 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3791 return implode(' ' . ts('or') . ' ', $names);
3796 * Where / qill clause for state/province AND country (if present).
3798 * @param array $values
3799 * @param null $status
3803 public function stateProvince(&$values, $status = NULL) {
3804 list($name, $op, $value, $grouping, $wildcard) = $values;
3806 $stateClause = self
::buildClause('civicrm_address.state_province_id', $op, $value, 'Positive');
3807 $this->_tables
['civicrm_address'] = 1;
3808 $this->_whereTables
['civicrm_address'] = 1;
3810 $countryValues = $this->getWhereValues('country', $grouping);
3811 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3812 if ($countryClause) {
3813 $clause = "( $stateClause AND $countryClause )";
3816 $clause = $stateClause;
3819 $this->_where
[$grouping][] = $clause;
3820 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
3822 $this->_qill
[$grouping][] = ts("State/Province %1 %2 %3", array(1 => $qillop, 2 => $qillVal, 3 => $countryQill));
3825 return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill;
3830 * Where / qill clause for change log.
3832 * @param array $values
3834 public function changeLog(&$values) {
3835 list($name, $op, $value, $grouping, $wildcard) = $values;
3837 $targetName = $this->getWhereValues('changed_by', $grouping);
3842 $name = trim($targetName[2]);
3843 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3844 $name = $targetName[4] ?
"%$name%" : $name;
3845 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3846 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3847 $this->_qill
[$grouping][] = ts('Modified By') . " $name";
3853 public function modifiedDates($values) {
3854 $this->_useDistinct
= TRUE;
3856 // CRM-11281, default to added date if not set
3857 $fieldTitle = ts('Added Date');
3858 $fieldName = 'created_date';
3859 foreach (array_keys($this->_params
) as $id) {
3860 if ($this->_params
[$id][0] == 'log_date') {
3861 if ($this->_params
[$id][2] == 2) {
3862 $fieldTitle = ts('Modified Date');
3863 $fieldName = 'modified_date';
3868 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3870 self
::$_openedPanes[ts('Change Log')] = TRUE;
3876 public function demographics(&$values) {
3877 list($name, $op, $value, $grouping, $wildcard) = $values;
3879 if (($name == 'age_low') ||
($name == 'age_high')) {
3880 $this->ageRangeQueryBuilder($values,
3881 'contact_a', 'age', 'birth_date', ts('Age')
3884 elseif (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3886 $this->dateQueryBuilder($values,
3887 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3890 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3892 $this->dateQueryBuilder($values,
3893 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3897 self
::$_openedPanes[ts('Demographics')] = TRUE;
3903 public function privacy(&$values) {
3904 list($name, $op, $value, $grouping, $wildcard) = $values;
3905 //fixed for profile search listing CRM-4633
3906 if (strpbrk($value, "[")) {
3907 $value = "'{$value}'";
3909 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3912 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3914 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3915 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
3916 $title = $field ?
$field['title'] : $name;
3917 $this->_qill
[$grouping][] = "$title $op $value";
3923 public function privacyOptions($values) {
3924 list($name, $op, $value, $grouping, $wildcard) = $values;
3926 if (empty($value) ||
!is_array($value)) {
3930 // get the operator and toggle values
3931 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3934 strtolower($opValues[2] == 'AND')
3939 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3941 if ($toggleValues &&
3942 $toggleValues[2] == 2
3949 foreach ($value as $dontCare => $pOption) {
3950 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
3951 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3952 $title = $field ?
$field['title'] : $pOption;
3953 $qill[] = " $title = 1 ";
3956 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
3957 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
3963 public function preferredCommunication(&$values) {
3964 list($name, $op, $value, $grouping, $wildcard) = $values;
3966 if (!is_array($value)) {
3967 $value = str_replace(array('(', ')'), '', explode(",", $value));
3969 elseif (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3971 $value = $value[$op];
3973 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Contact', $name, $value, $op);
3975 if (self
::caseImportant($op)) {
3976 $value = implode("[[:cntrl:]]|[[:cntrl:]]", (array) $value);
3977 $op = (strstr($op, '!') ||
strstr($op, 'NOT')) ?
'NOT RLIKE' : 'RLIKE';
3978 $value = "[[:cntrl:]]" . $value . "[[:cntrl:]]";
3981 $this->_where
[$grouping][] = self
::buildClause("contact_a.preferred_communication_method", $op, $value);
3982 $this->_qill
[$grouping][] = ts('Preferred Communication Method %1 %2', array(1 => $qillop, 2 => $qillVal));
3986 * Where / qill clause for relationship.
3988 * @param array $values
3990 public function relationship(&$values) {
3991 list($name, $op, $value, $grouping, $wildcard) = $values;
3992 if ($this->_relationshipValuesAdded
) {
3995 // also get values array for relation_target_name
3996 // for relationship search we always do wildcard
3997 $relationType = $this->getWhereValues('relation_type_id', $grouping);
3998 $targetName = $this->getWhereValues('relation_target_name', $grouping);
3999 $relStatus = $this->getWhereValues('relation_status', $grouping);
4000 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4001 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4003 $nameClause = $name = NULL;
4005 $name = trim($targetName[2]);
4006 if (substr($name, 0, 1) == '"' &&
4007 substr($name, -1, 1) == '"'
4009 $name = substr($name, 1, -1);
4010 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4011 $nameClause = "= '$name'";
4014 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4015 $nameClause = "LIKE '%{$name}%'";
4019 $rTypeValues = array();
4020 if (!empty($relationType)) {
4021 $rel = explode('_', $relationType[2]);
4022 self
::$_relType = $rel[1];
4023 $params = array('id' => $rel[0]);
4024 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
4026 if (!empty($rTypeValues) && $rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
4027 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4028 //@todo unless we are dealing with a target group
4029 self
::$_relType = 'reciprocal';
4031 // if we are creating a temp table we build our own where for the relationship table
4032 $relationshipTempTable = NULL;
4033 if (self
::$_relType == 'reciprocal' && empty($targetGroup)) {
4035 self
::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO
::createTempTableName('civicrm_rel');
4037 $where[$grouping][] = " sort_name $nameClause ";
4041 $where = &$this->_where
;
4043 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4047 $allRelationshipType = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE);
4049 if ($nameClause ||
!$targetGroup) {
4050 if (!empty($relationType)) {
4051 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " $name";
4054 $this->_qill
[$grouping][] = $name;
4058 //check to see if the target contact is in specified group
4060 //add contacts from static groups
4061 $this->_tables
['civicrm_relationship_group_contact'] = $this->_whereTables
['civicrm_relationship_group_contact']
4062 = " 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'";
4063 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4064 implode(",", $targetGroup[2]) . ") ) ";
4066 //add contacts from saved searches
4067 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b", $op);
4069 //set the group where clause
4071 $groupWhere[] = "( " . $ssWhere . " )";
4073 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4075 //Get the names of the target groups for the qill
4076 $groupNames = CRM_Core_PseudoConstant
::group();
4077 $qillNames = array();
4078 foreach ($targetGroup[2] as $groupId) {
4079 if (array_key_exists($groupId, $groupNames)) {
4080 $qillNames[] = $groupNames[$groupId];
4083 if (!empty($relationType)) {
4084 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " ( " . implode(", ", $qillNames) . " )";
4087 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4091 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4092 $today = date('Ymd');
4093 //check for active, inactive and all relation status
4094 if ($relStatus[2] == 0) {
4095 $where[$grouping][] = "(
4096 civicrm_relationship.is_active = 1 AND
4097 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4098 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4100 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4102 elseif ($relStatus[2] == 1) {
4103 $where[$grouping][] = "(
4104 civicrm_relationship.is_active = 0 OR
4105 civicrm_relationship.end_date < {$today} OR
4106 civicrm_relationship.start_date > {$today}
4108 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4112 if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
)) {
4115 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4117 //check for permissioned, non-permissioned and all permissioned relations
4118 if ($relPermission[2] == 1) {
4119 $where[$grouping][] = "(
4120 civicrm_relationship.is_permission_a_b = 1
4122 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4124 elseif ($relPermission[2] == 2) {
4125 //non-allowed permission relationship.
4126 $where[$grouping][] = "(
4127 civicrm_relationship.is_permission_a_b = 0
4129 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4132 $this->addRelationshipDateClauses($grouping, $where);
4133 if (!empty($relationType) && !empty($rType) && isset($rType->id
)) {
4134 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
4136 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4137 $this->_useDistinct
= TRUE;
4138 $this->_relationshipValuesAdded
= TRUE;
4139 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4141 // @todo creating a temp table could be expanded to group filter
4142 // as even creating a temp table of all relationships is much much more efficient than
4143 // an OR in the join
4144 if ($relationshipTempTable) {
4146 if (!empty($where[$grouping])) {
4147 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4148 $whereClause = str_replace('contact_b', 'c', $whereClause);
4151 CREATE TEMPORARY TABLE {$relationshipTempTable}
4152 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4153 FROM civicrm_relationship
4154 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4157 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4158 FROM civicrm_relationship
4159 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4162 CRM_Core_DAO
::executeQuery($sql);
4168 * Add start & end date criteria in
4169 * @param string $grouping
4170 * @param array $where
4171 * = array to add where clauses to, in case you are generating a temp table.
4172 * not the main query.
4174 public function addRelationshipDateClauses($grouping, &$where) {
4175 $dateValues = array();
4181 foreach ($dateTypes as $dateField) {
4182 $dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping);
4183 $dateValueHigh = $this->getWhereValues('relation_' . $dateField . '_high', $grouping);
4184 if (!empty($dateValueLow)) {
4185 $date = date('Ymd', strtotime($dateValueLow[2]));
4186 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4187 $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);
4189 if (!empty($dateValueHigh)) {
4190 $date = date('Ymd', strtotime($dateValueHigh[2]));
4191 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4192 $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);
4198 * Default set of return properties.
4203 * derault return properties
4205 public static function &defaultReturnProperties($mode = 1) {
4206 if (!isset(self
::$_defaultReturnProperties)) {
4207 self
::$_defaultReturnProperties = array();
4210 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4211 // add activity return properties
4212 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4213 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4216 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4219 if (empty(self
::$_defaultReturnProperties[$mode])) {
4220 self
::$_defaultReturnProperties[$mode] = array(
4223 'legal_identifier' => 1,
4224 'external_identifier' => 1,
4225 'contact_type' => 1,
4226 'contact_sub_type' => 1,
4228 'display_name' => 1,
4229 'preferred_mail_format' => 1,
4236 'formal_title' => 1,
4237 'communication_style_id' => 1,
4240 'street_address' => 1,
4241 'supplemental_address_1' => 1,
4242 'supplemental_address_2' => 1,
4243 'supplemental_address_3' => 1,
4246 'postal_code_suffix' => 1,
4247 'state_province' => 1,
4249 'world_region' => 1,
4256 'household_name' => 1,
4257 'organization_name' => 1,
4258 'deceased_date' => 1,
4263 'current_employer' => 1,
4264 // FIXME: should we use defaultHierReturnProperties() for the below?
4265 'do_not_email' => 1,
4268 'do_not_phone' => 1,
4269 'do_not_trade' => 1,
4271 'contact_is_deleted' => 1,
4272 'preferred_communication_method' => 1,
4273 'preferred_language' => 1,
4277 return self
::$_defaultReturnProperties[$mode];
4281 * Get primary condition for a sql clause.
4285 * @return string|NULL
4287 public static function getPrimaryCondition($value) {
4288 if (is_numeric($value)) {
4289 $value = (int ) $value;
4290 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4296 * Wrapper for a simple search query.
4298 * @param array $params
4299 * @param array $returnProperties
4300 * @param bool $count
4304 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4305 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4306 list($select, $from, $where, $having) = $query->query();
4307 $groupBy = ($query->_useGroupBy
) ?
'GROUP BY contact_a.id' : '';
4309 $query = "$select $from $where $groupBy $having";
4314 * These are stub comments as this function needs more explanation - particularly in terms of how it
4315 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4317 * This function was originally written as a wrapper for the api query but is called from multiple places
4318 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4319 * but it is unclear as to whehter that is historical or there is a reason
4320 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4322 * @param array $params
4323 * @param array $returnProperties
4324 * @param null $fields
4325 * @param string $sort
4326 * @param int $offset
4327 * @param int $row_count
4328 * @param bool $smartGroupCache
4329 * ?? update smart group cache?.
4330 * @param bool $count
4331 * Return count obnly.
4332 * @param bool $skipPermissions
4333 * Should permissions be ignored or should the logged in user's permissions be applied.
4335 * This basically correlates to the component.
4336 * @param string $apiEntity
4337 * The api entity being called.
4338 * This sort-of duplicates $mode in a confusing way. Probably not by design.
4342 public static function apiQuery(
4344 $returnProperties = NULL,
4349 $smartGroupCache = TRUE,
4351 $skipPermissions = TRUE,
4352 $mode = CRM_Contact_BAO_Query
::MODE_CONTACTS
,
4356 $query = new CRM_Contact_BAO_Query(
4357 $params, $returnProperties,
4358 NULL, TRUE, FALSE, $mode,
4360 TRUE, $smartGroupCache,
4365 //this should add a check for view deleted if permissions are enabled
4366 if ($skipPermissions) {
4367 $query->_skipDeleteClause
= TRUE;
4369 $query->generatePermissionClause(FALSE, $count);
4371 // note : this modifies _fromClause and _simpleFromClause
4372 $query->includePseudoFieldsJoin($sort);
4374 list($select, $from, $where, $having) = $query->query($count);
4376 $options = $query->_options
;
4377 if (!empty($query->_permissionWhereClause
)) {
4378 if (empty($where)) {
4379 $where = "WHERE $query->_permissionWhereClause";
4382 $where = "$where AND $query->_permissionWhereClause";
4386 $sql = "$select $from $where $having";
4389 if ($query->_useGroupBy
) {
4390 $sql .= self
::getGroupByFromSelectColumns($query->_select
, 'contact_a.id');
4392 if (!empty($sort)) {
4393 $sort = CRM_Utils_Type
::escape($sort, 'String');
4394 $sql .= " ORDER BY $sort ";
4396 if ($row_count > 0 && $offset >= 0) {
4397 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4398 $row_count = CRM_Utils_Type
::escape($row_count, 'Int');
4399 $sql .= " LIMIT $offset, $row_count ";
4402 $dao = CRM_Core_DAO
::executeQuery($sql);
4404 // @todo derive this from the component class rather than hard-code two options.
4405 $entityIDField = ($mode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) ?
'contribution_id' : 'contact_id';
4408 while ($dao->fetch()) {
4410 $noRows = $dao->rowCount
;
4412 return array($noRows, NULL);
4414 $val = $query->store($dao);
4415 $convertedVals = $query->convertToPseudoNames($dao, TRUE, TRUE);
4417 if (!empty($convertedVals)) {
4418 $val = array_replace_recursive($val, $convertedVals);
4420 $values[$dao->$entityIDField] = $val;
4423 return array($values, $options);
4427 * Get the actual custom field name by stripping off the appended string.
4429 * The string could be _relative, _from, or _to
4431 * @todo use metadata rather than convention to do this.
4433 * @param string $parameterName
4434 * The name of the parameter submitted to the form.
4441 public static function getCustomFieldName($parameterName) {
4442 if (substr($parameterName, -5, 5) == '_from') {
4443 return substr($parameterName, 0, strpos($parameterName, '_from'));
4445 if (substr($parameterName, -9, 9) == '_relative') {
4446 return substr($parameterName, 0, strpos($parameterName, '_relative'));
4448 if (substr($parameterName, -3, 3) == '_to') {
4449 return substr($parameterName, 0, strpos($parameterName, '_to'));
4454 * Convert submitted values for relative custom fields to query object format.
4456 * The query will support the sqlOperator format so convert to that format.
4458 * @param array $formValues
4460 * @param array $params
4461 * Converted parameters for the query object.
4462 * @param string $values
4464 * @param string $fieldName
4465 * Submitted field name. (Matches form field not DB field.)
4467 protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) {
4468 if (empty($values)) {
4469 // e.g we might have relative set & from & to empty. The form flow is a bit funky &
4470 // this function gets called again after they fields have been converted which can get ugly.
4473 $customFieldName = self
::getCustomFieldName($fieldName);
4475 if (substr($fieldName, -9, 9) == '_relative') {
4476 list($from, $to) = CRM_Utils_Date
::getFromTo($values, NULL, NULL);
4479 if ($fieldName == $customFieldName . '_to' && CRM_Utils_Array
::value($customFieldName . '_from', $formValues)) {
4480 // Both to & from are set. We only need to acton one, choosing from.
4484 $from = CRM_Utils_Array
::value($customFieldName . '_from', $formValues, NULL);
4485 $to = CRM_Utils_Array
::value($customFieldName . '_to', $formValues, NULL);
4487 if (self
::isCustomDateField($customFieldName)) {
4488 list($from, $to) = CRM_Utils_Date
::getFromTo(NULL, $from, $to);
4494 $relativeFunction = array('BETWEEN' => array($from, $to));
4497 $relativeFunction = array('>=' => $from);
4501 $relativeFunction = array('<=' => $to);
4513 * Are we dealing with custom field of type date.
4519 public static function isCustomDateField($fieldName) {
4520 if (($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($fieldName)) == FALSE) {
4523 if ('Date' == civicrm_api3('CustomField', 'getvalue', array('id' => $customFieldID, 'return' => 'data_type'))) {
4530 * Has this field already been reformatting to Query object syntax.
4532 * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems
4533 * to come with associated double queries & is possibly damaging performance.
4535 * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns
4538 * @param mixed $values
4539 * Value in formValues for the field.
4543 public static function isAlreadyProcessedForQueryFormat($values) {
4544 if (!is_array($values)) {
4547 if (($operator = CRM_Utils_Array
::value(1, $values)) == FALSE) {
4550 return in_array($operator, CRM_Core_DAO
::acceptedSQLOperators());
4554 * If the state and country are passed remove state.
4556 * Country is implicit from the state, but including both results in
4557 * a poor query as there is no combined index on state AND country.
4561 * @param array $formValues
4563 public static function filterCountryFromValuesIfStateExists(&$formValues) {
4564 if (!empty($formValues['country']) && !empty($formValues['state_province'])) {
4565 // The use of array map sanitises the data by ensuring we are dealing with integers.
4566 $states = implode(', ', array_map('intval', $formValues['state_province']));
4567 $countryList = CRM_Core_DAO
::singleValueQuery(
4568 "SELECT GROUP_CONCAT(country_id) FROM civicrm_state_province WHERE id IN ($states)"
4570 if ($countryList == $formValues['country']) {
4571 unset($formValues['country']);
4577 * For some special cases, grouping by subset of select fields becomes mandatory.
4578 * Hence, full_group_by mode is handled by appending any_value
4579 * keyword to select fields not present in groupBy
4581 * @param array $selectClauses
4582 * @param array $groupBy - Columns already included in GROUP By clause.
4586 public static function appendAnyValueToSelect($selectClauses, $groupBy) {
4587 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4588 $sqlMode = explode(',', CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode'));
4590 // Disable only_full_group_by mode for lower sql versions.
4591 if (version_compare($mysqlVersion, '5.7', '<') ||
(!empty($sqlMode) && !in_array('ONLY_FULL_GROUP_BY', $sqlMode))) {
4592 $key = array_search('ONLY_FULL_GROUP_BY', $sqlMode);
4593 unset($sqlMode[$key]);
4594 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = '" . implode(',', $sqlMode) . "'");
4597 $groupBy = array_map('trim', (array) $groupBy);
4598 $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN)\(/i';
4599 foreach ($selectClauses as $key => &$val) {
4600 list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL);
4601 // append ANY_VALUE() keyword
4602 if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) {
4603 $val = str_replace($selectColumn, "ANY_VALUE({$selectColumn})", $val);
4608 return "SELECT " . implode(', ', $selectClauses) . " ";
4612 * Include Select columns in groupBy clause.
4614 * @param array $selectClauses
4615 * @param array $groupBy - Columns already included in GROUP By clause.
4619 public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NULL) {
4620 $groupBy = (array) $groupBy;
4621 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4622 $sqlMode = CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode');
4624 //return if ONLY_FULL_GROUP_BY is not enabled.
4625 if (!version_compare($mysqlVersion, '5.7', '<') && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
4626 $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN)\(/i';
4627 foreach ($selectClauses as $key => $val) {
4628 $aliasArray = preg_split('/ as /i', $val);
4629 // if more than 1 alias we need to split by ','.
4630 if (count($aliasArray) > 2) {
4631 $aliasArray = preg_split('/,/', $val);
4632 foreach ($aliasArray as $key => $value) {
4633 $alias = current(preg_split('/ as /i', $value));
4634 if (!in_array($alias, $groupBy) && preg_match($regexToExclude, trim($alias)) !== 1) {
4635 $groupBy[] = $alias;
4640 list($selectColumn, $alias) = array_pad($aliasArray, 2, NULL);
4641 $dateRegex = '/^(DATE_FORMAT|DATE_ADD|CASE)/i';
4642 $tableName = current(explode('.', $selectColumn));
4643 $primaryKey = "{$tableName}.id";
4644 // exclude columns which are already included in groupBy and aggregate functions from select
4645 // CRM-18439 - Also exclude the columns which are functionally dependent on columns in $groupBy (MySQL 5.7+)
4646 if (!in_array($selectColumn, $groupBy) && !in_array($primaryKey, $groupBy) && preg_match($regexToExclude, trim($selectColumn)) !== 1) {
4647 if (!empty($alias) && preg_match($dateRegex, trim($selectColumn))) {
4648 $groupBy[] = $alias;
4651 $groupBy[] = $selectColumn;
4658 if (!empty($groupBy)) {
4659 return " GROUP BY " . implode(', ', $groupBy);
4665 * Create and query the db for an contact search.
4667 * @param int $offset
4668 * The offset for the query.
4669 * @param int $rowCount
4670 * The number of rows to return.
4671 * @param string|CRM_Utils_Sort $sort
4672 * The order by string.
4673 * @param bool $count
4674 * Is this a count only query ?.
4675 * @param bool $includeContactIds
4676 * Should we include contact ids?.
4677 * @param bool $sortByChar
4678 * If true returns the distinct array of first characters for search results.
4679 * @param bool $groupContacts
4680 * If true, return only the contact ids.
4681 * @param bool $returnQuery
4682 * Should we return the query as a string.
4683 * @param string $additionalWhereClause
4684 * If the caller wants to further restrict the search (used for components).
4685 * @param null $sortOrder
4686 * @param string $additionalFromClause
4687 * Should be clause with proper joins, effective to reduce where clause load.
4689 * @param bool $skipOrderAndLimit
4691 * @return CRM_Core_DAO
4693 public function searchQuery(
4694 $offset = 0, $rowCount = 0, $sort = NULL,
4695 $count = FALSE, $includeContactIds = FALSE,
4696 $sortByChar = FALSE, $groupContacts = FALSE,
4697 $returnQuery = FALSE,
4698 $additionalWhereClause = NULL, $sortOrder = NULL,
4699 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4702 if ($includeContactIds) {
4703 $this->_includeContactIds
= TRUE;
4704 $this->_whereClause
= $this->whereClause();
4707 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4709 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4710 // and that contact happens to be deleted, set $onlyDeleted to true
4711 foreach ($this->_params
as $values) {
4712 $name = CRM_Utils_Array
::value(0, $values);
4713 $op = CRM_Utils_Array
::value(1, $values);
4714 $value = CRM_Utils_Array
::value(2, $values);
4715 if ($name == 'contact_id' and $op == '=') {
4716 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4717 $onlyDeleted = TRUE;
4723 // building the query string
4724 $groupBy = $groupByCol = NULL;
4726 if (isset($this->_groupByComponentClause
)) {
4727 $groupBy = $this->_groupByComponentClause
;
4728 $groupCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause
));
4729 $groupByCol = explode(', ', $groupCols);
4731 elseif ($this->_useGroupBy
) {
4732 $groupByCol = 'contact_a.id';
4733 $groupBy = ' GROUP BY contact_a.id';
4736 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4737 $groupByCol = 'civicrm_activity.id';
4738 $groupBy = 'GROUP BY civicrm_activity.id ';
4741 $order = $orderBy = $limit = '';
4743 list($order, $additionalFromClause) = $this->prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause);
4745 if ($rowCount > 0 && $offset >= 0) {
4746 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4747 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4748 $limit = " LIMIT $offset, $rowCount ";
4753 $this->_sort
= $sort;
4756 $this->includePseudoFieldsJoin($sort);
4758 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4760 if (!empty($groupByCol)) {
4761 $groupBy = self
::getGroupByFromSelectColumns($this->_select
, $groupByCol);
4764 if ($additionalWhereClause) {
4765 $where = $where . ' AND ' . $additionalWhereClause;
4768 //additional from clause should be w/ proper joins.
4769 if ($additionalFromClause) {
4770 $from .= "\n" . $additionalFromClause;
4773 // if we are doing a transform, do it here
4774 // use the $from, $where and $having to get the contact ID
4775 if ($this->_displayRelationshipType
) {
4776 $this->filterRelatedContacts($from, $where, $having);
4779 if ($skipOrderAndLimit) {
4780 $query = "$select $from $where $having $groupBy";
4783 $query = "$select $from $where $having $groupBy $order $limit";
4790 return CRM_Core_DAO
::singleValueQuery($query);
4793 $dao = CRM_Core_DAO
::executeQuery($query);
4794 if ($groupContacts) {
4796 while ($dao->fetch()) {
4800 return implode(',', $ids);
4807 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4809 * @param string $cacheKey
4810 * @param int $offset
4811 * @param int $rowCount
4812 * @param bool $includeContactIds
4813 * @return CRM_Core_DAO
4815 public function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4816 $this->_includeContactIds
= $includeContactIds;
4817 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4818 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
4819 $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);
4820 $order = " ORDER BY pnc.id";
4821 $groupByCol = array('contact_a.id', 'pnc.id');
4822 $groupBy = self
::getGroupByFromSelectColumns($this->_select
, $groupByCol);
4823 $limit = " LIMIT $offset, $rowCount";
4824 $query = "$select $from $where $groupBy $order $limit";
4826 return CRM_Core_DAO
::executeQuery($query);
4830 * Populate $this->_permissionWhereClause with permission related clause and update other
4831 * query related properties.
4833 * Function calls ACL permission class and hooks to filter the query appropriately
4835 * Note that these 2 params were in the code when extracted from another function
4836 * and a second round extraction would be to make them properties of the class
4838 * @param bool $onlyDeleted
4839 * Only get deleted contacts.
4840 * @param bool $count
4841 * Return Count only.
4843 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4844 if (!$this->_skipPermission
) {
4845 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4846 CRM_Core_Permission
::VIEW
,
4848 $this->_whereTables
,
4851 $this->_skipDeleteClause
4854 // regenerate fromClause since permission might have added tables
4855 if ($this->_permissionWhereClause
) {
4856 //fix for row count in qill (in contribute/membership find)
4858 $this->_useDistinct
= TRUE;
4861 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4862 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4863 // note : this modifies _fromClause and _simpleFromClause
4864 $this->includePseudoFieldsJoin($this->_sort
);
4868 // add delete clause if needed even if we are skipping permission
4870 if (!$this->_skipDeleteClause
) {
4871 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4872 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4876 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4885 public function setSkipPermission($val) {
4886 $this->_skipPermission
= $val;
4890 * @param null $context
4894 public function &summaryContribution($context = NULL) {
4895 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4899 SELECT COUNT( conts.total_amount ) as total_count,
4900 SUM( conts.total_amount ) as total_amount,
4901 AVG( conts.total_amount ) as total_avg,
4902 conts.currency as currency";
4903 if ($this->_permissionWhereClause
) {
4904 $where .= " AND " . $this->_permissionWhereClause
;
4906 if ($context == 'search') {
4907 $where .= " AND contact_a.is_deleted = 0 ";
4909 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4910 if (!empty($financialTypes)) {
4911 $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
4912 $from .= " LEFT JOIN civicrm_line_item li
4913 ON civicrm_contribution.id = li.contribution_id AND
4914 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
4917 $where .= " AND civicrm_contribution.financial_type_id IN (0)";
4920 // make sure contribution is completed - CRM-4989
4921 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4924 $summary['total'] = array();
4925 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4926 $innerQuery = "SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
4927 civicrm_contribution.currency $from $completedWhere";
4928 $query = "$select FROM (
4929 $innerQuery GROUP BY civicrm_contribution.id
4933 $dao = CRM_Core_DAO
::executeQuery($query);
4935 $summary['total']['count'] = 0;
4936 $summary['total']['amount'] = $summary['total']['avg'] = array();
4937 while ($dao->fetch()) {
4938 $summary['total']['count'] +
= $dao->total_count
;
4939 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4940 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4943 $orderBy = 'ORDER BY civicrm_contribution_total_amount_count DESC';
4944 $groupBy = 'GROUP BY currency, civicrm_contribution.total_amount';
4945 $modeSQL = "$select, SUBSTRING_INDEX(GROUP_CONCAT(conts.total_amount
4946 ORDER BY conts.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
4947 MAX(conts.civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count
4949 $groupBy $orderBy) as conts
4952 $summary['total']['mode'] = CRM_Contribute_BAO_Contribution
::computeStats('mode', $modeSQL);
4954 $medianSQL = "{$from} {$completedWhere}";
4955 $summary['total']['median'] = CRM_Contribute_BAO_Contribution
::computeStats('median', $medianSQL, 'civicrm_contribution');
4956 $summary['total']['currencyCount'] = count($summary['total']['median']);
4958 if (!empty($summary['total']['amount'])) {
4959 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4960 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4961 $summary['total']['mode'] = implode(', ', $summary['total']['mode']);
4962 $summary['total']['median'] = implode(', ', $summary['total']['median']);
4965 $summary['total']['amount'] = $summary['total']['avg'] = $summary['total']['median'] = 0;
4968 // soft credit summary
4969 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
4970 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
4973 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
4974 GROUP BY civicrm_contribution_soft.id
4977 $dao = CRM_Core_DAO
::executeQuery($query);
4978 $summary['soft_credit']['count'] = 0;
4979 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
4980 while ($dao->fetch()) {
4981 $summary['soft_credit']['count'] +
= $dao->total_count
;
4982 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4983 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4985 if (!empty($summary['soft_credit']['amount'])) {
4986 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
4987 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
4990 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
4995 //@todo - this could be one query using the IF in mysql - eg
4996 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
4997 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
4998 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
4999 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
5000 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
5001 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
5002 // FROM civicrm_contact contact_a
5003 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
5004 // WHERE ( ... where clause....
5005 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
5009 SELECT COUNT( conts.total_amount ) as cancel_count,
5010 SUM( conts.total_amount ) as cancel_amount,
5011 AVG( conts.total_amount ) as cancel_avg,
5012 conts.currency as currency";
5014 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
5015 if ($context == 'search') {
5016 $where .= " AND contact_a.is_deleted = 0 ";
5019 $query = "$select FROM (
5020 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
5021 GROUP BY civicrm_contribution.id
5025 $dao = CRM_Core_DAO
::executeQuery($query);
5028 if ($dao->fetch()) {
5029 $summary['cancel']['count'] = $dao->cancel_count
;
5030 $summary['cancel']['amount'] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
5031 $summary['cancel']['avg'] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
5035 $summary['cancel']['count'] = 0;
5036 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
5037 while ($dao->fetch()) {
5038 $summary['cancel']['count'] +
= $dao->cancel_count
;
5039 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
5040 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
5042 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
5043 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
5050 * Getter for the qill object.
5054 public function qill() {
5055 return $this->_qill
;
5059 * Default set of return default hier return properties.
5063 public static function &defaultHierReturnProperties() {
5064 if (!isset(self
::$_defaultHierReturnProperties)) {
5065 self
::$_defaultHierReturnProperties = array(
5068 'legal_identifier' => 1,
5069 'external_identifier' => 1,
5070 'contact_type' => 1,
5071 'contact_sub_type' => 1,
5073 'display_name' => 1,
5080 'formal_title' => 1,
5081 'communication_style_id' => 1,
5082 'email_greeting' => 1,
5083 'postal_greeting' => 1,
5087 'preferred_communication_method' => 1,
5088 'do_not_phone' => 1,
5089 'do_not_email' => 1,
5092 'do_not_trade' => 1,
5093 'location' => array(
5095 'location_type' => 1,
5096 'street_address' => 1,
5098 'state_province' => 1,
5100 'postal_code_suffix' => 1,
5103 'phone-Mobile' => 1,
5116 'location_type' => 1,
5117 'street_address' => 1,
5119 'state_province' => 1,
5121 'postal_code_suffix' => 1,
5124 'phone-Mobile' => 1,
5138 return self
::$_defaultHierReturnProperties;
5142 * Build query for a date field.
5144 * @param array $values
5145 * @param string $tableName
5146 * @param string $fieldName
5147 * @param string $dbFieldName
5148 * @param string $fieldTitle
5149 * @param bool $appendTimeStamp
5151 public function dateQueryBuilder(
5152 &$values, $tableName, $fieldName,
5153 $dbFieldName, $fieldTitle,
5154 $appendTimeStamp = TRUE
5156 list($name, $op, $value, $grouping, $wildcard) = $values;
5158 if ($name == "{$fieldName}_low" ||
5159 $name == "{$fieldName}_high"
5161 if (isset($this->_rangeCache
[$fieldName]) ||
!$value) {
5164 $this->_rangeCache
[$fieldName] = 1;
5166 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
5168 if ($name == $fieldName . '_low') {
5170 $firstPhrase = ts('greater than or equal to');
5171 $firstDate = CRM_Utils_Date
::processDate($value);
5173 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5174 if (!empty($secondValues) && $secondValues[2]) {
5176 $secondPhrase = ts('less than or equal to');
5177 $secondValue = $secondValues[2];
5179 if ($appendTimeStamp && strlen($secondValue) == 10) {
5180 $secondValue .= ' 23:59:59';
5182 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5185 elseif ($name == $fieldName . '_high') {
5187 $firstPhrase = ts('less than or equal to');
5189 if ($appendTimeStamp && strlen($value) == 10) {
5190 $value .= ' 23:59:59';
5192 $firstDate = CRM_Utils_Date
::processDate($value);
5194 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5195 if (!empty($secondValues) && $secondValues[2]) {
5197 $secondPhrase = ts('greater than or equal to');
5198 $secondValue = $secondValues[2];
5199 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5203 if (!$appendTimeStamp) {
5204 $firstDate = substr($firstDate, 0, 8);
5206 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5209 if (!$appendTimeStamp) {
5210 $secondDate = substr($secondDate, 0, 8);
5212 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5215 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5217 $this->_where
[$grouping][] = "
5218 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5219 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5221 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5224 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5225 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5229 if ($name == $fieldName) {
5230 //In Get API, for operators other then '=' the $value is in array(op => value) format
5231 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5233 $value = $value[$op];
5236 $date = $format = NULL;
5237 if (strstr($op, 'IN')) {
5239 foreach ($value as &$date) {
5240 $date = CRM_Utils_Date
::processDate($date);
5241 if (!$appendTimeStamp) {
5242 $date = substr($date, 0, 8);
5244 $format[] = CRM_Utils_Date
::customFormat($date);
5246 $date = "('" . implode("','", $value) . "')";
5247 $format = implode(', ', $format);
5249 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5250 $date = CRM_Utils_Date
::processDate($value);
5251 if (!$appendTimeStamp) {
5252 $date = substr($date, 0, 8);
5254 $format = CRM_Utils_Date
::customFormat($date);
5259 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5262 $this->_where
[$grouping][] = self
::buildClause("{$tableName}.{$dbFieldName}", $op);
5265 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5267 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
5268 $this->_qill
[$grouping][] = "$fieldTitle $op $format";
5274 * @param string $tableName
5275 * @param string $fieldName
5276 * @param string $dbFieldName
5277 * @param $fieldTitle
5278 * @param null $options
5280 public function numberRangeBuilder(
5282 $tableName, $fieldName,
5283 $dbFieldName, $fieldTitle,
5286 list($name, $op, $value, $grouping, $wildcard) = $values;
5288 if ($name == "{$fieldName}_low" ||
5289 $name == "{$fieldName}_high"
5291 if (isset($this->_rangeCache
[$fieldName])) {
5294 $this->_rangeCache
[$fieldName] = 1;
5296 $secondOP = $secondPhrase = $secondValue = NULL;
5298 if ($name == "{$fieldName}_low") {
5300 $firstPhrase = ts('greater than');
5302 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5303 if (!empty($secondValues)) {
5305 $secondPhrase = ts('less than');
5306 $secondValue = $secondValues[2];
5311 $firstPhrase = ts('less than');
5313 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5314 if (!empty($secondValues)) {
5316 $secondPhrase = ts('greater than');
5317 $secondValue = $secondValues[2];
5322 $this->_where
[$grouping][] = "
5323 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5324 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5326 $displayValue = $options ?
$options[$value] : $value;
5327 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5329 $this->_qill
[$grouping][]
5330 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5333 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5334 $displayValue = $options ?
$options[$value] : $value;
5335 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5337 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5342 if ($name == $fieldName) {
5346 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5348 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5349 $displayValue = $options ?
$options[$value] : $value;
5350 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5357 * @param string $tableName
5358 * @param string $fieldName
5359 * @param string $dbFieldName
5360 * @param $fieldTitle
5361 * @param null $options
5363 public function ageRangeQueryBuilder(
5365 $tableName, $fieldName,
5366 $dbFieldName, $fieldTitle,
5369 list($name, $op, $value, $grouping, $wildcard) = $values;
5371 $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
5372 $asofDate = NULL; // will be treated as current day
5373 if ($asofDateValues) {
5374 $asofDate = CRM_Utils_Date
::processDate($asofDateValues[2]);
5375 $asofDateFormat = CRM_Utils_Date
::customFormat(substr($asofDate, 0, 8));
5376 $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat;
5379 if ($name == "{$fieldName}_low" ||
5380 $name == "{$fieldName}_high"
5382 if (isset($this->_rangeCache
[$fieldName])) {
5385 $this->_rangeCache
[$fieldName] = 1;
5387 $secondOP = $secondPhrase = $secondValue = NULL;
5389 if ($name == "{$fieldName}_low") {
5390 $firstPhrase = ts('greater than or equal to');
5391 // NB: age > X means date of birth < Y
5393 $firstDate = self
::calcDateFromAge($asofDate, $value, 'min');
5395 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5396 if (!empty($secondValues)) {
5398 $secondPhrase = ts('less than or equal to');
5399 $secondValue = $secondValues[2];
5400 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'max');
5405 $firstPhrase = ts('less than or equal to');
5406 $firstDate = self
::calcDateFromAge($asofDate, $value, 'max');
5408 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5409 if (!empty($secondValues)) {
5411 $secondPhrase = ts('greater than or equal to');
5412 $secondValue = $secondValues[2];
5413 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'min');
5418 $this->_where
[$grouping][] = "
5419 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5420 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5422 $displayValue = $options ?
$options[$value] : $value;
5423 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5425 $this->_qill
[$grouping][]
5426 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5429 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5430 $displayValue = $options ?
$options[$value] : $value;
5431 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5433 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5439 * Calculate date from age.
5441 * @param string $asofDate
5443 * @param string $type
5447 public static function calcDateFromAge($asofDate, $age, $type) {
5448 $date = new DateTime($asofDate);
5449 if ($type == "min") {
5450 // minimum age is $age: dob <= date - age "235959"
5451 $date->sub(new DateInterval("P" . $age . "Y"));
5452 return $date->format('Ymd') . "235959";
5455 // max age is $age: dob >= date - (age + 1y) + 1d "000000"
5456 $date->sub(new DateInterval("P" . ($age +
1) . "Y"))->add(new DateInterval("P1D"));
5457 return $date->format('Ymd') . "000000";
5462 * Given the field name, operator, value & its data type
5463 * builds the where Clause for the query
5464 * used for handling 'IS NULL'/'IS NOT NULL' operators
5466 * @param string $field
5470 * @param string $value
5472 * @param string $dataType
5473 * Data type of the field.
5476 * Where clause for the query.
5478 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5480 $clause = "$field $op";
5488 $clause = " (NULLIF($field, '') IS NULL) ";
5491 case 'IS NOT EMPTY':
5492 $clause = " (NULLIF($field, '') IS NOT NULL) ";
5497 // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
5498 if (!empty($value) && (!is_array($value) ||
!array_key_exists($op, $value))) {
5499 $value = array($op => (array) $value);
5503 if (empty($dataType)) {
5504 $dataType = 'String';
5506 if (is_array($value)) {
5507 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5508 // widely used and consistent across the codebase
5509 // adding this here won't accept the search functions which don't submit an array
5510 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, $value, $dataType)) != FALSE) {
5512 return $queryString;
5515 // 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))
5516 // but we got only array(2,5) from the form.
5517 // We could get away with keeping this in 4.6 if we make it such that it throws an enotice in 4.7 so
5518 // people have to de-slopify it.
5519 if (!empty($value[0])) {
5520 if ($op != 'BETWEEN') {
5521 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReport;
5523 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => $value), $dataType)) != FALSE) {
5524 return $queryString;
5529 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReportUsingOldFormat;
5530 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => array_keys($value)), $dataType)) != FALSE) {
5531 return $queryString;
5536 $value = CRM_Utils_Type
::escape($value, $dataType);
5537 // if we don't have a dataType we should assume
5538 if ($dataType == 'String' ||
$dataType == 'Text') {
5539 $value = "'" . strtolower($value) . "'";
5541 return "$clause $value";
5546 * @param bool $reset
5550 public function openedSearchPanes($reset = FALSE) {
5551 if (!$reset ||
empty($this->_whereTables
)) {
5552 return self
::$_openedPanes;
5555 // pane name to table mapper
5556 $panesMapper = array(
5557 ts('Contributions') => 'civicrm_contribution',
5558 ts('Memberships') => 'civicrm_membership',
5559 ts('Events') => 'civicrm_participant',
5560 ts('Relationships') => 'civicrm_relationship',
5561 ts('Activities') => 'civicrm_activity',
5562 ts('Pledges') => 'civicrm_pledge',
5563 ts('Cases') => 'civicrm_case',
5564 ts('Grants') => 'civicrm_grant',
5565 ts('Address Fields') => 'civicrm_address',
5566 ts('Notes') => 'civicrm_note',
5567 ts('Change Log') => 'civicrm_log',
5568 ts('Mailings') => 'civicrm_mailing',
5570 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5572 foreach (array_keys($this->_whereTables
) as $table) {
5573 if ($panName = array_search($table, $panesMapper)) {
5574 self
::$_openedPanes[$panName] = TRUE;
5578 return self
::$_openedPanes;
5584 public function setOperator($operator) {
5585 $validOperators = array('AND', 'OR');
5586 if (!in_array($operator, $validOperators)) {
5589 $this->_operator
= $operator;
5595 public function getOperator() {
5596 return $this->_operator
;
5604 public function filterRelatedContacts(&$from, &$where, &$having) {
5605 static $_rTypeProcessed = NULL;
5606 static $_rTypeFrom = NULL;
5607 static $_rTypeWhere = NULL;
5609 if (!$_rTypeProcessed) {
5610 $_rTypeProcessed = TRUE;
5612 // create temp table with contact ids
5613 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5614 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5615 CRM_Core_DAO
::executeQuery($sql);
5618 REPLACE INTO $tableName ( contact_id )
5624 CRM_Core_DAO
::executeQuery($sql);
5626 $qillMessage = ts('Contacts with a Relationship Type of: ');
5627 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5629 if (is_numeric($this->_displayRelationshipType
)) {
5630 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5632 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5633 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5636 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5637 AND displayRelType.is_active = 1
5641 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5642 if ($dirOne == 'a') {
5643 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5645 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5646 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5650 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5652 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5653 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5657 WHERE displayRelType.relationship_type_id = $relType
5658 AND displayRelType.is_active = 1
5661 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5664 if (!empty($this->_permissionWhereClause
)) {
5665 $_rTypeWhere .= "AND $this->_permissionWhereClause";
5668 if (strpos($from, $_rTypeFrom) === FALSE) {
5669 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5670 // this happens when we have an event_type in the quert (CRM-7969)
5671 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5672 $from .= $_rTypeFrom;
5673 $where = $_rTypeWhere;
5680 * See CRM-19811 for why this is database hurty without apparent benefit.
5686 public static function caseImportant($op) {
5688 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5692 * @param $returnProperties
5697 public static function componentPresent(&$returnProperties, $prefix) {
5698 foreach ($returnProperties as $name => $dontCare) {
5699 if (substr($name, 0, strlen($prefix)) == $prefix) {
5707 * Builds the necessary structures for all fields that are similar to option value look-ups.
5709 * @param string $name
5710 * the name of the field.
5712 * the sql operator, this function should handle ALL SQL operators.
5713 * @param string $value
5714 * depends on the operator and who's calling the query builder.
5715 * @param int $grouping
5716 * the index where to place the where clause.
5717 * @param string $daoName
5719 * @param array $field
5720 * an array that contains various properties of the field identified by $name.
5721 * @param string $label
5722 * The label for this field element.
5723 * @param string $dataType
5724 * The data type for this element.
5725 * @param bool $useIDsOnly
5727 public function optionValueQuery(
5735 $dataType = 'String',
5739 $pseudoFields = array(
5746 'communication_style_id',
5750 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5751 if ($tableName == 'civicrm_contact') {
5752 $wc = "contact_a.$fieldName";
5755 $wc = "$tableName.id";
5759 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
5760 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5762 if (in_array($name, $pseudoFields)) {
5763 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5764 $wc = "contact_a.{$name}_id";
5766 $dataType = 'Positive';
5767 $value = (!$value) ?
0 : $value;
5769 if ($name == "world_region") {
5770 $field['name'] = $name;
5773 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue($daoName, $field['name'], $value, $op);
5774 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillop, 3 => $qillVal));
5775 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5779 * Check and explode a user defined numeric string into an array
5780 * this was the protocol used by search builder in the old old days before we had
5781 * super nice js widgets to do the hard work
5783 * @param string $string
5784 * @param string $dataType
5785 * The dataType we should check for the values, default integer.
5787 * @return bool|array
5788 * false if string does not match the pattern
5789 * array of numeric values if string does match the pattern
5791 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5792 $string = trim($string);
5793 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5797 $string = substr($string, 1, -1);
5798 $values = explode(',', $string);
5799 if (empty($values)) {
5803 $returnValues = array();
5804 foreach ($values as $v) {
5805 if ($dataType == 'Integer' && !is_numeric($v)) {
5808 elseif ($dataType == 'String' && !is_string($v)) {
5811 $returnValues[] = trim($v);
5814 if (empty($returnValues)) {
5818 return $returnValues;
5822 * Convert the pseudo constants id's to their names
5824 * @param CRM_Core_DAO $dao
5825 * @param bool $return
5826 * @param bool $usedForAPI
5828 * @return array|NULL
5830 public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) {
5831 if (empty($this->_pseudoConstantsSelect
)) {
5835 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5836 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5840 if (is_object($dao) && property_exists($dao, $value['idCol'])) {
5841 $val = $dao->{$value['idCol']};
5842 if ($key == 'groups') {
5843 $dao->groups
= $this->convertGroupIDStringToLabelString($dao, $val);
5847 if (CRM_Utils_System
::isNull($val)) {
5850 elseif (!empty($value['pseudoconstant'])) {
5851 // If pseudoconstant is set that is kind of defacto for 'we have a bit more info about this'
5852 // and we can use the metadata to figure it out.
5853 // ideally this bit of IF will absorb & replace all the rest in time as we move to
5854 // more metadata based choices.
5855 if (strpos($val, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
5856 $dbValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($val, CRM_Core_DAO
::VALUE_SEPARATOR
));
5857 foreach ($dbValues as $pseudoValue) {
5858 $convertedValues[] = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $pseudoValue);
5861 $dao->$key = ($usedForAPI) ?
$convertedValues : implode(', ', $convertedValues);
5862 $realFieldName = CRM_Utils_Array
::value('field_name', $this->_pseudoConstantsSelect
[$key]);
5863 if ($usedForAPI && $realFieldName) {
5864 // normally we would see 2 fields returned for pseudoConstants. An exception is
5865 // preferred_communication_method where there is no id-variant.
5866 // For the api we prioritise getting the real data returned.
5867 // over the resolved version
5868 $dao->$realFieldName = $dbValues;
5873 // This is basically the same as the default but since we have the bao we can use
5874 // a cached function.
5875 $dao->$key = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $val);
5878 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5880 $idColumn = "{$key}_id";
5881 $dao->$idColumn = $val;
5883 if ($key == 'state_province_name') {
5884 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::stateProvince($val);
5887 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5890 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5891 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5893 // @todo handle this in the section above for pseudoconstants.
5894 elseif (in_array($value['pseudoField'], array('participant_role_id', 'participant_role'))) {
5895 // @todo define bao on this & merge into the above condition.
5896 $viewValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val);
5898 if ($value['pseudoField'] == 'participant_role') {
5899 $pseudoOptions = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'role_id');
5900 foreach ($viewValues as $k => $v) {
5901 $viewValues[$k] = $pseudoOptions[$v];
5904 $dao->$key = ($usedForAPI && count($viewValues) > 1) ?
$viewValues : implode(', ', $viewValues);
5907 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5908 $dao->$key = $labels[$val];
5911 // return converted values in array format
5913 if (strpos($key, '-') !== FALSE) {
5914 $keyVal = explode('-', $key);
5915 $current = &$values;
5916 $lastElement = array_pop($keyVal);
5917 foreach ($keyVal as $v) {
5918 if (!array_key_exists($v, $current)) {
5919 $current[$v] = array();
5921 $current = &$current[$v];
5923 $current[$lastElement] = $dao->$key;
5926 $values[$key] = $dao->$key;
5933 'gender_id' => 'gender',
5934 'prefix_id' => 'individual_prefix',
5935 'suffix_id' => 'individual_suffix',
5936 'communication_style_id' => 'communication_style',
5937 ) as $realField => $labelField) {
5938 // This is a temporary routine for handling these fields while
5939 // we figure out how to handled them based on metadata in
5940 /// export and search builder. CRM-19815, CRM-19830.
5941 if (isset($dao->$realField) && is_numeric($dao->$realField) && isset($dao->$labelField)) {
5942 $dao->$realField = $dao->$labelField;
5950 * Include pseudo fields LEFT JOIN.
5951 * @param string|array $sort can be a object or string
5953 * @return array|NULL
5955 public function includePseudoFieldsJoin($sort) {
5956 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5959 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5962 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5963 if (!empty($value['table'])) {
5964 $regex = "/({$value['table']}\.|{$name})/";
5965 if (preg_match($regex, $sort)) {
5966 $this->_elemnt
[$value['element']] = 1;
5967 $this->_select
[$value['element']] = $value['select'];
5968 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5969 $present[$value['table']] = $value['join'];
5973 $presentSimpleFrom = $present;
5975 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5976 array_key_exists('civicrm_country', $presentSimpleFrom)
5978 unset($presentSimpleFrom['civicrm_country']);
5980 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5981 array_key_exists('civicrm_country', $present)
5983 unset($present['civicrm_country']);
5986 $presentClause = $presentSimpleFromClause = NULL;
5987 if (!empty($present)) {
5988 $presentClause = implode(' ', $present);
5990 if (!empty($presentSimpleFrom)) {
5991 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5994 $this->_fromClause
= $this->_fromClause
. $presentClause;
5995 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5997 return array($presentClause, $presentSimpleFromClause);
6001 * Build qill for field.
6003 * Qill refers to the query detail visible on the UI.
6005 * @param string $daoName
6006 * @param string $fieldName
6007 * @param mixed $fieldValue
6009 * @param array $pseudoExtraParam
6011 * Type of the field per CRM_Utils_Type
6015 public static function buildQillForFieldValue(
6020 $pseudoExtraParam = array(),
6021 $type = CRM_Utils_Type
::T_STRING
6023 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
6025 //API usually have fieldValue format as array(operator => array(values)),
6026 //so we need to separate operator out of fieldValue param
6027 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
6028 $op = key($fieldValue);
6029 $fieldValue = $fieldValue[$op];
6032 // if Operator chosen is NULL/EMPTY then
6033 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
6034 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), '');
6037 if ($fieldName == 'activity_type_id') {
6038 $pseudoOptions = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
6040 elseif ($fieldName == 'country_id') {
6041 $pseudoOptions = CRM_Core_PseudoConstant
::country();
6043 elseif ($fieldName == 'county_id') {
6044 $pseudoOptions = CRM_Core_PseudoConstant
::county();
6046 elseif ($fieldName == 'world_region') {
6047 $pseudoOptions = CRM_Core_PseudoConstant
::worldRegion();
6049 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
6050 $pseudoOptions = CRM_Event_BAO_Event
::getEvents(0, $fieldValue, TRUE, TRUE, TRUE);
6052 elseif ($fieldName == 'contribution_product_id') {
6053 $pseudoOptions = CRM_Contribute_PseudoConstant
::products();
6055 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
6056 $pseudoOptions = CRM_Core_PseudoConstant
::group();
6058 elseif ($daoName == 'CRM_Batch_BAO_EntityBatch' && $fieldName == 'batch_id') {
6059 $pseudoOptions = CRM_Contribute_PseudoConstant
::batch();
6062 $pseudoOptions = CRM_Core_PseudoConstant
::get($daoName, $fieldName, $pseudoExtraParam);
6065 if (is_array($fieldValue)) {
6066 $qillString = array();
6067 if (!empty($pseudoOptions)) {
6068 foreach ((array) $fieldValue as $val) {
6069 $qillString[] = CRM_Utils_Array
::value($val, $pseudoOptions, $val);
6071 $fieldValue = implode(', ', $qillString);
6074 if ($type == CRM_Utils_Type
::T_DATE
) {
6075 foreach ($fieldValue as $index => $value) {
6076 $fieldValue[$index] = CRM_Utils_Date
::customFormat($value);
6080 // @todo - this is a bit specific (one operator).
6081 // However it is covered by a unit test so can be altered later with
6083 if ($op == 'BETWEEN') {
6084 $separator = ' AND ';
6086 $fieldValue = implode($separator, $fieldValue);
6089 elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) {
6090 $fieldValue = $pseudoOptions[$fieldValue];
6092 elseif ($type === CRM_Utils_Type
::T_DATE
) {
6093 $fieldValue = CRM_Utils_Date
::customFormat($fieldValue);
6096 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), $fieldValue);
6100 * Alter value to reflect wildcard settings.
6102 * The form will have tried to guess whether this is a good field to wildcard but there is
6103 * also a site-wide setting that specifies whether it is OK to append the wild card to the beginning
6104 * or only the end of the string
6106 * @param bool $wildcard
6107 * This is a bool made on an assessment 'elsewhere' on whether this is a good field to wildcard.
6109 * Generally '=' or 'LIKE'.
6110 * @param string $value
6111 * The search string.
6115 public static function getWildCardedValue($wildcard, $op, $value) {
6116 if ($wildcard && $op == 'LIKE') {
6117 if (CRM_Core_Config
::singleton()->includeWildCardInName
&& (substr($value, 0, 1) != '%')) {
6130 * Process special fields of Search Form in OK (Operator in Key) format
6132 * @param array $formValues
6133 * @param array $specialFields
6134 * Special params to be processed
6135 * @param array $changeNames
6136 * Array of fields whose name should be changed
6138 public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = array()) {
6139 // Array of special fields whose value are considered only for NULL or EMPTY operators
6140 $nullableFields = array('contribution_batch_id');
6142 foreach ($specialFields as $element) {
6143 $value = CRM_Utils_Array
::value($element, $formValues);
6145 if (is_array($value)) {
6146 if (in_array($element, array_keys($changeNames))) {
6147 unset($formValues[$element]);
6148 $element = $changeNames[$element];
6150 $formValues[$element] = array('IN' => $value);
6152 elseif (in_array($value, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
6153 $formValues[$element] = array($value => 1);
6155 elseif (!in_array($element, $nullableFields)) {
6156 // if wildcard is already present return searchString as it is OR append and/or prepend with wildcard
6157 $isWilcard = strstr($value, '%') ?
FALSE : CRM_Core_Config
::singleton()->includeWildCardInName
;
6158 $formValues[$element] = array('LIKE' => self
::getWildCardedValue($isWilcard, 'LIKE', $value));
6165 * Parse and assimilate the various sort options.
6167 * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`,
6168 * `email`), the related table may be joined automatically.
6170 * At time of writing, this code is deeply flawed and should be rewritten. For the moment,
6171 * it's been extracted to a standalone function.
6173 * @param string|CRM_Utils_Sort $sort
6174 * The order by string.
6175 * @param bool $sortByChar
6176 * If true returns the distinct array of first characters for search results.
6177 * @param null $sortOrder
6178 * Who knows? Hu knows. He who knows Hu knows who.
6179 * @param string $additionalFromClause
6180 * Should be clause with proper joins, effective to reduce where clause load.
6182 * list(string $orderByClause, string $additionalFromClause).
6184 protected function prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause) {
6186 $orderByArray = array();
6187 $config = CRM_Core_Config
::singleton();
6188 if ($config->includeOrderByClause ||
6189 isset($this->_distinctComponentClause
)
6192 if (is_string($sort)) {
6196 $orderBy = trim($sort->orderBy());
6198 // Deliberately remove the backticks again, as they mess up the evil
6199 // string munging below. This balanced by re-escaping before use.
6200 $orderBy = str_replace('`', '', $orderBy);
6202 if (!empty($orderBy)) {
6203 // this is special case while searching for
6204 // change log CRM-1718
6205 if (preg_match('/sort_name/i', $orderBy)) {
6206 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
6209 $order = " ORDER BY $orderBy";
6212 $order .= " $sortOrder";
6215 // always add contact_a.id to the ORDER clause
6216 // so the order is deterministic
6217 if (strpos('contact_a.id', $order) === FALSE) {
6218 $order .= ", contact_a.id";
6222 elseif ($sortByChar) {
6223 $orderByArray = array("UPPER(LEFT(contact_a.sort_name, 1)) asc");
6226 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
6229 if (!$order && empty($orderByArray)) {
6230 return array($order, $additionalFromClause);
6232 // Remove this here & add it at the end for simplicity.
6233 $order = trim(str_replace('ORDER BY', '', $order));
6235 // hack for order clause
6236 if (!empty($orderByArray)) {
6237 $order = implode(', ', $orderByArray);
6240 $orderByArray = explode(',', $order);
6242 foreach ($orderByArray as $orderByClause) {
6243 $orderByClauseParts = explode(' ', trim($orderByClause));
6244 $field = $orderByClauseParts[0];
6245 $direction = isset($orderByClauseParts[1]) ?
$orderByClauseParts[1] : 'asc';
6250 $this->_tables
["civicrm_address"] = $this->_whereTables
["civicrm_address"] = 1;
6251 $order = str_replace($field, "civicrm_address.{$field}", $order);
6255 case 'state_province':
6256 $this->_tables
["civicrm_{$field}"] = $this->_whereTables
["civicrm_{$field}"] = 1;
6257 if (is_array($this->_returnProperties
) && empty($this->_returnProperties
)) {
6258 $additionalFromClause .= " LEFT JOIN civicrm_{$field} ON civicrm_{$field}.id = civicrm_address.{$field}_id";
6260 $order = str_replace($field, "civicrm_{$field}.name", $order);
6264 $this->_tables
["civicrm_email"] = $this->_whereTables
["civicrm_email"] = 1;
6265 $order = str_replace($field, "civicrm_email.{$field}", $order);
6269 foreach ($this->_pseudoConstantsSelect
as $key => $pseudoConstantMetadata) {
6270 // By replacing the join to the option value table with the mysql construct
6271 // ORDER BY field('contribution_status_id', 2,1,4)
6272 // we can remove a join. In the case of the option value join it is
6273 /// a join known to cause slow queries.
6274 // @todo cover other pseudoconstant types. Limited to option group ones in the
6275 // first instance for scope reasons. They require slightly different handling as the column (label)
6276 // is not declared for them.
6277 // @todo so far only integer fields are being handled. If we add string fields we need to look at
6279 if (isset($pseudoConstantMetadata['pseudoconstant'])
6280 && isset($pseudoConstantMetadata['pseudoconstant']['optionGroupName'])
6281 && $field === CRM_Utils_Array
::value('optionGroupName', $pseudoConstantMetadata['pseudoconstant'])
6283 $sortedOptions = $pseudoConstantMetadata['bao']::buildOptions($pseudoConstantMetadata['pseudoField'], NULL, array(
6284 'orderColumn' => 'label',
6286 $order = str_replace("$field $direction", "field({$pseudoConstantMetadata['pseudoField']}," . implode(',', array_keys($sortedOptions)) . ") $direction", $order);
6288 //CRM-12565 add "`" around $field if it is a pseudo constant
6289 // This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
6290 if (!empty($pseudoConstantMetadata['element']) && $pseudoConstantMetadata['element'] == $field) {
6291 $order = str_replace($field, "`{$field}`", $order);
6297 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6298 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6300 // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
6301 // clause. But this magic helper which forgivingly reescapes ORDER BY.
6302 // Note: $sortByChar implies that $order was hard-coded/trusted, so it can do funky things.
6304 return array(' ORDER BY ' . $order, $additionalFromClause);
6307 $order = CRM_Utils_Type
::escape($order, 'MysqlOrderBy');
6308 return array(' ORDER BY ' . $order, $additionalFromClause);
6313 * Convert a string of group IDs to a string of group labels.
6315 * The original string may include duplicates and groups the user does not have
6316 * permission to see.
6318 * @param CRM_Core_DAO $dao
6319 * @param string $val
6323 public function convertGroupIDStringToLabelString(&$dao, $val) {
6324 $groupIDs = explode(',', $val);
6326 // The pseudoConstant function does not actually cache.
6329 $allGroups = CRM_Core_PseudoConstant
::group();
6331 // Note that groups that the user does not have permission to will be excluded (good).
6332 $groups = array_intersect_key($allGroups, array_flip($groupIDs));
6333 return implode(', ', $groups);
6338 * Set the qill and where properties for a field.
6340 * This function is intended as a short-term function to encourage refactoring
6341 * & re-use - but really we should just have less special-casing.
6343 * @param string $name
6345 * @param string|array $value
6346 * @param string $grouping
6347 * @param string $field
6349 public function setQillAndWhere($name, $op, $value, $grouping, $field) {
6350 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
6351 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
6352 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(
6353 1 => $field['title'],
6360 * Has the pseudoconstant of the field been requested.
6362 * For example if the field is payment_instrument_id then it
6363 * has been requested if either payment_instrument_id or payment_instrument
6364 * have been requested. Payment_instrument is the option groun name field value.
6366 * @param array $field
6370 private function pseudoConstantNameIsInReturnProperties($field) {
6371 if (!isset($field['pseudoconstant']['optionGroupName'])) {
6375 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
6378 if (CRM_Utils_Array
::value($field['name'], $this->_returnProperties
)) {