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_active_period_date_high':
1976 case 'relation_active_period_date_low':
1977 case 'relation_target_name':
1978 case 'relation_status':
1979 case 'relation_date_low':
1980 case 'relation_date_high':
1981 $this->relationship($values);
1982 $this->_relationshipValuesAdded
= TRUE;
1985 case 'task_status_id':
1986 $this->task($values);
1990 // since this case is handled with the above
1993 case 'prox_distance':
1994 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1997 case 'prox_street_address':
1999 case 'prox_postal_code':
2000 case 'prox_state_province_id':
2001 case 'prox_country_id':
2002 // handled by the proximity_distance clause
2006 $this->restWhere($values);
2012 * Given a list of conditions in params generate the required where clause.
2014 * @param string $apiEntity
2018 public function whereClause($apiEntity = NULL) {
2019 $this->_where
[0] = array();
2020 $this->_qill
[0] = array();
2022 $this->includeContactIds();
2023 if (!empty($this->_params
)) {
2024 foreach (array_keys($this->_params
) as $id) {
2025 if (empty($this->_params
[$id][0])) {
2028 // check for both id and contact_id
2029 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
2030 $this->_where
[0][] = self
::buildClause("contact_a.id", $this->_params
[$id][1], $this->_params
[$id][2]);
2033 $this->whereClauseSingle($this->_params
[$id], $apiEntity);
2037 CRM_Core_Component
::alterQuery($this, 'where');
2039 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
2042 if ($this->_customQuery
) {
2043 // Added following if condition to avoid the wrong value display for 'my account' / any UF info.
2044 // Hope it wont affect the other part of civicrm.. if it does please remove it.
2045 if (!empty($this->_customQuery
->_where
)) {
2046 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
2049 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
2053 $andClauses = array();
2056 if (!empty($this->_where
)) {
2057 foreach ($this->_where
as $grouping => $values) {
2058 if ($grouping > 0 && !empty($values)) {
2059 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
2064 if (!empty($this->_where
[0])) {
2065 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
2067 if (!empty($clauses)) {
2068 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
2071 if ($validClauses > 1) {
2072 $this->_useDistinct
= TRUE;
2076 return implode(' AND ', $andClauses);
2080 * Generate where clause for any parameters not already handled.
2082 * @param array $values
2086 public function restWhere(&$values) {
2087 $name = CRM_Utils_Array
::value(0, $values);
2088 $op = CRM_Utils_Array
::value(1, $values);
2089 $value = CRM_Utils_Array
::value(2, $values);
2090 $grouping = CRM_Utils_Array
::value(3, $values);
2091 $wildcard = CRM_Utils_Array
::value(4, $values);
2093 if (isset($grouping) && empty($this->_where
[$grouping])) {
2094 $this->_where
[$grouping] = array();
2097 $multipleFields = array('url');
2099 //check if the location type exists for fields
2101 $locType = explode('-', $name);
2103 if (!in_array($locType[0], $multipleFields)) {
2104 //add phone type if exists
2105 if (isset($locType[2]) && $locType[2]) {
2106 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
2110 $field = CRM_Utils_Array
::value($name, $this->_fields
);
2113 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
2122 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2123 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2124 if (isset($locType[1]) && is_numeric($locType[1])) {
2125 $lType = $locationType[$locType[1]];
2128 $field['title'] .= " ($lType)";
2131 if (substr($name, 0, 14) === 'state_province') {
2132 if (isset($locType[1]) && is_numeric($locType[1])) {
2134 $aName = "{$lType}-address";
2135 $where = "`$aName`.state_province_id";
2138 $where = "civicrm_address.state_province_id";
2141 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value);
2142 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
2143 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
2145 elseif (!empty($field['pseudoconstant'])) {
2146 $this->optionValueQuery(
2147 $name, $op, $value, $grouping,
2148 'CRM_Contact_DAO_Contact',
2154 if ($name == 'gender_id') {
2155 self
::$_openedPanes[ts('Demographics')] = TRUE;
2158 elseif (substr($name, 0, 7) === 'country' ||
substr($name, 0, 6) === 'county') {
2159 $name = (substr($name, 0, 7) === 'country') ?
"country_id" : "county_id";
2160 if (isset($locType[1]) && is_numeric($locType[1])) {
2162 $aName = "{$lType}-address";
2163 $where = "`$aName`.$name";
2166 $where = "civicrm_address.$name";
2169 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2171 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
2172 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
2174 elseif ($name === 'world_region') {
2175 $this->optionValueQuery(
2176 $name, $op, $value, $grouping,
2184 elseif ($name === 'is_deceased') {
2185 $this->setQillAndWhere($name, $op, $value, $grouping, $field);
2186 self
::$_openedPanes[ts('Demographics')] = TRUE;
2188 elseif ($name === 'created_date' ||
$name === 'modified_date' ||
$name === 'deceased_date' ||
$name === 'birth_date') {
2189 $appendDateTime = TRUE;
2190 if ($name === 'deceased_date' ||
$name === 'birth_date') {
2191 $appendDateTime = FALSE;
2192 self
::$_openedPanes[ts('Demographics')] = TRUE;
2194 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2196 elseif ($name === 'contact_id') {
2197 if (is_int($value)) {
2198 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2199 $this->_qill
[$grouping][] = "$field[title] $op $value";
2202 elseif ($name === 'name') {
2203 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2206 $value = self
::getWildCardedValue($wildcard, $op, $value);
2208 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
2209 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2210 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2211 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2213 elseif ($name === 'current_employer') {
2216 $value = self
::getWildCardedValue($wildcard, $op, $value);
2218 $ceWhereClause = self
::buildClause("contact_a.organization_name", $op,
2221 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2222 $this->_where
[$grouping][] = $ceWhereClause;
2223 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2225 elseif ($name === 'email_greeting') {
2226 $filterCondition = array('greeting_type' => 'email_greeting');
2227 $this->optionValueQuery(
2228 $name, $op, $value, $grouping,
2229 CRM_Core_PseudoConstant
::greeting($filterCondition),
2231 ts('Email Greeting')
2234 elseif ($name === 'postal_greeting') {
2235 $filterCondition = array('greeting_type' => 'postal_greeting');
2236 $this->optionValueQuery(
2237 $name, $op, $value, $grouping,
2238 CRM_Core_PseudoConstant
::greeting($filterCondition),
2240 ts('Postal Greeting')
2243 elseif ($name === 'addressee') {
2244 $filterCondition = array('greeting_type' => 'addressee');
2245 $this->optionValueQuery(
2246 $name, $op, $value, $grouping,
2247 CRM_Core_PseudoConstant
::greeting($filterCondition),
2252 elseif (substr($name, 0, 4) === 'url-') {
2253 $tName = 'civicrm_website';
2254 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2255 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2258 $value = self
::getWildCardedValue($wildcard, $op, $value);
2261 $this->_where
[$grouping][] = $d = self
::buildClause('civicrm_website.url', $op, $value);
2262 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2264 elseif ($name === 'contact_is_deleted') {
2265 $this->setQillAndWhere('is_deleted', $op, $value, $grouping, $field);
2267 elseif (!empty($field['where'])) {
2269 if (!empty($field['type'])) {
2270 $type = CRM_Utils_Type
::typeToString($field['type']);
2273 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2275 if (isset($locType[1]) &&
2276 is_numeric($locType[1])
2280 //get the location name
2281 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2282 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
2283 $fieldName = "LOWER(`$tName`.$fldName)";
2285 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2286 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2290 if ($tableName == 'civicrm_contact') {
2291 $fieldName = "contact_a.{$fieldName}";
2294 if ($op != 'IN' && !is_numeric($value) && !is_array($value)) {
2295 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
2296 $fieldName = "LOWER({$field['where']})";
2299 $fieldName = "{$field['where']}";
2304 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2305 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(
2306 1 => $field['title'],
2308 3 => (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) ?
$qillVal : "'$qillVal'"));
2310 if (is_array($value)) {
2311 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2312 // for api style operators for functions that hit this point without worrying about regression
2313 // (the previous comments indicated the condition for hitting this point were unknown
2314 // per CRM-14743 we are adding modified_date & created_date operator support
2315 $operations = array_keys($value);
2316 foreach ($operations as $operator) {
2317 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2318 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2319 //so this condition will satisfy the search for now
2320 if (strpos($op, 'IN') !== FALSE) {
2321 $value = array($op => $value);
2323 // we don't know when this might happen
2325 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $operator)));
2329 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($fieldName, $value, $type);
2332 if (!strpos($op, 'IN')) {
2333 $value = $strtolower($value);
2337 $value = self
::getWildCardedValue($wildcard, $op, $value);
2340 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2344 if ($setTables && isset($field['where'])) {
2345 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2346 if (isset($tableName)) {
2347 $this->_tables
[$tableName] = 1;
2348 $this->_whereTables
[$tableName] = 1;
2360 public static function getLocationTableName(&$where, &$locType) {
2361 if (isset($locType[1]) && is_numeric($locType[1])) {
2362 list($tbName, $fldName) = explode(".", $where);
2364 //get the location name
2365 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2366 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2367 if (in_array($locType[0], $specialFields)) {
2368 //hack to fix / special handing for phone_ext
2369 if ($locType[0] == 'phone_ext') {
2370 $locType[0] = 'phone';
2372 if (isset($locType[2]) && $locType[2]) {
2373 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2376 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2379 elseif (in_array($locType[0],
2384 'street_number_suffix',
2386 'supplemental_address_1',
2387 'supplemental_address_2',
2388 'supplemental_address_3',
2391 'postal_code_suffix',
2397 //fix for search by profile with address fields.
2398 $tName = "{$locationType[$locType[1]]}-address";
2400 elseif (in_array($locType[0],
2408 $tName = "{$locationType[$locType[1]]}-email";
2410 elseif ($locType[0] == 'provider_id') {
2411 $tName = "{$locationType[$locType[1]]}-im";
2413 elseif ($locType[0] == 'openid') {
2414 $tName = "{$locationType[$locType[1]]}-openid";
2417 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2419 $tName = str_replace(' ', '_', $tName);
2420 return array($tName, $fldName);
2422 CRM_Core_Error
::fatal();
2426 * Given a result dao, extract the values and return that array
2428 * @param CRM_Core_DAO $dao
2431 * values for this query
2433 public function store($dao) {
2436 foreach ($this->_element
as $key => $dontCare) {
2437 if (property_exists($dao, $key)) {
2438 if (strpos($key, '-') !== FALSE) {
2439 $values = explode('-', $key);
2440 $lastElement = array_pop($values);
2442 $cnt = count($values);
2444 foreach ($values as $v) {
2445 if (!array_key_exists($v, $current)) {
2446 $current[$v] = array();
2448 //bad hack for im_provider
2449 if ($lastElement == 'provider_id') {
2450 if ($count < $cnt) {
2451 $current = &$current[$v];
2454 $lastElement = "{$v}_{$lastElement}";
2458 $current = &$current[$v];
2463 $current[$lastElement] = $dao->$key;
2466 $value[$key] = $dao->$key;
2474 * Getter for tables array.
2478 public function tables() {
2479 return $this->_tables
;
2483 * Sometimes used to create the from clause, but, not reliably, set
2484 * this AND set tables.
2486 * It's unclear the intent - there is a 'simpleFrom' clause which
2487 * takes whereTables into account & a fromClause which doesn't.
2489 * logic may have eroded?
2493 public function whereTables() {
2494 return $this->_whereTables
;
2498 * Generate the where clause (used in match contacts and permissions)
2500 * @param array $params
2501 * @param array $fields
2502 * @param array $tables
2503 * @param $whereTables
2504 * @param bool $strict
2508 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2509 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2513 $tables = array_merge($query->tables(), $tables);
2514 $whereTables = array_merge($query->whereTables(), $whereTables);
2516 return $query->_whereClause
;
2520 * Create the from clause.
2522 * @param array $tables
2523 * Tables that need to be included in this from clause. If null,
2524 * return mimimal from clause (i.e. civicrm_contact).
2525 * @param array $inner
2526 * Tables that should be inner-joined.
2527 * @param array $right
2528 * Tables that should be right-joined.
2529 * @param bool $primaryLocation
2530 * Search on primary location. See note below.
2532 * Determines search mode based on bitwise MODE_* constants.
2533 * @param string|NULL $apiEntity
2534 * Determines search mode based on entity by string.
2536 * The $primaryLocation flag only seems to be used when
2537 * locationType() has been called. This may be a search option
2538 * exposed, or perhaps it's a "search all details" approach which
2539 * predates decoupling of location types and primary fields?
2541 * @see https://issues.civicrm.org/jira/browse/CRM-19967
2546 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1, $apiEntity = NULL) {
2548 $from = ' FROM civicrm_contact contact_a';
2549 if (empty($tables)) {
2553 if (!empty($tables['civicrm_worldregion'])) {
2554 $tables = array_merge(array('civicrm_country' => 1), $tables);
2557 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2558 CRM_Utils_Array
::value('civicrm_county', $tables)
2559 ) && empty($tables['civicrm_address'])
2561 $tables = array_merge(array('civicrm_address' => 1),
2566 // add group_contact and group table is subscription history is present
2567 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2568 $tables = array_merge(array(
2569 'civicrm_group' => 1,
2570 'civicrm_group_contact' => 1,
2576 // to handle table dependencies of components
2577 CRM_Core_Component
::tableNames($tables);
2578 // to handle table dependencies of hook injected tables
2579 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2581 //format the table list according to the weight
2582 $info = CRM_Core_TableHierarchy
::info();
2584 foreach ($tables as $key => $value) {
2586 if (strpos($key, '-') !== FALSE) {
2587 $keyArray = explode('-', $key);
2588 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2590 elseif (strpos($key, '_') !== FALSE) {
2591 $keyArray = explode('_', $key);
2592 if (is_numeric(array_pop($keyArray))) {
2593 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2596 $k = CRM_Utils_Array
::value($key, $info, 99);
2600 $k = CRM_Utils_Array
::value($key, $info, 99);
2602 $tempTable[$k . ".$key"] = $key;
2605 $newTables = array();
2606 foreach ($tempTable as $key) {
2607 $newTables[$key] = $tables[$key];
2610 $tables = $newTables;
2612 foreach ($tables as $name => $value) {
2617 if (!empty($inner[$name])) {
2620 elseif (!empty($right[$name])) {
2628 // if there is already a join statement in value, use value itself
2629 if (strpos($value, 'JOIN')) {
2630 $from .= " $value ";
2633 $from .= " $side JOIN $name ON ( $value ) ";
2637 $searchPrimary = '';
2638 if (Civi
::settings()->get('searchPrimaryDetailsOnly') ||
$apiEntity) {
2639 $searchPrimary = "AND {$name}.is_primary = 1";
2642 case 'civicrm_address':
2643 //CRM-14263 further handling of address joins further down...
2644 if (!$primaryLocation) {
2645 $searchPrimary = '';
2647 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id {$searchPrimary} )";
2650 case 'civicrm_phone':
2651 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id {$searchPrimary}) ";
2654 case 'civicrm_email':
2655 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id {$searchPrimary})";
2659 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id {$searchPrimary}) ";
2663 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2664 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2665 $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)";
2668 case 'civicrm_openid':
2669 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id {$searchPrimary} )";
2672 case 'civicrm_worldregion':
2673 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2674 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2677 case 'civicrm_location_type':
2678 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2681 case 'civicrm_group':
2682 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2685 case 'civicrm_group_contact':
2686 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2689 case 'civicrm_group_contact_cache':
2690 $from .= " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
2693 case 'civicrm_activity':
2694 case 'civicrm_activity_tag':
2695 case 'activity_type':
2696 case 'activity_status':
2698 case 'civicrm_activity_contact':
2699 case 'source_contact':
2700 case 'activity_priority':
2701 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2704 case 'civicrm_entity_tag':
2705 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2706 civicrm_entity_tag.entity_id = contact_a.id ) ";
2709 case 'civicrm_note':
2710 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2711 contact_a.id = civicrm_note.entity_id ) ";
2714 case 'civicrm_subscription_history':
2715 $from .= " $side JOIN civicrm_subscription_history
2716 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2717 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2720 case 'civicrm_relationship':
2721 if (self
::$_relType == 'reciprocal') {
2722 if (self
::$_relationshipTempTable) {
2723 // we have a temptable to join on
2724 $tbl = self
::$_relationshipTempTable;
2725 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2728 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2729 $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)";
2732 elseif (self
::$_relType == 'b') {
2733 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2734 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2737 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2738 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2743 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2744 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2748 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2751 case 'civicrm_grant':
2752 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2755 case 'civicrm_website':
2756 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2760 $locationTypeName = '';
2761 if (strpos($name, '-address') != 0) {
2762 $locationTypeName = 'address';
2764 elseif (strpos($name, '-phone') != 0) {
2765 $locationTypeName = 'phone';
2767 elseif (strpos($name, '-email') != 0) {
2768 $locationTypeName = 'email';
2770 elseif (strpos($name, '-im') != 0) {
2771 $locationTypeName = 'im';
2773 elseif (strpos($name, '-openid') != 0) {
2774 $locationTypeName = 'openid';
2777 if ($locationTypeName) {
2778 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2779 $parts = explode('-', $name);
2780 $locationID = array_search($parts[0], CRM_Core_BAO_Address
::buildOptions('location_type_id', 'get', array('name' => $parts[0])));
2781 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2784 $from .= CRM_Core_Component
::from($name, $mode, $side);
2786 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2795 * WHERE / QILL clause for deleted_contacts
2797 * @param array $values
2799 public function deletedContacts($values) {
2800 list($_, $_, $value, $grouping, $_) = $values;
2802 // *prepend* to the relevant grouping as this is quite an important factor
2803 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2808 * Where / qill clause for contact_type
2812 public function contactType(&$values) {
2813 list($name, $op, $value, $grouping, $wildcard) = $values;
2815 $subTypes = array();
2818 // account for search builder mapping multiple values
2819 if (!is_array($value)) {
2820 $values = self
::parseSearchBuilderString($value, 'String');
2821 if (is_array($values)) {
2822 $value = array_flip($values);
2826 if (is_array($value)) {
2827 foreach ($value as $k => $v) {
2832 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2833 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2836 if (!empty($subType)) {
2837 $subTypes[$subType] = 1;
2839 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2844 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2845 $contactType = $contactTypeANDSubType[0];
2846 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2847 if (!empty($subType)) {
2848 $subTypes[$subType] = 1;
2850 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2854 if (!empty($clause)) {
2856 if ($op == 'IN' ||
$op == 'NOT IN') {
2857 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2860 $type = array_pop($clause);
2861 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2864 $this->_qill
[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2866 if (!empty($subTypes)) {
2867 $this->includeContactSubTypes($subTypes, $grouping);
2873 * Where / qill clause for contact_sub_type.
2875 * @param array $values
2877 public function contactSubType(&$values) {
2878 list($name, $op, $value, $grouping, $wildcard) = $values;
2879 $this->includeContactSubTypes($value, $grouping, $op);
2887 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2889 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2891 $value = $value[$op];
2895 $alias = "contact_a.contact_sub_type";
2896 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
2898 $op = str_replace('IN', 'LIKE', $op);
2899 $op = str_replace('=', 'LIKE', $op);
2900 $op = str_replace('!', 'NOT ', $op);
2902 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2903 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
2905 elseif (is_array($value)) {
2906 foreach ($value as $k => $v) {
2907 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($v, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2911 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2914 if (!empty($clause)) {
2915 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2917 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', array(1 => $qillOperators[$op])) . implode(' ' . ts('or') . ' ', array_keys($clause));
2921 * Where / qill clause for groups.
2925 public function group($values) {
2926 list($name, $op, $value, $grouping, $wildcard) = $values;
2928 // If the $value is in OK (operator as key) array format we need to extract the key as operator and value first
2929 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2931 $value = $value[$op];
2934 // Replace pseudo operators from search builder
2935 $op = str_replace('EMPTY', 'NULL', $op);
2937 if (strpos($op, 'NULL')) {
2941 if (count($value) > 1) {
2942 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
2943 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $op)));
2945 $this->_useDistinct
= TRUE;
2948 if (isset($value)) {
2949 $value = CRM_Utils_Array
::value($op, $value, $value);
2952 if ($name == 'group_type') {
2953 $value = array_keys($this->getGroupsFromTypeCriteria($value));
2956 $regularGroupIDs = $smartGroupIDs = array();
2957 foreach ((array) $value as $id) {
2958 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
2959 $smartGroupIDs[] = $id;
2962 $regularGroupIDs[] = $id;
2966 $isNotOp = ($op == 'NOT IN' ||
$op == '!=');
2969 $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
2971 is_array($gcsValues[2])
2973 foreach ($gcsValues[2] as $k => $v) {
2975 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2980 $statii[] = "'Added'";
2982 $groupClause = array();
2983 if (count($regularGroupIDs) ||
empty($value)) {
2984 // include child groups IDs if any
2985 $childGroupIds = (array) CRM_Contact_BAO_Group
::getChildGroupIds($regularGroupIDs);
2986 foreach ($childGroupIds as $key => $id) {
2987 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
2988 $smartGroupIDs[] = $id;
2989 unset($childGroupIds[$key]);
2992 if (count($childGroupIds)) {
2993 $regularGroupIDs = array_merge($regularGroupIDs, $childGroupIds);
2996 // if $regularGroupIDs is populated with regular child group IDs
2997 // then change the mysql operator to desired
2998 if (count($regularGroupIDs) > 1) {
2999 $op = strpos($op, 'IN') ?
$op : ($op == '!=') ?
'NOT IN' : 'IN';
3001 $groupIds = implode(',', (array) $regularGroupIDs);
3002 $gcTable = "`civicrm_group_contact-{$groupIds}`";
3003 $joinClause = array("contact_a.id = {$gcTable}.contact_id");
3005 if (strpos($op, 'IN') !== FALSE) {
3006 $clause = "{$gcTable}.group_id $op ( $groupIds ) ";
3008 elseif ($op == '!=') {
3009 $clause = "{$gcTable}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact cgc WHERE cgc.group_id = $groupIds )";
3012 $clause = "{$gcTable}.group_id $op $groupIds ";
3014 $groupClause[] = "( {$clause} )";
3017 $joinClause[] = "{$gcTable}.status IN (" . implode(', ', $statii) . ")";
3019 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3022 //CRM-19589: contact(s) removed from a Smart Group, resides in civicrm_group_contact table
3023 if (count($smartGroupIDs)) {
3024 $groupClause[] = " ( " . $this->addGroupContactCache($smartGroupIDs, NULL, "contact_a", $op) . " ) ";
3027 $and = ($op == 'IS NULL') ?
' AND ' : ' OR ';
3028 $this->_where
[$grouping][] = ' ( ' . implode($and, $groupClause) . ' ) ';
3030 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
3031 $this->_qill
[$grouping][] = ts("Group(s) %1 %2", array(1 => $qillop, 2 => $qillVal));
3032 if (strpos($op, 'NULL') === FALSE) {
3033 $this->_qill
[$grouping][] = ts("Group Status %1", array(1 => implode(' ' . ts('or') . ' ', $statii)));
3038 * Function translates selection of group type into a list of groups.
3043 public function getGroupsFromTypeCriteria($value) {
3044 $groupIds = array();
3045 foreach ((array) $value as $groupTypeValue) {
3046 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
3047 $groupIds = ($groupIds +
$groupList);
3053 * @param array $groups
3054 * @param string $tableAlias
3055 * @param string $joinTable
3058 * @return null|string
3060 public function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a", $op) {
3061 $isNullOp = (strpos($op, 'NULL') !== FALSE);
3062 $groupsIds = $groups;
3063 if (!$isNullOp && !$groups) {
3066 elseif (strpos($op, 'IN') !== FALSE) {
3067 $groups = array($op => $groups);
3069 elseif (is_array($groups) && count($groups)) {
3070 $groups = array('IN' => $groups);
3073 // Find all the groups that are part of a saved search.
3074 $smartGroupClause = self
::buildClause("id", $op, $groups, 'Int');
3076 SELECT id, cache_date, saved_search_id, children
3078 WHERE $smartGroupClause
3079 AND ( saved_search_id != 0
3080 OR saved_search_id IS NOT NULL
3081 OR children IS NOT NULL )
3084 $group = CRM_Core_DAO
::executeQuery($sql);
3086 while ($group->fetch()) {
3087 $this->_useDistinct
= TRUE;
3088 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
3089 CRM_Contact_BAO_GroupContactCache
::load($group);
3092 if ($group->N
== 0) {
3097 $tableAlias = "`civicrm_group_contact_cache_";
3098 $tableAlias .= ($isNullOp) ?
"a`" : implode(',', (array) $groupsIds) . "`";
3101 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.id = {$tableAlias}.contact_id ";
3102 return self
::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
3106 * Where / qill clause for cms users
3110 public function ufUser(&$values) {
3111 list($name, $op, $value, $grouping, $wildcard) = $values;
3114 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3116 $this->_qill
[$grouping][] = ts('CMS User');
3118 elseif ($value == 0) {
3119 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3121 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3122 $this->_qill
[$grouping][] = ts('Not a CMS User');
3127 * All tag search specific.
3129 * @param array $values
3131 public function tagSearch(&$values) {
3132 list($name, $op, $value, $grouping, $wildcard) = $values;
3135 $value = "%{$value}%";
3137 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3138 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3140 $etTable = "`civicrm_entity_tag-" . $value . "`";
3141 $tTable = "`civicrm_tag-" . $value . "`";
3143 if ($useAllTagTypes[2]) {
3144 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3145 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3146 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3148 // search tag in cases
3149 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3150 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
3151 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3152 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3153 LEFT JOIN civicrm_case
3154 ON (civicrm_case_contact.case_id = civicrm_case.id
3155 AND civicrm_case.is_deleted = 0 )
3156 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3157 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3158 // search tag in activities
3159 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3160 $tActTable = "`civicrm_act_tag-" . $value . "`";
3161 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3162 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3164 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3165 = " LEFT JOIN civicrm_activity_contact
3166 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3167 LEFT JOIN civicrm_activity
3168 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3169 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3170 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3171 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3173 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $value . "' OR {$tCaseTable}.name $op '" . $value . "' OR {$tActTable}.name $op '" . $value . "')";
3174 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
3177 $etTable = "`civicrm_entity_tag-" . $value . "`";
3178 $tTable = "`civicrm_tag-" . $value . "`";
3179 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3180 {$etTable}.entity_table = 'civicrm_contact' )
3181 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3183 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3184 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
3189 * Where / qill clause for tag.
3191 * @param array $values
3193 public function tag(&$values) {
3194 list($name, $op, $value, $grouping, $wildcard) = $values;
3196 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, array('onlyActive' => FALSE));
3197 // API/Search Builder format array(operator => array(values))
3198 if (is_array($value)) {
3199 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3201 $value = $value[$op];
3203 if (count($value) > 1) {
3204 $this->_useDistinct
= TRUE;
3206 $value = implode(',', (array) $value);
3209 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3210 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3212 $etTable = "`civicrm_entity_tag-" . $value . "`";
3214 if ($useAllTagTypes[2]) {
3215 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3216 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3218 // search tag in cases
3219 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3220 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3221 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3223 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3224 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3225 LEFT JOIN civicrm_case
3226 ON (civicrm_case_contact.case_id = civicrm_case.id
3227 AND civicrm_case.is_deleted = 0 )
3228 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3229 // search tag in activities
3230 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3231 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3232 = " LEFT JOIN civicrm_activity_contact
3233 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3234 LEFT JOIN civicrm_activity
3235 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3236 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3237 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3240 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3241 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3244 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3248 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3249 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3252 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3253 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3254 $op = str_replace('EMPTY', 'NULL', $op);
3255 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3257 // CRM-16941: for tag tried with != operator we don't show contact who don't have given $value AND also in other tag
3258 elseif ($op == '!=') {
3259 $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') . ")";
3261 elseif ($op == '=' ||
strstr($op, 'IN')) {
3262 $op = ($op == '=') ?
'IN' : $op;
3263 $this->_where
[$grouping][] = "{$etTable}.tag_id $op ( $value )";
3266 $this->_qill
[$grouping][] = ts('Tagged %1 %2', array(1 => $qillop, 2 => $qillVal));
3270 * Where/qill clause for notes
3272 * @param array $values
3274 public function notes(&$values) {
3275 list($name, $op, $value, $grouping, $wildcard) = $values;
3277 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3278 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3279 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3281 $this->_useDistinct
= TRUE;
3283 $this->_tables
['civicrm_note'] = $this->_whereTables
['civicrm_note']
3284 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3286 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3288 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3290 if (strpos($value, '%') === FALSE) {
3291 $value = "%$value%";
3295 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3301 if ($noteOption %
2 == 0) {
3302 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3303 $label = ts('Note: Body Only');
3305 if ($noteOption %
3 == 0) {
3306 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3307 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3309 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3310 list($qillOp, $qillVal) = self
::buildQillForFieldValue(NULL, $name, $n, $op);
3311 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillOp, 3 => $qillVal));
3315 * @param string $name
3321 public function nameNullOrEmptyOp($name, $op, $grouping) {
3325 $this->_where
[$grouping][] = "contact_a.$name $op";
3326 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3330 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3331 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3334 case 'IS NOT EMPTY':
3335 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3336 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3345 * Where / qill clause for sort_name
3347 * @param array $values
3349 public function sortName(&$values) {
3350 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3352 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3353 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3357 $input = $value = trim($value);
3359 if (!strlen($value)) {
3363 $config = CRM_Core_Config
::singleton();
3367 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3370 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3372 $firstChar = substr($value, 0, 1);
3373 $lastChar = substr($value, -1, 1);
3374 $quotes = array("'", '"');
3375 // If string is quoted, strip quotes and otherwise don't alter it
3376 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3377 $value = trim($value, implode('', $quotes));
3379 // Replace spaces with wildcards for a LIKE operation
3380 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3381 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3382 $value = str_replace(' ', '%', $value);
3384 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($value)));
3385 if (strlen($value)) {
3386 $fieldsub = array();
3387 $value = "'" . self
::getWildCardedValue($wildcard, $op, $value) . "'";
3388 if ($fieldName == 'sort_name') {
3389 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3390 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3393 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3394 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3396 $fieldsub[] = " ( $wc $op $value )";
3397 if ($config->includeNickNameInName
) {
3398 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3399 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3400 $fieldsub[] = " ( $wc $op $value )";
3402 if ($config->includeEmailInName
) {
3403 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3405 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3408 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3410 $this->_where
[$grouping][] = $sub;
3411 if ($config->includeEmailInName
) {
3412 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3413 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3416 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3421 * Where/qill clause for greeting fields.
3423 * @param array $values
3425 public function greetings(&$values) {
3426 list($name, $op, $value, $grouping, $wildcard) = $values;
3427 $name .= '_display';
3429 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
3430 $this->_qill
[$grouping][] = ts('Greeting %1 %2', array(1 => $qillop, 2 => $qillVal));
3431 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value, 'String');
3435 * Where / qill clause for email
3437 * @param array $values
3438 * @param string $apiEntity
3440 protected function email(&$values, $apiEntity) {
3441 list($name, $op, $value, $grouping, $wildcard) = $values;
3442 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3444 // CRM-18147: for Contact's GET API, email fieldname got appended with its entity as in {$apiEntiy}_{$name}
3445 // so following code is use build whereClause for contact's primart email id
3446 if (!empty($apiEntity)) {
3447 $dataType = 'String';
3448 if ($name == 'email_id') {
3449 $dataType = 'Integer';
3453 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.is_primary', '=', 1, 'Integer');
3454 $this->_where
[$grouping][] = self
::buildClause("civicrm_email.$name", $op, $value, $dataType);
3458 $n = strtolower(trim($value));
3460 if (substr($n, 0, 1) == '"' &&
3461 substr($n, -1, 1) == '"'
3463 $n = substr($n, 1, -1);
3464 $value = CRM_Core_DAO
::escapeString($n);
3468 $value = self
::getWildCardedValue($wildcard, $op, $n);
3470 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3471 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3474 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3475 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3480 * Where / qill clause for phone number
3482 * @param array $values
3484 public function phone_numeric(&$values) {
3485 list($name, $op, $value, $grouping, $wildcard) = $values;
3486 // Strip non-numeric characters; allow wildcards
3487 $number = preg_replace('/[^\d%]/', '', $value);
3489 if (strpos($number, '%') === FALSE) {
3490 $number = "%$number%";
3493 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3494 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3495 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3500 * Where / qill clause for phone type/location
3502 * @param array $values
3504 public function phone_option_group($values) {
3505 list($name, $op, $value, $grouping, $wildcard) = $values;
3506 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3507 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3508 $optionName = $options[$value];
3509 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3510 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3511 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3515 * Where / qill clause for street_address.
3517 * @param array $values
3519 public function street_address(&$values) {
3520 list($name, $op, $value, $grouping, $wildcard) = $values;
3529 $value = strtolower($n);
3530 if (strpos($value, '%') === FALSE) {
3531 // only add wild card if not there
3532 $value = "%{$value}%";
3535 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3536 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3537 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3540 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3541 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3544 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3548 * Where / qill clause for street_unit.
3550 * @param array $values
3552 public function street_number(&$values) {
3553 list($name, $op, $value, $grouping, $wildcard) = $values;
3561 if (strtolower($n) == 'odd') {
3562 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3563 $this->_qill
[$grouping][] = ts('Street Number is odd');
3565 elseif (strtolower($n) == 'even') {
3566 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3567 $this->_qill
[$grouping][] = ts('Street Number is even');
3570 $value = strtolower($n);
3572 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3573 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3574 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3577 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3581 * Where / qill clause for sorting by character.
3583 * @param array $values
3585 public function sortByCharacter(&$values) {
3586 list($name, $op, $value, $grouping, $wildcard) = $values;
3588 $name = trim($value);
3589 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3590 $this->_where
[$grouping][] = $cond;
3591 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3595 * Where / qill clause for including contact ids.
3597 public function includeContactIDs() {
3598 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3602 $contactIds = array();
3603 foreach ($this->_params
as $id => $values) {
3604 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3605 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3608 CRM_Utils_Type
::validateAll($contactIds, 'Positive');
3609 if (!empty($contactIds)) {
3610 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3615 * Where / qill clause for postal code.
3617 * @param array $values
3619 public function postalCode(&$values) {
3620 // skip if the fields dont have anything to do with postal_code
3621 if (empty($this->_fields
['postal_code'])) {
3625 list($name, $op, $value, $grouping, $wildcard) = $values;
3627 // Handle numeric postal code range searches properly by casting the column as numeric
3628 if (is_numeric($value)) {
3629 $field = "IF (civicrm_address.postal_code REGEXP '^[0-9]+$', CAST(civicrm_address.postal_code AS UNSIGNED), 0)";
3630 $val = CRM_Utils_Type
::escape($value, 'Integer');
3633 $field = 'civicrm_address.postal_code';
3634 // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string.
3635 if (!is_array($value)) {
3636 $val = CRM_Utils_Type
::escape($value, 'String');
3639 // Do we need to escape values here? I would expect buildClause does.
3644 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3646 if ($name == 'postal_code') {
3647 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3648 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3650 elseif ($name == 'postal_code_low') {
3651 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3652 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3654 elseif ($name == 'postal_code_high') {
3655 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3656 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3661 * Where / qill clause for location type.
3663 * @param array $values
3664 * @param null $status
3668 public function locationType(&$values, $status = NULL) {
3669 list($name, $op, $value, $grouping, $wildcard) = $values;
3671 if (is_array($value)) {
3672 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3673 $this->_tables
['civicrm_address'] = 1;
3674 $this->_whereTables
['civicrm_address'] = 1;
3676 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3678 foreach ($value as $id) {
3679 $names[] = $locationType[$id];
3682 $this->_primaryLocation
= FALSE;
3685 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3688 return implode(' ' . ts('or') . ' ', $names);
3695 * @param bool $fromStateProvince
3697 * @return array|NULL
3699 public function country(&$values, $fromStateProvince = TRUE) {
3700 list($name, $op, $value, $grouping, $wildcard) = $values;
3702 if (!$fromStateProvince) {
3703 $stateValues = $this->getWhereValues('state_province', $grouping);
3704 if (!empty($stateValues)) {
3705 // return back to caller if there are state province values
3706 // since that handles this case
3711 $countryClause = $countryQill = NULL;
3712 if ($values && !empty($value)) {
3713 $this->_tables
['civicrm_address'] = 1;
3714 $this->_whereTables
['civicrm_address'] = 1;
3716 $countryClause = self
::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
3717 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, 'country_id', $value, $op);
3718 $countryQill = ts("%1 %2 %3", array(1 => 'Country', 2 => $qillop, 3 => $qillVal));
3720 if (!$fromStateProvince) {
3721 $this->_where
[$grouping][] = $countryClause;
3722 $this->_qill
[$grouping][] = $countryQill;
3726 if ($fromStateProvince) {
3727 if (!empty($countryClause)) {
3730 " ...AND... " . $countryQill,
3734 return array(NULL, NULL);
3740 * Where / qill clause for county (if present).
3742 * @param array $values
3743 * @param null $status
3747 public function county(&$values, $status = NULL) {
3748 list($name, $op, $value, $grouping, $wildcard) = $values;
3750 if (!is_array($value)) {
3751 // force the county to be an array
3752 $value = array($value);
3755 // check if the values are ids OR names of the counties
3756 $inputFormat = 'id';
3757 foreach ($value as $v) {
3758 if (!is_numeric($v)) {
3759 $inputFormat = 'name';
3767 elseif ($op == '!=') {
3771 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3772 $op = str_replace('EMPTY', 'NULL', $op);
3775 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3776 $clause = "civicrm_address.county_id $op";
3778 elseif ($inputFormat == 'id') {
3779 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3781 $county = CRM_Core_PseudoConstant
::county();
3782 foreach ($value as $id) {
3783 $names[] = CRM_Utils_Array
::value($id, $county);
3787 $inputClause = array();
3788 $county = CRM_Core_PseudoConstant
::county();
3789 foreach ($value as $name) {
3790 $name = trim($name);
3791 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3793 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3796 $this->_tables
['civicrm_address'] = 1;
3797 $this->_whereTables
['civicrm_address'] = 1;
3799 $this->_where
[$grouping][] = $clause;
3801 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3804 return implode(' ' . ts('or') . ' ', $names);
3809 * Where / qill clause for state/province AND country (if present).
3811 * @param array $values
3812 * @param null $status
3816 public function stateProvince(&$values, $status = NULL) {
3817 list($name, $op, $value, $grouping, $wildcard) = $values;
3819 $stateClause = self
::buildClause('civicrm_address.state_province_id', $op, $value, 'Positive');
3820 $this->_tables
['civicrm_address'] = 1;
3821 $this->_whereTables
['civicrm_address'] = 1;
3823 $countryValues = $this->getWhereValues('country', $grouping);
3824 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3825 if ($countryClause) {
3826 $clause = "( $stateClause AND $countryClause )";
3829 $clause = $stateClause;
3832 $this->_where
[$grouping][] = $clause;
3833 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
3835 $this->_qill
[$grouping][] = ts("State/Province %1 %2 %3", array(1 => $qillop, 2 => $qillVal, 3 => $countryQill));
3838 return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill;
3843 * Where / qill clause for change log.
3845 * @param array $values
3847 public function changeLog(&$values) {
3848 list($name, $op, $value, $grouping, $wildcard) = $values;
3850 $targetName = $this->getWhereValues('changed_by', $grouping);
3855 $name = trim($targetName[2]);
3856 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3857 $name = $targetName[4] ?
"%$name%" : $name;
3858 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3859 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3860 $this->_qill
[$grouping][] = ts('Modified By') . " $name";
3866 public function modifiedDates($values) {
3867 $this->_useDistinct
= TRUE;
3869 // CRM-11281, default to added date if not set
3870 $fieldTitle = ts('Added Date');
3871 $fieldName = 'created_date';
3872 foreach (array_keys($this->_params
) as $id) {
3873 if ($this->_params
[$id][0] == 'log_date') {
3874 if ($this->_params
[$id][2] == 2) {
3875 $fieldTitle = ts('Modified Date');
3876 $fieldName = 'modified_date';
3881 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3883 self
::$_openedPanes[ts('Change Log')] = TRUE;
3889 public function demographics(&$values) {
3890 list($name, $op, $value, $grouping, $wildcard) = $values;
3892 if (($name == 'age_low') ||
($name == 'age_high')) {
3893 $this->ageRangeQueryBuilder($values,
3894 'contact_a', 'age', 'birth_date', ts('Age')
3897 elseif (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3899 $this->dateQueryBuilder($values,
3900 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3903 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3905 $this->dateQueryBuilder($values,
3906 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3910 self
::$_openedPanes[ts('Demographics')] = TRUE;
3916 public function privacy(&$values) {
3917 list($name, $op, $value, $grouping, $wildcard) = $values;
3918 //fixed for profile search listing CRM-4633
3919 if (strpbrk($value, "[")) {
3920 $value = "'{$value}'";
3922 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3925 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3927 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3928 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
3929 $title = $field ?
$field['title'] : $name;
3930 $this->_qill
[$grouping][] = "$title $op $value";
3936 public function privacyOptions($values) {
3937 list($name, $op, $value, $grouping, $wildcard) = $values;
3939 if (empty($value) ||
!is_array($value)) {
3943 // get the operator and toggle values
3944 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3947 strtolower($opValues[2] == 'AND')
3952 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3954 if ($toggleValues &&
3955 $toggleValues[2] == 2
3962 foreach ($value as $dontCare => $pOption) {
3963 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
3964 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3965 $title = $field ?
$field['title'] : $pOption;
3966 $qill[] = " $title = 1 ";
3969 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
3970 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
3976 public function preferredCommunication(&$values) {
3977 list($name, $op, $value, $grouping, $wildcard) = $values;
3979 if (!is_array($value)) {
3980 $value = str_replace(array('(', ')'), '', explode(",", $value));
3982 elseif (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3984 $value = $value[$op];
3986 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Contact', $name, $value, $op);
3988 if (self
::caseImportant($op)) {
3989 $value = implode("[[:cntrl:]]|[[:cntrl:]]", (array) $value);
3990 $op = (strstr($op, '!') ||
strstr($op, 'NOT')) ?
'NOT RLIKE' : 'RLIKE';
3991 $value = "[[:cntrl:]]" . $value . "[[:cntrl:]]";
3994 $this->_where
[$grouping][] = self
::buildClause("contact_a.preferred_communication_method", $op, $value);
3995 $this->_qill
[$grouping][] = ts('Preferred Communication Method %1 %2', array(1 => $qillop, 2 => $qillVal));
3999 * Where / qill clause for relationship.
4001 * @param array $values
4003 public function relationship(&$values) {
4004 list($name, $op, $value, $grouping, $wildcard) = $values;
4005 if ($this->_relationshipValuesAdded
) {
4008 // also get values array for relation_target_name
4009 // for relationship search we always do wildcard
4010 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4011 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4012 $relStatus = $this->getWhereValues('relation_status', $grouping);
4013 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4014 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4016 $nameClause = $name = NULL;
4018 $name = trim($targetName[2]);
4019 if (substr($name, 0, 1) == '"' &&
4020 substr($name, -1, 1) == '"'
4022 $name = substr($name, 1, -1);
4023 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4024 $nameClause = "= '$name'";
4027 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4028 $nameClause = "LIKE '%{$name}%'";
4032 $rTypeValues = array();
4033 if (!empty($relationType)) {
4034 $rel = explode('_', $relationType[2]);
4035 self
::$_relType = $rel[1];
4036 $params = array('id' => $rel[0]);
4037 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
4039 if (!empty($rTypeValues) && $rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
4040 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4041 //@todo unless we are dealing with a target group
4042 self
::$_relType = 'reciprocal';
4044 // if we are creating a temp table we build our own where for the relationship table
4045 $relationshipTempTable = NULL;
4046 if (self
::$_relType == 'reciprocal' && empty($targetGroup)) {
4048 self
::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO
::createTempTableName('civicrm_rel');
4050 $where[$grouping][] = " sort_name $nameClause ";
4054 $where = &$this->_where
;
4056 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4060 $allRelationshipType = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE);
4062 if ($nameClause ||
!$targetGroup) {
4063 if (!empty($relationType)) {
4064 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " $name";
4067 $this->_qill
[$grouping][] = $name;
4071 //check to see if the target contact is in specified group
4073 //add contacts from static groups
4074 $this->_tables
['civicrm_relationship_group_contact'] = $this->_whereTables
['civicrm_relationship_group_contact']
4075 = " 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'";
4076 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4077 implode(",", $targetGroup[2]) . ") ) ";
4079 //add contacts from saved searches
4080 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b", $op);
4082 //set the group where clause
4084 $groupWhere[] = "( " . $ssWhere . " )";
4086 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4088 //Get the names of the target groups for the qill
4089 $groupNames = CRM_Core_PseudoConstant
::group();
4090 $qillNames = array();
4091 foreach ($targetGroup[2] as $groupId) {
4092 if (array_key_exists($groupId, $groupNames)) {
4093 $qillNames[] = $groupNames[$groupId];
4096 if (!empty($relationType)) {
4097 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " ( " . implode(", ", $qillNames) . " )";
4100 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4104 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4105 $today = date('Ymd');
4106 //check for active, inactive and all relation status
4107 if ($relStatus[2] == 0) {
4108 $where[$grouping][] = "(
4109 civicrm_relationship.is_active = 1 AND
4110 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4111 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4113 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4115 elseif ($relStatus[2] == 1) {
4116 $where[$grouping][] = "(
4117 civicrm_relationship.is_active = 0 OR
4118 civicrm_relationship.end_date < {$today} OR
4119 civicrm_relationship.start_date > {$today}
4121 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4125 if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
)) {
4128 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4130 //check for permissioned, non-permissioned and all permissioned relations
4131 if ($relPermission[2] == 1) {
4132 $where[$grouping][] = "(
4133 civicrm_relationship.is_permission_a_b = 1
4135 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4137 elseif ($relPermission[2] == 2) {
4138 //non-allowed permission relationship.
4139 $where[$grouping][] = "(
4140 civicrm_relationship.is_permission_a_b = 0
4142 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4145 $this->addRelationshipDateClauses($grouping, $where);
4146 $this->addRelationshipActivePeriodClauses($grouping, $where);
4147 if (!empty($relationType) && !empty($rType) && isset($rType->id
)) {
4148 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
4150 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4151 $this->_useDistinct
= TRUE;
4152 $this->_relationshipValuesAdded
= TRUE;
4153 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4155 // @todo creating a temp table could be expanded to group filter
4156 // as even creating a temp table of all relationships is much much more efficient than
4157 // an OR in the join
4158 if ($relationshipTempTable) {
4160 if (!empty($where[$grouping])) {
4161 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4162 $whereClause = str_replace('contact_b', 'c', $whereClause);
4165 CREATE TEMPORARY TABLE {$relationshipTempTable}
4166 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4167 FROM civicrm_relationship
4168 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4171 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4172 FROM civicrm_relationship
4173 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4176 CRM_Core_DAO
::executeQuery($sql);
4182 * Add start & end date criteria in
4183 * @param string $grouping
4184 * @param array $where
4185 * = array to add where clauses to, in case you are generating a temp table.
4186 * not the main query.
4188 public function addRelationshipDateClauses($grouping, &$where) {
4189 $dateValues = array();
4195 foreach ($dateTypes as $dateField) {
4196 $dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping);
4197 $dateValueHigh = $this->getWhereValues('relation_' . $dateField . '_high', $grouping);
4198 if (!empty($dateValueLow)) {
4199 $date = date('Ymd', strtotime($dateValueLow[2]));
4200 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4201 $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);
4203 if (!empty($dateValueHigh)) {
4204 $date = date('Ymd', strtotime($dateValueHigh[2]));
4205 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4206 $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);
4212 * Add start & end active period criteria in
4213 * @param string $grouping
4214 * @param array $where
4215 * = array to add where clauses to, in case you are generating a temp table.
4216 * not the main query.
4218 public function addRelationshipActivePeriodClauses($grouping, &$where) {
4219 $dateValues = array();
4220 $dateField = 'active_period_date';
4222 $dateValueLow = $this->getWhereValues('relation_active_period_date_low', $grouping);
4223 $dateValueHigh = $this->getWhereValues('relation_active_period_date_high', $grouping);
4224 $dateValueLowFormated = $dateValueHighFormated = NULL;
4225 if (!empty($dateValueLow) && !empty($dateValueHigh)) {
4226 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4227 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4228 $this->_qill
[$grouping][] = (ts('Relationship was active between')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated) . " and " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4230 elseif (!empty($dateValueLow)) {
4231 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4232 $this->_qill
[$grouping][] = (ts('Relationship was active after')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated);
4234 elseif (!empty($dateValueHigh)) {
4235 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4236 $this->_qill
[$grouping][] = (ts('Relationship was active before')) . " " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4239 if ($activePeriodClauses = self
::getRelationshipActivePeriodClauses($dateValueLowFormated, $dateValueHighFormated, TRUE)) {
4240 $where[$grouping][] = $activePeriodClauses;
4245 * Get start & end active period criteria
4247 public static function getRelationshipActivePeriodClauses($from, $to, $forceTableName) {
4248 $tableName = $forceTableName ?
'civicrm_relationship.' : '';
4249 if (!is_null($from) && !is_null($to)) {
4250 return '(((' . $tableName . 'start_date >= ' . $from . ' AND ' . $tableName . 'start_date <= ' . $to . ') OR
4251 (' . $tableName . 'end_date >= ' . $from . ' AND ' . $tableName . 'end_date <= ' . $to . ') OR
4252 (' . $tableName . 'start_date <= ' . $from . ' AND ' . $tableName . 'end_date >= ' . $to . ' )) OR
4253 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4254 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . ') OR
4255 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4257 elseif (!is_null($from)) {
4258 return '((' . $tableName . 'start_date >= ' . $from . ') OR
4259 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4260 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . '))';
4262 elseif (!is_null($to)) {
4263 return '((' . $tableName . 'start_date <= ' . $to . ') OR
4264 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4265 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4270 * Default set of return properties.
4275 * derault return properties
4277 public static function &defaultReturnProperties($mode = 1) {
4278 if (!isset(self
::$_defaultReturnProperties)) {
4279 self
::$_defaultReturnProperties = array();
4282 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4283 // add activity return properties
4284 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4285 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4288 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4291 if (empty(self
::$_defaultReturnProperties[$mode])) {
4292 self
::$_defaultReturnProperties[$mode] = array(
4295 'legal_identifier' => 1,
4296 'external_identifier' => 1,
4297 'contact_type' => 1,
4298 'contact_sub_type' => 1,
4300 'display_name' => 1,
4301 'preferred_mail_format' => 1,
4308 'formal_title' => 1,
4309 'communication_style_id' => 1,
4312 'street_address' => 1,
4313 'supplemental_address_1' => 1,
4314 'supplemental_address_2' => 1,
4315 'supplemental_address_3' => 1,
4318 'postal_code_suffix' => 1,
4319 'state_province' => 1,
4321 'world_region' => 1,
4328 'household_name' => 1,
4329 'organization_name' => 1,
4330 'deceased_date' => 1,
4335 'current_employer' => 1,
4336 // FIXME: should we use defaultHierReturnProperties() for the below?
4337 'do_not_email' => 1,
4340 'do_not_phone' => 1,
4341 'do_not_trade' => 1,
4343 'contact_is_deleted' => 1,
4344 'preferred_communication_method' => 1,
4345 'preferred_language' => 1,
4349 return self
::$_defaultReturnProperties[$mode];
4353 * Get primary condition for a sql clause.
4357 * @return string|NULL
4359 public static function getPrimaryCondition($value) {
4360 if (is_numeric($value)) {
4361 $value = (int ) $value;
4362 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4368 * Wrapper for a simple search query.
4370 * @param array $params
4371 * @param array $returnProperties
4372 * @param bool $count
4376 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4377 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4378 list($select, $from, $where, $having) = $query->query();
4379 $groupBy = ($query->_useGroupBy
) ?
'GROUP BY contact_a.id' : '';
4381 $query = "$select $from $where $groupBy $having";
4386 * These are stub comments as this function needs more explanation - particularly in terms of how it
4387 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4389 * This function was originally written as a wrapper for the api query but is called from multiple places
4390 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4391 * but it is unclear as to whehter that is historical or there is a reason
4392 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4394 * @param array $params
4395 * @param array $returnProperties
4396 * @param null $fields
4397 * @param string $sort
4398 * @param int $offset
4399 * @param int $row_count
4400 * @param bool $smartGroupCache
4401 * ?? update smart group cache?.
4402 * @param bool $count
4403 * Return count obnly.
4404 * @param bool $skipPermissions
4405 * Should permissions be ignored or should the logged in user's permissions be applied.
4407 * This basically correlates to the component.
4408 * @param string $apiEntity
4409 * The api entity being called.
4410 * This sort-of duplicates $mode in a confusing way. Probably not by design.
4414 public static function apiQuery(
4416 $returnProperties = NULL,
4421 $smartGroupCache = TRUE,
4423 $skipPermissions = TRUE,
4424 $mode = CRM_Contact_BAO_Query
::MODE_CONTACTS
,
4428 $query = new CRM_Contact_BAO_Query(
4429 $params, $returnProperties,
4430 NULL, TRUE, FALSE, $mode,
4432 TRUE, $smartGroupCache,
4437 //this should add a check for view deleted if permissions are enabled
4438 if ($skipPermissions) {
4439 $query->_skipDeleteClause
= TRUE;
4441 $query->generatePermissionClause(FALSE, $count);
4443 // note : this modifies _fromClause and _simpleFromClause
4444 $query->includePseudoFieldsJoin($sort);
4446 list($select, $from, $where, $having) = $query->query($count);
4448 $options = $query->_options
;
4449 if (!empty($query->_permissionWhereClause
)) {
4450 if (empty($where)) {
4451 $where = "WHERE $query->_permissionWhereClause";
4454 $where = "$where AND $query->_permissionWhereClause";
4458 $sql = "$select $from $where $having";
4460 // add group by only when API action is not getcount
4461 // otherwise query fetches incorrect count
4462 if ($query->_useGroupBy
&& !$count) {
4463 $sql .= self
::getGroupByFromSelectColumns($query->_select
, 'contact_a.id');
4465 if (!empty($sort)) {
4466 $sort = CRM_Utils_Type
::escape($sort, 'String');
4467 $sql .= " ORDER BY $sort ";
4469 if ($row_count > 0 && $offset >= 0) {
4470 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4471 $row_count = CRM_Utils_Type
::escape($row_count, 'Int');
4472 $sql .= " LIMIT $offset, $row_count ";
4475 $dao = CRM_Core_DAO
::executeQuery($sql);
4477 // @todo derive this from the component class rather than hard-code two options.
4478 $entityIDField = ($mode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) ?
'contribution_id' : 'contact_id';
4481 while ($dao->fetch()) {
4483 $noRows = $dao->rowCount
;
4485 return array($noRows, NULL);
4487 $val = $query->store($dao);
4488 $convertedVals = $query->convertToPseudoNames($dao, TRUE, TRUE);
4490 if (!empty($convertedVals)) {
4491 $val = array_replace_recursive($val, $convertedVals);
4493 $values[$dao->$entityIDField] = $val;
4496 return array($values, $options);
4500 * Get the actual custom field name by stripping off the appended string.
4502 * The string could be _relative, _from, or _to
4504 * @todo use metadata rather than convention to do this.
4506 * @param string $parameterName
4507 * The name of the parameter submitted to the form.
4514 public static function getCustomFieldName($parameterName) {
4515 if (substr($parameterName, -5, 5) == '_from') {
4516 return substr($parameterName, 0, strpos($parameterName, '_from'));
4518 if (substr($parameterName, -9, 9) == '_relative') {
4519 return substr($parameterName, 0, strpos($parameterName, '_relative'));
4521 if (substr($parameterName, -3, 3) == '_to') {
4522 return substr($parameterName, 0, strpos($parameterName, '_to'));
4527 * Convert submitted values for relative custom fields to query object format.
4529 * The query will support the sqlOperator format so convert to that format.
4531 * @param array $formValues
4533 * @param array $params
4534 * Converted parameters for the query object.
4535 * @param string $values
4537 * @param string $fieldName
4538 * Submitted field name. (Matches form field not DB field.)
4540 protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) {
4541 if (empty($values)) {
4542 // e.g we might have relative set & from & to empty. The form flow is a bit funky &
4543 // this function gets called again after they fields have been converted which can get ugly.
4546 $customFieldName = self
::getCustomFieldName($fieldName);
4548 if (substr($fieldName, -9, 9) == '_relative') {
4549 list($from, $to) = CRM_Utils_Date
::getFromTo($values, NULL, NULL);
4552 if ($fieldName == $customFieldName . '_to' && CRM_Utils_Array
::value($customFieldName . '_from', $formValues)) {
4553 // Both to & from are set. We only need to acton one, choosing from.
4557 $from = CRM_Utils_Array
::value($customFieldName . '_from', $formValues, NULL);
4558 $to = CRM_Utils_Array
::value($customFieldName . '_to', $formValues, NULL);
4560 if (self
::isCustomDateField($customFieldName)) {
4561 list($from, $to) = CRM_Utils_Date
::getFromTo(NULL, $from, $to);
4567 $relativeFunction = array('BETWEEN' => array($from, $to));
4570 $relativeFunction = array('>=' => $from);
4574 $relativeFunction = array('<=' => $to);
4586 * Are we dealing with custom field of type date.
4592 public static function isCustomDateField($fieldName) {
4593 if (($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($fieldName)) == FALSE) {
4596 if ('Date' == civicrm_api3('CustomField', 'getvalue', array('id' => $customFieldID, 'return' => 'data_type'))) {
4603 * Has this field already been reformatting to Query object syntax.
4605 * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems
4606 * to come with associated double queries & is possibly damaging performance.
4608 * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns
4611 * @param mixed $values
4612 * Value in formValues for the field.
4616 public static function isAlreadyProcessedForQueryFormat($values) {
4617 if (!is_array($values)) {
4620 if (($operator = CRM_Utils_Array
::value(1, $values)) == FALSE) {
4623 return in_array($operator, CRM_Core_DAO
::acceptedSQLOperators());
4627 * If the state and country are passed remove state.
4629 * Country is implicit from the state, but including both results in
4630 * a poor query as there is no combined index on state AND country.
4634 * @param array $formValues
4636 public static function filterCountryFromValuesIfStateExists(&$formValues) {
4637 if (!empty($formValues['country']) && !empty($formValues['state_province'])) {
4638 // The use of array map sanitises the data by ensuring we are dealing with integers.
4639 $states = implode(', ', array_map('intval', $formValues['state_province']));
4640 $countryList = CRM_Core_DAO
::singleValueQuery(
4641 "SELECT GROUP_CONCAT(country_id) FROM civicrm_state_province WHERE id IN ($states)"
4643 if ($countryList == $formValues['country']) {
4644 unset($formValues['country']);
4650 * For some special cases, grouping by subset of select fields becomes mandatory.
4651 * Hence, full_group_by mode is handled by appending any_value
4652 * keyword to select fields not present in groupBy
4654 * @param array $selectClauses
4655 * @param array $groupBy - Columns already included in GROUP By clause.
4659 public static function appendAnyValueToSelect($selectClauses, $groupBy) {
4660 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4661 $sqlMode = explode(',', CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode'));
4663 // Disable only_full_group_by mode for lower sql versions.
4664 if (version_compare($mysqlVersion, '5.7', '<') ||
(!empty($sqlMode) && !in_array('ONLY_FULL_GROUP_BY', $sqlMode))) {
4665 $key = array_search('ONLY_FULL_GROUP_BY', $sqlMode);
4666 unset($sqlMode[$key]);
4667 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = '" . implode(',', $sqlMode) . "'");
4670 $groupBy = array_map('trim', (array) $groupBy);
4671 $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN)\(/i';
4672 foreach ($selectClauses as $key => &$val) {
4673 list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL);
4674 // append ANY_VALUE() keyword
4675 if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) {
4676 $val = str_replace($selectColumn, "ANY_VALUE({$selectColumn})", $val);
4681 return "SELECT " . implode(', ', $selectClauses) . " ";
4685 * Include Select columns in groupBy clause.
4687 * @param array $selectClauses
4688 * @param array $groupBy - Columns already included in GROUP By clause.
4692 public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NULL) {
4693 $groupBy = (array) $groupBy;
4694 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4695 $sqlMode = CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode');
4697 //return if ONLY_FULL_GROUP_BY is not enabled.
4698 if (!version_compare($mysqlVersion, '5.7', '<') && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
4699 $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN)\(/i';
4700 foreach ($selectClauses as $key => $val) {
4701 $aliasArray = preg_split('/ as /i', $val);
4702 // if more than 1 alias we need to split by ','.
4703 if (count($aliasArray) > 2) {
4704 $aliasArray = preg_split('/,/', $val);
4705 foreach ($aliasArray as $key => $value) {
4706 $alias = current(preg_split('/ as /i', $value));
4707 if (!in_array($alias, $groupBy) && preg_match($regexToExclude, trim($alias)) !== 1) {
4708 $groupBy[] = $alias;
4713 list($selectColumn, $alias) = array_pad($aliasArray, 2, NULL);
4714 $dateRegex = '/^(DATE_FORMAT|DATE_ADD|CASE)/i';
4715 $tableName = current(explode('.', $selectColumn));
4716 $primaryKey = "{$tableName}.id";
4717 // exclude columns which are already included in groupBy and aggregate functions from select
4718 // CRM-18439 - Also exclude the columns which are functionally dependent on columns in $groupBy (MySQL 5.7+)
4719 if (!in_array($selectColumn, $groupBy) && !in_array($primaryKey, $groupBy) && preg_match($regexToExclude, trim($selectColumn)) !== 1) {
4720 if (!empty($alias) && preg_match($dateRegex, trim($selectColumn))) {
4721 $groupBy[] = $alias;
4724 $groupBy[] = $selectColumn;
4731 if (!empty($groupBy)) {
4732 return " GROUP BY " . implode(', ', $groupBy);
4738 * Create and query the db for an contact search.
4740 * @param int $offset
4741 * The offset for the query.
4742 * @param int $rowCount
4743 * The number of rows to return.
4744 * @param string|CRM_Utils_Sort $sort
4745 * The order by string.
4746 * @param bool $count
4747 * Is this a count only query ?.
4748 * @param bool $includeContactIds
4749 * Should we include contact ids?.
4750 * @param bool $sortByChar
4751 * If true returns the distinct array of first characters for search results.
4752 * @param bool $groupContacts
4753 * If true, return only the contact ids.
4754 * @param bool $returnQuery
4755 * Should we return the query as a string.
4756 * @param string $additionalWhereClause
4757 * If the caller wants to further restrict the search (used for components).
4758 * @param null $sortOrder
4759 * @param string $additionalFromClause
4760 * Should be clause with proper joins, effective to reduce where clause load.
4762 * @param bool $skipOrderAndLimit
4764 * @return CRM_Core_DAO
4766 public function searchQuery(
4767 $offset = 0, $rowCount = 0, $sort = NULL,
4768 $count = FALSE, $includeContactIds = FALSE,
4769 $sortByChar = FALSE, $groupContacts = FALSE,
4770 $returnQuery = FALSE,
4771 $additionalWhereClause = NULL, $sortOrder = NULL,
4772 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4775 if ($includeContactIds) {
4776 $this->_includeContactIds
= TRUE;
4777 $this->_whereClause
= $this->whereClause();
4780 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4782 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4783 // and that contact happens to be deleted, set $onlyDeleted to true
4784 foreach ($this->_params
as $values) {
4785 $name = CRM_Utils_Array
::value(0, $values);
4786 $op = CRM_Utils_Array
::value(1, $values);
4787 $value = CRM_Utils_Array
::value(2, $values);
4788 if ($name == 'contact_id' and $op == '=') {
4789 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4790 $onlyDeleted = TRUE;
4796 // building the query string
4797 $groupBy = $groupByCol = NULL;
4799 if (isset($this->_groupByComponentClause
)) {
4800 $groupBy = $this->_groupByComponentClause
;
4801 $groupCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause
));
4802 $groupByCol = explode(', ', $groupCols);
4804 elseif ($this->_useGroupBy
) {
4805 $groupByCol = 'contact_a.id';
4806 $groupBy = ' GROUP BY contact_a.id';
4809 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4810 $groupByCol = 'civicrm_activity.id';
4811 $groupBy = 'GROUP BY civicrm_activity.id ';
4814 $order = $orderBy = $limit = '';
4816 list($order, $additionalFromClause) = $this->prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause);
4818 if ($rowCount > 0 && $offset >= 0) {
4819 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4820 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4821 $limit = " LIMIT $offset, $rowCount ";
4826 $this->_sort
= $sort;
4829 $this->includePseudoFieldsJoin($sort);
4831 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4833 if (!empty($groupByCol)) {
4834 $groupBy = self
::getGroupByFromSelectColumns($this->_select
, $groupByCol);
4837 if ($additionalWhereClause) {
4838 $where = $where . ' AND ' . $additionalWhereClause;
4841 //additional from clause should be w/ proper joins.
4842 if ($additionalFromClause) {
4843 $from .= "\n" . $additionalFromClause;
4846 // if we are doing a transform, do it here
4847 // use the $from, $where and $having to get the contact ID
4848 if ($this->_displayRelationshipType
) {
4849 $this->filterRelatedContacts($from, $where, $having);
4852 if ($skipOrderAndLimit) {
4853 $query = "$select $from $where $having $groupBy";
4856 $query = "$select $from $where $having $groupBy $order $limit";
4863 return CRM_Core_DAO
::singleValueQuery($query);
4866 $dao = CRM_Core_DAO
::executeQuery($query);
4867 if ($groupContacts) {
4869 while ($dao->fetch()) {
4873 return implode(',', $ids);
4880 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4882 * @param string $cacheKey
4883 * @param int $offset
4884 * @param int $rowCount
4885 * @param bool $includeContactIds
4886 * @return CRM_Core_DAO
4888 public function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4889 $this->_includeContactIds
= $includeContactIds;
4890 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4891 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
4892 $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);
4893 $order = " ORDER BY pnc.id";
4894 $groupByCol = array('contact_a.id', 'pnc.id');
4895 $groupBy = self
::getGroupByFromSelectColumns($this->_select
, $groupByCol);
4896 $limit = " LIMIT $offset, $rowCount";
4897 $query = "$select $from $where $groupBy $order $limit";
4899 return CRM_Core_DAO
::executeQuery($query);
4903 * Populate $this->_permissionWhereClause with permission related clause and update other
4904 * query related properties.
4906 * Function calls ACL permission class and hooks to filter the query appropriately
4908 * Note that these 2 params were in the code when extracted from another function
4909 * and a second round extraction would be to make them properties of the class
4911 * @param bool $onlyDeleted
4912 * Only get deleted contacts.
4913 * @param bool $count
4914 * Return Count only.
4916 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4917 if (!$this->_skipPermission
) {
4918 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4919 CRM_Core_Permission
::VIEW
,
4921 $this->_whereTables
,
4924 $this->_skipDeleteClause
4927 // regenerate fromClause since permission might have added tables
4928 if ($this->_permissionWhereClause
) {
4929 //fix for row count in qill (in contribute/membership find)
4931 $this->_useDistinct
= TRUE;
4934 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4935 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4936 // note : this modifies _fromClause and _simpleFromClause
4937 $this->includePseudoFieldsJoin($this->_sort
);
4941 // add delete clause if needed even if we are skipping permission
4943 if (!$this->_skipDeleteClause
) {
4944 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4945 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4949 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4958 public function setSkipPermission($val) {
4959 $this->_skipPermission
= $val;
4963 * @param null $context
4967 public function &summaryContribution($context = NULL) {
4968 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4972 SELECT COUNT( conts.total_amount ) as total_count,
4973 SUM( conts.total_amount ) as total_amount,
4974 AVG( conts.total_amount ) as total_avg,
4975 conts.currency as currency";
4976 if ($this->_permissionWhereClause
) {
4977 $where .= " AND " . $this->_permissionWhereClause
;
4979 if ($context == 'search') {
4980 $where .= " AND contact_a.is_deleted = 0 ";
4982 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4983 if (!empty($financialTypes)) {
4984 $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
4985 $from .= " LEFT JOIN civicrm_line_item li
4986 ON civicrm_contribution.id = li.contribution_id AND
4987 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
4990 $where .= " AND civicrm_contribution.financial_type_id IN (0)";
4993 // make sure contribution is completed - CRM-4989
4994 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4997 $summary['total'] = array();
4998 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4999 $innerQuery = "SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
5000 civicrm_contribution.currency $from $completedWhere";
5001 $query = "$select FROM (
5002 $innerQuery GROUP BY civicrm_contribution.id
5006 $dao = CRM_Core_DAO
::executeQuery($query);
5008 $summary['total']['count'] = 0;
5009 $summary['total']['amount'] = $summary['total']['avg'] = array();
5010 while ($dao->fetch()) {
5011 $summary['total']['count'] +
= $dao->total_count
;
5012 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
5013 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
5016 $orderBy = 'ORDER BY civicrm_contribution_total_amount_count DESC';
5017 $groupBy = 'GROUP BY currency, civicrm_contribution.total_amount';
5018 $modeSQL = "$select, SUBSTRING_INDEX(GROUP_CONCAT(conts.total_amount
5019 ORDER BY conts.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
5020 MAX(conts.civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count
5022 $groupBy $orderBy) as conts
5025 $summary['total']['mode'] = CRM_Contribute_BAO_Contribution
::computeStats('mode', $modeSQL);
5027 $medianSQL = "{$from} {$completedWhere}";
5028 $summary['total']['median'] = CRM_Contribute_BAO_Contribution
::computeStats('median', $medianSQL, 'civicrm_contribution');
5029 $summary['total']['currencyCount'] = count($summary['total']['median']);
5031 if (!empty($summary['total']['amount'])) {
5032 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
5033 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
5034 $summary['total']['mode'] = implode(', ', $summary['total']['mode']);
5035 $summary['total']['median'] = implode(', ', $summary['total']['median']);
5038 $summary['total']['amount'] = $summary['total']['avg'] = $summary['total']['median'] = 0;
5041 // soft credit summary
5042 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
5043 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
5046 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
5047 GROUP BY civicrm_contribution_soft.id
5050 $dao = CRM_Core_DAO
::executeQuery($query);
5051 $summary['soft_credit']['count'] = 0;
5052 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
5053 while ($dao->fetch()) {
5054 $summary['soft_credit']['count'] +
= $dao->total_count
;
5055 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
5056 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
5058 if (!empty($summary['soft_credit']['amount'])) {
5059 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
5060 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
5063 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
5068 //@todo - this could be one query using the IF in mysql - eg
5069 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
5070 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
5071 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
5072 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
5073 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
5074 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
5075 // FROM civicrm_contact contact_a
5076 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
5077 // WHERE ( ... where clause....
5078 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
5082 SELECT COUNT( conts.total_amount ) as cancel_count,
5083 SUM( conts.total_amount ) as cancel_amount,
5084 AVG( conts.total_amount ) as cancel_avg,
5085 conts.currency as currency";
5087 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
5088 if ($context == 'search') {
5089 $where .= " AND contact_a.is_deleted = 0 ";
5092 $query = "$select FROM (
5093 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
5094 GROUP BY civicrm_contribution.id
5098 $dao = CRM_Core_DAO
::executeQuery($query);
5101 if ($dao->fetch()) {
5102 $summary['cancel']['count'] = $dao->cancel_count
;
5103 $summary['cancel']['amount'] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
5104 $summary['cancel']['avg'] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
5108 $summary['cancel']['count'] = 0;
5109 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
5110 while ($dao->fetch()) {
5111 $summary['cancel']['count'] +
= $dao->cancel_count
;
5112 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
5113 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
5115 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
5116 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
5123 * Getter for the qill object.
5127 public function qill() {
5128 return $this->_qill
;
5132 * Default set of return default hier return properties.
5136 public static function &defaultHierReturnProperties() {
5137 if (!isset(self
::$_defaultHierReturnProperties)) {
5138 self
::$_defaultHierReturnProperties = array(
5141 'legal_identifier' => 1,
5142 'external_identifier' => 1,
5143 'contact_type' => 1,
5144 'contact_sub_type' => 1,
5146 'display_name' => 1,
5153 'formal_title' => 1,
5154 'communication_style_id' => 1,
5155 'email_greeting' => 1,
5156 'postal_greeting' => 1,
5160 'preferred_communication_method' => 1,
5161 'do_not_phone' => 1,
5162 'do_not_email' => 1,
5165 'do_not_trade' => 1,
5166 'location' => array(
5168 'location_type' => 1,
5169 'street_address' => 1,
5171 'state_province' => 1,
5173 'postal_code_suffix' => 1,
5176 'phone-Mobile' => 1,
5189 'location_type' => 1,
5190 'street_address' => 1,
5192 'state_province' => 1,
5194 'postal_code_suffix' => 1,
5197 'phone-Mobile' => 1,
5211 return self
::$_defaultHierReturnProperties;
5215 * Build query for a date field.
5217 * @param array $values
5218 * @param string $tableName
5219 * @param string $fieldName
5220 * @param string $dbFieldName
5221 * @param string $fieldTitle
5222 * @param bool $appendTimeStamp
5224 public function dateQueryBuilder(
5225 &$values, $tableName, $fieldName,
5226 $dbFieldName, $fieldTitle,
5227 $appendTimeStamp = TRUE
5229 list($name, $op, $value, $grouping, $wildcard) = $values;
5231 if ($name == "{$fieldName}_low" ||
5232 $name == "{$fieldName}_high"
5234 if (isset($this->_rangeCache
[$fieldName]) ||
!$value) {
5237 $this->_rangeCache
[$fieldName] = 1;
5239 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
5241 if ($name == $fieldName . '_low') {
5243 $firstPhrase = ts('greater than or equal to');
5244 $firstDate = CRM_Utils_Date
::processDate($value);
5246 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5247 if (!empty($secondValues) && $secondValues[2]) {
5249 $secondPhrase = ts('less than or equal to');
5250 $secondValue = $secondValues[2];
5252 if ($appendTimeStamp && strlen($secondValue) == 10) {
5253 $secondValue .= ' 23:59:59';
5255 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5258 elseif ($name == $fieldName . '_high') {
5260 $firstPhrase = ts('less than or equal to');
5262 if ($appendTimeStamp && strlen($value) == 10) {
5263 $value .= ' 23:59:59';
5265 $firstDate = CRM_Utils_Date
::processDate($value);
5267 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5268 if (!empty($secondValues) && $secondValues[2]) {
5270 $secondPhrase = ts('greater than or equal to');
5271 $secondValue = $secondValues[2];
5272 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5276 if (!$appendTimeStamp) {
5277 $firstDate = substr($firstDate, 0, 8);
5279 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5282 if (!$appendTimeStamp) {
5283 $secondDate = substr($secondDate, 0, 8);
5285 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5288 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5290 $this->_where
[$grouping][] = "
5291 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5292 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5294 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5297 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5298 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5302 if ($name == $fieldName) {
5303 //In Get API, for operators other then '=' the $value is in array(op => value) format
5304 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5306 $value = $value[$op];
5309 $date = $format = NULL;
5310 if (strstr($op, 'IN')) {
5312 foreach ($value as &$date) {
5313 $date = CRM_Utils_Date
::processDate($date);
5314 if (!$appendTimeStamp) {
5315 $date = substr($date, 0, 8);
5317 $format[] = CRM_Utils_Date
::customFormat($date);
5319 $date = "('" . implode("','", $value) . "')";
5320 $format = implode(', ', $format);
5322 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5323 $date = CRM_Utils_Date
::processDate($value);
5324 if (!$appendTimeStamp) {
5325 $date = substr($date, 0, 8);
5327 $format = CRM_Utils_Date
::customFormat($date);
5332 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5335 $this->_where
[$grouping][] = self
::buildClause("{$tableName}.{$dbFieldName}", $op);
5338 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5340 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
5341 $this->_qill
[$grouping][] = "$fieldTitle $op $format";
5347 * @param string $tableName
5348 * @param string $fieldName
5349 * @param string $dbFieldName
5350 * @param $fieldTitle
5351 * @param null $options
5353 public function numberRangeBuilder(
5355 $tableName, $fieldName,
5356 $dbFieldName, $fieldTitle,
5359 list($name, $op, $value, $grouping, $wildcard) = $values;
5361 if ($name == "{$fieldName}_low" ||
5362 $name == "{$fieldName}_high"
5364 if (isset($this->_rangeCache
[$fieldName])) {
5367 $this->_rangeCache
[$fieldName] = 1;
5369 $secondOP = $secondPhrase = $secondValue = NULL;
5371 if ($name == "{$fieldName}_low") {
5373 $firstPhrase = ts('greater than');
5375 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5376 if (!empty($secondValues)) {
5378 $secondPhrase = ts('less than');
5379 $secondValue = $secondValues[2];
5384 $firstPhrase = ts('less than');
5386 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5387 if (!empty($secondValues)) {
5389 $secondPhrase = ts('greater than');
5390 $secondValue = $secondValues[2];
5395 $this->_where
[$grouping][] = "
5396 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5397 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5399 $displayValue = $options ?
$options[$value] : $value;
5400 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5402 $this->_qill
[$grouping][]
5403 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5406 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5407 $displayValue = $options ?
$options[$value] : $value;
5408 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5410 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5415 if ($name == $fieldName) {
5419 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5421 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5422 $displayValue = $options ?
$options[$value] : $value;
5423 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5430 * @param string $tableName
5431 * @param string $fieldName
5432 * @param string $dbFieldName
5433 * @param $fieldTitle
5434 * @param null $options
5436 public function ageRangeQueryBuilder(
5438 $tableName, $fieldName,
5439 $dbFieldName, $fieldTitle,
5442 list($name, $op, $value, $grouping, $wildcard) = $values;
5444 $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
5445 $asofDate = NULL; // will be treated as current day
5446 if ($asofDateValues) {
5447 $asofDate = CRM_Utils_Date
::processDate($asofDateValues[2]);
5448 $asofDateFormat = CRM_Utils_Date
::customFormat(substr($asofDate, 0, 8));
5449 $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat;
5452 if ($name == "{$fieldName}_low" ||
5453 $name == "{$fieldName}_high"
5455 if (isset($this->_rangeCache
[$fieldName])) {
5458 $this->_rangeCache
[$fieldName] = 1;
5460 $secondOP = $secondPhrase = $secondValue = NULL;
5462 if ($name == "{$fieldName}_low") {
5463 $firstPhrase = ts('greater than or equal to');
5464 // NB: age > X means date of birth < Y
5466 $firstDate = self
::calcDateFromAge($asofDate, $value, 'min');
5468 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5469 if (!empty($secondValues)) {
5471 $secondPhrase = ts('less than or equal to');
5472 $secondValue = $secondValues[2];
5473 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'max');
5478 $firstPhrase = ts('less than or equal to');
5479 $firstDate = self
::calcDateFromAge($asofDate, $value, 'max');
5481 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5482 if (!empty($secondValues)) {
5484 $secondPhrase = ts('greater than or equal to');
5485 $secondValue = $secondValues[2];
5486 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'min');
5491 $this->_where
[$grouping][] = "
5492 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5493 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5495 $displayValue = $options ?
$options[$value] : $value;
5496 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5498 $this->_qill
[$grouping][]
5499 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5502 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5503 $displayValue = $options ?
$options[$value] : $value;
5504 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5506 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5512 * Calculate date from age.
5514 * @param string $asofDate
5516 * @param string $type
5520 public static function calcDateFromAge($asofDate, $age, $type) {
5521 $date = new DateTime($asofDate);
5522 if ($type == "min") {
5523 // minimum age is $age: dob <= date - age "235959"
5524 $date->sub(new DateInterval("P" . $age . "Y"));
5525 return $date->format('Ymd') . "235959";
5528 // max age is $age: dob >= date - (age + 1y) + 1d "000000"
5529 $date->sub(new DateInterval("P" . ($age +
1) . "Y"))->add(new DateInterval("P1D"));
5530 return $date->format('Ymd') . "000000";
5535 * Given the field name, operator, value & its data type
5536 * builds the where Clause for the query
5537 * used for handling 'IS NULL'/'IS NOT NULL' operators
5539 * @param string $field
5543 * @param string $value
5545 * @param string $dataType
5546 * Data type of the field.
5549 * Where clause for the query.
5551 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5553 $clause = "$field $op";
5561 $clause = " (NULLIF($field, '') IS NULL) ";
5564 case 'IS NOT EMPTY':
5565 $clause = " (NULLIF($field, '') IS NOT NULL) ";
5570 // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
5571 if (!empty($value) && (!is_array($value) ||
!array_key_exists($op, $value))) {
5572 $value = array($op => (array) $value);
5576 if (empty($dataType)) {
5577 $dataType = 'String';
5579 if (is_array($value)) {
5580 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5581 // widely used and consistent across the codebase
5582 // adding this here won't accept the search functions which don't submit an array
5583 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, $value, $dataType)) != FALSE) {
5585 return $queryString;
5588 // 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))
5589 // but we got only array(2,5) from the form.
5590 // We could get away with keeping this in 4.6 if we make it such that it throws an enotice in 4.7 so
5591 // people have to de-slopify it.
5592 if (!empty($value[0])) {
5593 if ($op != 'BETWEEN') {
5594 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReport;
5596 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => $value), $dataType)) != FALSE) {
5597 return $queryString;
5602 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReportUsingOldFormat;
5603 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => array_keys($value)), $dataType)) != FALSE) {
5604 return $queryString;
5609 $value = CRM_Utils_Type
::escape($value, $dataType);
5610 // if we don't have a dataType we should assume
5611 if ($dataType == 'String' ||
$dataType == 'Text') {
5612 $value = "'" . strtolower($value) . "'";
5614 return "$clause $value";
5619 * @param bool $reset
5623 public function openedSearchPanes($reset = FALSE) {
5624 if (!$reset ||
empty($this->_whereTables
)) {
5625 return self
::$_openedPanes;
5628 // pane name to table mapper
5629 $panesMapper = array(
5630 ts('Contributions') => 'civicrm_contribution',
5631 ts('Memberships') => 'civicrm_membership',
5632 ts('Events') => 'civicrm_participant',
5633 ts('Relationships') => 'civicrm_relationship',
5634 ts('Activities') => 'civicrm_activity',
5635 ts('Pledges') => 'civicrm_pledge',
5636 ts('Cases') => 'civicrm_case',
5637 ts('Grants') => 'civicrm_grant',
5638 ts('Address Fields') => 'civicrm_address',
5639 ts('Notes') => 'civicrm_note',
5640 ts('Change Log') => 'civicrm_log',
5641 ts('Mailings') => 'civicrm_mailing',
5643 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5645 foreach (array_keys($this->_whereTables
) as $table) {
5646 if ($panName = array_search($table, $panesMapper)) {
5647 self
::$_openedPanes[$panName] = TRUE;
5651 return self
::$_openedPanes;
5657 public function setOperator($operator) {
5658 $validOperators = array('AND', 'OR');
5659 if (!in_array($operator, $validOperators)) {
5662 $this->_operator
= $operator;
5668 public function getOperator() {
5669 return $this->_operator
;
5677 public function filterRelatedContacts(&$from, &$where, &$having) {
5678 static $_rTypeProcessed = NULL;
5679 static $_rTypeFrom = NULL;
5680 static $_rTypeWhere = NULL;
5682 if (!$_rTypeProcessed) {
5683 $_rTypeProcessed = TRUE;
5685 // create temp table with contact ids
5686 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5687 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5688 CRM_Core_DAO
::executeQuery($sql);
5691 REPLACE INTO $tableName ( contact_id )
5697 CRM_Core_DAO
::executeQuery($sql);
5699 $qillMessage = ts('Contacts with a Relationship Type of: ');
5700 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5702 if (is_numeric($this->_displayRelationshipType
)) {
5703 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5705 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5706 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5709 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5710 AND displayRelType.is_active = 1
5714 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5715 if ($dirOne == 'a') {
5716 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5718 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5719 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5723 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5725 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5726 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5730 WHERE displayRelType.relationship_type_id = $relType
5731 AND displayRelType.is_active = 1
5734 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5737 if (!empty($this->_permissionWhereClause
)) {
5738 $_rTypeWhere .= "AND $this->_permissionWhereClause";
5741 if (strpos($from, $_rTypeFrom) === FALSE) {
5742 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5743 // this happens when we have an event_type in the quert (CRM-7969)
5744 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5745 $from .= $_rTypeFrom;
5746 $where = $_rTypeWhere;
5753 * See CRM-19811 for why this is database hurty without apparent benefit.
5759 public static function caseImportant($op) {
5761 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5765 * @param $returnProperties
5770 public static function componentPresent(&$returnProperties, $prefix) {
5771 foreach ($returnProperties as $name => $dontCare) {
5772 if (substr($name, 0, strlen($prefix)) == $prefix) {
5780 * Builds the necessary structures for all fields that are similar to option value look-ups.
5782 * @param string $name
5783 * the name of the field.
5785 * the sql operator, this function should handle ALL SQL operators.
5786 * @param string $value
5787 * depends on the operator and who's calling the query builder.
5788 * @param int $grouping
5789 * the index where to place the where clause.
5790 * @param string $daoName
5792 * @param array $field
5793 * an array that contains various properties of the field identified by $name.
5794 * @param string $label
5795 * The label for this field element.
5796 * @param string $dataType
5797 * The data type for this element.
5798 * @param bool $useIDsOnly
5800 public function optionValueQuery(
5808 $dataType = 'String',
5812 $pseudoFields = array(
5819 'communication_style_id',
5823 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5824 if ($tableName == 'civicrm_contact') {
5825 $wc = "contact_a.$fieldName";
5828 $wc = "$tableName.id";
5832 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
5833 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5835 if (in_array($name, $pseudoFields)) {
5836 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5837 $wc = "contact_a.{$name}_id";
5839 $dataType = 'Positive';
5840 $value = (!$value) ?
0 : $value;
5842 if ($name == "world_region") {
5843 $field['name'] = $name;
5846 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue($daoName, $field['name'], $value, $op);
5847 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillop, 3 => $qillVal));
5848 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5852 * Check and explode a user defined numeric string into an array
5853 * this was the protocol used by search builder in the old old days before we had
5854 * super nice js widgets to do the hard work
5856 * @param string $string
5857 * @param string $dataType
5858 * The dataType we should check for the values, default integer.
5860 * @return bool|array
5861 * false if string does not match the pattern
5862 * array of numeric values if string does match the pattern
5864 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5865 $string = trim($string);
5866 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5870 $string = substr($string, 1, -1);
5871 $values = explode(',', $string);
5872 if (empty($values)) {
5876 $returnValues = array();
5877 foreach ($values as $v) {
5878 if ($dataType == 'Integer' && !is_numeric($v)) {
5881 elseif ($dataType == 'String' && !is_string($v)) {
5884 $returnValues[] = trim($v);
5887 if (empty($returnValues)) {
5891 return $returnValues;
5895 * Convert the pseudo constants id's to their names
5897 * @param CRM_Core_DAO $dao
5898 * @param bool $return
5899 * @param bool $usedForAPI
5901 * @return array|NULL
5903 public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) {
5904 if (empty($this->_pseudoConstantsSelect
)) {
5908 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5909 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5913 if (is_object($dao) && property_exists($dao, $value['idCol'])) {
5914 $val = $dao->{$value['idCol']};
5915 if ($key == 'groups') {
5916 $dao->groups
= $this->convertGroupIDStringToLabelString($dao, $val);
5920 if (CRM_Utils_System
::isNull($val)) {
5923 elseif (!empty($value['pseudoconstant'])) {
5924 // If pseudoconstant is set that is kind of defacto for 'we have a bit more info about this'
5925 // and we can use the metadata to figure it out.
5926 // ideally this bit of IF will absorb & replace all the rest in time as we move to
5927 // more metadata based choices.
5928 if (strpos($val, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
5929 $dbValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($val, CRM_Core_DAO
::VALUE_SEPARATOR
));
5930 foreach ($dbValues as $pseudoValue) {
5931 $convertedValues[] = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $pseudoValue);
5934 $dao->$key = ($usedForAPI) ?
$convertedValues : implode(', ', $convertedValues);
5935 $realFieldName = CRM_Utils_Array
::value('field_name', $this->_pseudoConstantsSelect
[$key]);
5936 if ($usedForAPI && $realFieldName) {
5937 // normally we would see 2 fields returned for pseudoConstants. An exception is
5938 // preferred_communication_method where there is no id-variant.
5939 // For the api we prioritise getting the real data returned.
5940 // over the resolved version
5941 $dao->$realFieldName = $dbValues;
5946 // This is basically the same as the default but since we have the bao we can use
5947 // a cached function.
5948 $dao->$key = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $val);
5951 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5953 $idColumn = "{$key}_id";
5954 $dao->$idColumn = $val;
5956 if ($key == 'state_province_name') {
5957 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::stateProvince($val);
5960 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5963 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5964 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5966 // @todo handle this in the section above for pseudoconstants.
5967 elseif (in_array($value['pseudoField'], array('participant_role_id', 'participant_role'))) {
5968 // @todo define bao on this & merge into the above condition.
5969 $viewValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val);
5971 if ($value['pseudoField'] == 'participant_role') {
5972 $pseudoOptions = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'role_id');
5973 foreach ($viewValues as $k => $v) {
5974 $viewValues[$k] = $pseudoOptions[$v];
5977 $dao->$key = ($usedForAPI && count($viewValues) > 1) ?
$viewValues : implode(', ', $viewValues);
5980 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5981 $dao->$key = $labels[$val];
5984 // return converted values in array format
5986 if (strpos($key, '-') !== FALSE) {
5987 $keyVal = explode('-', $key);
5988 $current = &$values;
5989 $lastElement = array_pop($keyVal);
5990 foreach ($keyVal as $v) {
5991 if (!array_key_exists($v, $current)) {
5992 $current[$v] = array();
5994 $current = &$current[$v];
5996 $current[$lastElement] = $dao->$key;
5999 $values[$key] = $dao->$key;
6006 'gender_id' => 'gender',
6007 'prefix_id' => 'individual_prefix',
6008 'suffix_id' => 'individual_suffix',
6009 'communication_style_id' => 'communication_style',
6010 ) as $realField => $labelField) {
6011 // This is a temporary routine for handling these fields while
6012 // we figure out how to handled them based on metadata in
6013 /// export and search builder. CRM-19815, CRM-19830.
6014 if (isset($dao->$realField) && is_numeric($dao->$realField) && isset($dao->$labelField)) {
6015 $dao->$realField = $dao->$labelField;
6023 * Include pseudo fields LEFT JOIN.
6024 * @param string|array $sort can be a object or string
6026 * @return array|NULL
6028 public function includePseudoFieldsJoin($sort) {
6029 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
6032 $sort = is_string($sort) ?
$sort : $sort->orderBy();
6035 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
6036 if (!empty($value['table'])) {
6037 $regex = "/({$value['table']}\.|{$name})/";
6038 if (preg_match($regex, $sort)) {
6039 $this->_elemnt
[$value['element']] = 1;
6040 $this->_select
[$value['element']] = $value['select'];
6041 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
6042 $present[$value['table']] = $value['join'];
6046 $presentSimpleFrom = $present;
6048 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
6049 array_key_exists('civicrm_country', $presentSimpleFrom)
6051 unset($presentSimpleFrom['civicrm_country']);
6053 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
6054 array_key_exists('civicrm_country', $present)
6056 unset($present['civicrm_country']);
6059 $presentClause = $presentSimpleFromClause = NULL;
6060 if (!empty($present)) {
6061 $presentClause = implode(' ', $present);
6063 if (!empty($presentSimpleFrom)) {
6064 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
6067 $this->_fromClause
= $this->_fromClause
. $presentClause;
6068 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
6070 return array($presentClause, $presentSimpleFromClause);
6074 * Build qill for field.
6076 * Qill refers to the query detail visible on the UI.
6078 * @param string $daoName
6079 * @param string $fieldName
6080 * @param mixed $fieldValue
6082 * @param array $pseudoExtraParam
6084 * Type of the field per CRM_Utils_Type
6088 public static function buildQillForFieldValue(
6093 $pseudoExtraParam = array(),
6094 $type = CRM_Utils_Type
::T_STRING
6096 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
6098 //API usually have fieldValue format as array(operator => array(values)),
6099 //so we need to separate operator out of fieldValue param
6100 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
6101 $op = key($fieldValue);
6102 $fieldValue = $fieldValue[$op];
6105 // if Operator chosen is NULL/EMPTY then
6106 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
6107 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), '');
6110 if ($fieldName == 'activity_type_id') {
6111 $pseudoOptions = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
6113 elseif ($fieldName == 'country_id') {
6114 $pseudoOptions = CRM_Core_PseudoConstant
::country();
6116 elseif ($fieldName == 'county_id') {
6117 $pseudoOptions = CRM_Core_PseudoConstant
::county();
6119 elseif ($fieldName == 'world_region') {
6120 $pseudoOptions = CRM_Core_PseudoConstant
::worldRegion();
6122 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
6123 $pseudoOptions = CRM_Event_BAO_Event
::getEvents(0, $fieldValue, TRUE, TRUE, TRUE);
6125 elseif ($fieldName == 'contribution_product_id') {
6126 $pseudoOptions = CRM_Contribute_PseudoConstant
::products();
6128 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
6129 $pseudoOptions = CRM_Core_PseudoConstant
::group();
6131 elseif ($daoName == 'CRM_Batch_BAO_EntityBatch' && $fieldName == 'batch_id') {
6132 $pseudoOptions = CRM_Contribute_PseudoConstant
::batch();
6135 $pseudoOptions = CRM_Core_PseudoConstant
::get($daoName, $fieldName, $pseudoExtraParam);
6138 if (is_array($fieldValue)) {
6139 $qillString = array();
6140 if (!empty($pseudoOptions)) {
6141 foreach ((array) $fieldValue as $val) {
6142 $qillString[] = CRM_Utils_Array
::value($val, $pseudoOptions, $val);
6144 $fieldValue = implode(', ', $qillString);
6147 if ($type == CRM_Utils_Type
::T_DATE
) {
6148 foreach ($fieldValue as $index => $value) {
6149 $fieldValue[$index] = CRM_Utils_Date
::customFormat($value);
6153 // @todo - this is a bit specific (one operator).
6154 // However it is covered by a unit test so can be altered later with
6156 if ($op == 'BETWEEN') {
6157 $separator = ' AND ';
6159 $fieldValue = implode($separator, $fieldValue);
6162 elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) {
6163 $fieldValue = $pseudoOptions[$fieldValue];
6165 elseif ($type === CRM_Utils_Type
::T_DATE
) {
6166 $fieldValue = CRM_Utils_Date
::customFormat($fieldValue);
6169 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), $fieldValue);
6173 * Alter value to reflect wildcard settings.
6175 * The form will have tried to guess whether this is a good field to wildcard but there is
6176 * also a site-wide setting that specifies whether it is OK to append the wild card to the beginning
6177 * or only the end of the string
6179 * @param bool $wildcard
6180 * This is a bool made on an assessment 'elsewhere' on whether this is a good field to wildcard.
6182 * Generally '=' or 'LIKE'.
6183 * @param string $value
6184 * The search string.
6188 public static function getWildCardedValue($wildcard, $op, $value) {
6189 if ($wildcard && $op == 'LIKE') {
6190 if (CRM_Core_Config
::singleton()->includeWildCardInName
&& (substr($value, 0, 1) != '%')) {
6203 * Process special fields of Search Form in OK (Operator in Key) format
6205 * @param array $formValues
6206 * @param array $specialFields
6207 * Special params to be processed
6208 * @param array $changeNames
6209 * Array of fields whose name should be changed
6211 public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = array()) {
6212 // Array of special fields whose value are considered only for NULL or EMPTY operators
6213 $nullableFields = array('contribution_batch_id');
6215 foreach ($specialFields as $element) {
6216 $value = CRM_Utils_Array
::value($element, $formValues);
6218 if (is_array($value)) {
6219 if (in_array($element, array_keys($changeNames))) {
6220 unset($formValues[$element]);
6221 $element = $changeNames[$element];
6223 $formValues[$element] = array('IN' => $value);
6225 elseif (in_array($value, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
6226 $formValues[$element] = array($value => 1);
6228 elseif (!in_array($element, $nullableFields)) {
6229 // if wildcard is already present return searchString as it is OR append and/or prepend with wildcard
6230 $isWilcard = strstr($value, '%') ?
FALSE : CRM_Core_Config
::singleton()->includeWildCardInName
;
6231 $formValues[$element] = array('LIKE' => self
::getWildCardedValue($isWilcard, 'LIKE', $value));
6238 * Parse and assimilate the various sort options.
6240 * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`,
6241 * `email`), the related table may be joined automatically.
6243 * At time of writing, this code is deeply flawed and should be rewritten. For the moment,
6244 * it's been extracted to a standalone function.
6246 * @param string|CRM_Utils_Sort $sort
6247 * The order by string.
6248 * @param bool $sortByChar
6249 * If true returns the distinct array of first characters for search results.
6250 * @param null $sortOrder
6251 * Who knows? Hu knows. He who knows Hu knows who.
6252 * @param string $additionalFromClause
6253 * Should be clause with proper joins, effective to reduce where clause load.
6255 * list(string $orderByClause, string $additionalFromClause).
6257 protected function prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause) {
6259 $orderByArray = array();
6260 $config = CRM_Core_Config
::singleton();
6261 if ($config->includeOrderByClause ||
6262 isset($this->_distinctComponentClause
)
6265 if (is_string($sort)) {
6269 $orderBy = trim($sort->orderBy());
6271 // Deliberately remove the backticks again, as they mess up the evil
6272 // string munging below. This balanced by re-escaping before use.
6273 $orderBy = str_replace('`', '', $orderBy);
6275 if (!empty($orderBy)) {
6276 // this is special case while searching for
6277 // change log CRM-1718
6278 if (preg_match('/sort_name/i', $orderBy)) {
6279 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
6282 $order = " ORDER BY $orderBy";
6285 $order .= " $sortOrder";
6288 // always add contact_a.id to the ORDER clause
6289 // so the order is deterministic
6290 if (strpos('contact_a.id', $order) === FALSE) {
6291 $order .= ", contact_a.id";
6295 elseif ($sortByChar) {
6296 $orderByArray = array("UPPER(LEFT(contact_a.sort_name, 1)) asc");
6299 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
6302 if (!$order && empty($orderByArray)) {
6303 return array($order, $additionalFromClause);
6305 // Remove this here & add it at the end for simplicity.
6306 $order = trim(str_replace('ORDER BY', '', $order));
6308 // hack for order clause
6309 if (!empty($orderByArray)) {
6310 $order = implode(', ', $orderByArray);
6313 $orderByArray = explode(',', $order);
6315 foreach ($orderByArray as $orderByClause) {
6316 $orderByClauseParts = explode(' ', trim($orderByClause));
6317 $field = $orderByClauseParts[0];
6318 $direction = isset($orderByClauseParts[1]) ?
$orderByClauseParts[1] : 'asc';
6323 $this->_tables
["civicrm_address"] = $this->_whereTables
["civicrm_address"] = 1;
6324 $order = str_replace($field, "civicrm_address.{$field}", $order);
6328 case 'state_province':
6329 $this->_tables
["civicrm_{$field}"] = $this->_whereTables
["civicrm_{$field}"] = 1;
6330 if (is_array($this->_returnProperties
) && empty($this->_returnProperties
)) {
6331 $additionalFromClause .= " LEFT JOIN civicrm_{$field} ON civicrm_{$field}.id = civicrm_address.{$field}_id";
6333 $order = str_replace($field, "civicrm_{$field}.name", $order);
6337 $this->_tables
["civicrm_email"] = $this->_whereTables
["civicrm_email"] = 1;
6338 $order = str_replace($field, "civicrm_email.{$field}", $order);
6342 foreach ($this->_pseudoConstantsSelect
as $key => $pseudoConstantMetadata) {
6343 // By replacing the join to the option value table with the mysql construct
6344 // ORDER BY field('contribution_status_id', 2,1,4)
6345 // we can remove a join. In the case of the option value join it is
6346 /// a join known to cause slow queries.
6347 // @todo cover other pseudoconstant types. Limited to option group ones in the
6348 // first instance for scope reasons. They require slightly different handling as the column (label)
6349 // is not declared for them.
6350 // @todo so far only integer fields are being handled. If we add string fields we need to look at
6352 if (isset($pseudoConstantMetadata['pseudoconstant'])
6353 && isset($pseudoConstantMetadata['pseudoconstant']['optionGroupName'])
6354 && $field === CRM_Utils_Array
::value('optionGroupName', $pseudoConstantMetadata['pseudoconstant'])
6356 $sortedOptions = $pseudoConstantMetadata['bao']::buildOptions($pseudoConstantMetadata['pseudoField'], NULL, array(
6357 'orderColumn' => 'label',
6359 $order = str_replace("$field $direction", "field({$pseudoConstantMetadata['pseudoField']}," . implode(',', array_keys($sortedOptions)) . ") $direction", $order);
6361 //CRM-12565 add "`" around $field if it is a pseudo constant
6362 // This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
6363 if (!empty($pseudoConstantMetadata['element']) && $pseudoConstantMetadata['element'] == $field) {
6364 $order = str_replace($field, "`{$field}`", $order);
6370 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6371 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6373 // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
6374 // clause. But this magic helper which forgivingly reescapes ORDER BY.
6375 // Note: $sortByChar implies that $order was hard-coded/trusted, so it can do funky things.
6377 return array(' ORDER BY ' . $order, $additionalFromClause);
6380 $order = CRM_Utils_Type
::escape($order, 'MysqlOrderBy');
6381 return array(' ORDER BY ' . $order, $additionalFromClause);
6386 * Convert a string of group IDs to a string of group labels.
6388 * The original string may include duplicates and groups the user does not have
6389 * permission to see.
6391 * @param CRM_Core_DAO $dao
6392 * @param string $val
6396 public function convertGroupIDStringToLabelString(&$dao, $val) {
6397 $groupIDs = explode(',', $val);
6398 // Note that groups that the user does not have permission to will be excluded (good).
6399 $groups = array_intersect_key(CRM_Core_PseudoConstant
::group(), array_flip($groupIDs));
6400 return implode(', ', $groups);
6405 * Set the qill and where properties for a field.
6407 * This function is intended as a short-term function to encourage refactoring
6408 * & re-use - but really we should just have less special-casing.
6410 * @param string $name
6412 * @param string|array $value
6413 * @param string $grouping
6414 * @param string $field
6416 public function setQillAndWhere($name, $op, $value, $grouping, $field) {
6417 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
6418 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
6419 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(
6420 1 => $field['title'],
6427 * Has the pseudoconstant of the field been requested.
6429 * For example if the field is payment_instrument_id then it
6430 * has been requested if either payment_instrument_id or payment_instrument
6431 * have been requested. Payment_instrument is the option groun name field value.
6433 * @param array $field
6437 private function pseudoConstantNameIsInReturnProperties($field) {
6438 if (!isset($field['pseudoconstant']['optionGroupName'])) {
6442 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
6445 if (CRM_Utils_Array
::value($field['name'], $this->_returnProperties
)) {