3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
35 * This is the heart of the search query building mechanism.
37 class CRM_Contact_BAO_Query
{
40 * The various search modes.
45 NO_RETURN_PROPERTIES
= 'CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES',
51 MODE_PLEDGEBANK
= 256,
60 * The default set of return properties.
64 static $_defaultReturnProperties = NULL;
67 * The default set of hier return properties.
71 static $_defaultHierReturnProperties;
74 * The set of input params.
86 * The set of output params
90 public $_returnProperties;
100 * The name of the elements that are in the select clause
101 * used to extract the values
108 * The tables involved in the query
115 * The table involved in the where clause
119 public $_whereTables;
133 public $_whereClause;
136 * Additional permission Where Clause
140 public $_permissionWhereClause;
150 * Additional permission from clause
154 public $_permissionFromClause;
157 * The from clause for the simple select and alphabetical
162 public $_simpleFromClause;
172 * The english language version of the query
179 * All the fields that could potentially be involved in
187 * The cache to translate the option values into labels.
194 * Are we in search mode.
198 public $_search = TRUE;
201 * Should we skip permission checking.
205 public $_skipPermission = FALSE;
208 * Should we skip adding of delete clause.
212 public $_skipDeleteClause = FALSE;
215 * Are we in strict mode (use equality over LIKE)
219 public $_strict = FALSE;
222 * What operator to use to group the clauses.
226 public $_operator = 'AND';
231 * Should we only search on primary location.
235 public $_primaryLocation = TRUE;
238 * Are contact ids part of the query.
242 public $_includeContactIds = FALSE;
245 * Should we use the smart group cache.
249 public $_smartGroupCache = TRUE;
252 * Should we display contacts with a specific relationship type.
256 public $_displayRelationshipType = NULL;
259 * Reference to the query object for custom values.
263 public $_customQuery;
266 * Should we enable the distinct clause, used if we are including
267 * more than one group
271 public $_useDistinct = FALSE;
274 * Should we just display one contact record
276 public $_useGroupBy = FALSE;
279 * The relationship type direction
290 static $_activityRole;
293 * Consider the component activity type
294 * during activity search.
298 static $_considerCompActivities;
301 * Consider with contact activities only,
302 * during activity search.
306 static $_withContactActivitiesOnly;
309 * Use distinct component clause for component searches
313 public $_distinctComponentClause;
315 public $_rowCountClause;
318 * Use groupBy component clause for component searches
322 public $_groupByComponentClause;
325 * Track open panes, useful in advance search
329 public static $_openedPanes = array();
332 * For search builder - which custom fields are location-dependent
335 public $_locationSpecificCustomFields = array();
338 * The tables which have a dependency on location and/or address
342 static $_dependencies = array(
343 'civicrm_state_province' => 1,
344 'civicrm_country' => 1,
345 'civicrm_county' => 1,
346 'civicrm_address' => 1,
347 'civicrm_location_type' => 1,
351 * List of location specific fields.
353 static $_locationSpecificFields = array(
358 'supplemental_address_1',
359 'supplemental_address_2',
362 'postal_code_suffix',
376 * Remember if we handle either end of a number or date range
377 * so we can skip the other
379 protected $_rangeCache = array();
381 * Set to true when $this->relationship is run to avoid adding twice
384 protected $_relationshipValuesAdded = FALSE;
387 * Set to the name of the temp table if one has been created
390 static $_relationshipTempTable = NULL;
392 public $_pseudoConstantsSelect = array();
395 * Class constructor which also does all the work.
397 * @param array $params
398 * @param array $returnProperties
399 * @param array $fields
400 * @param bool $includeContactIds
401 * @param bool $strict
402 * @param bool|int $mode - mode the search is operating on
404 * @param bool $skipPermission
405 * @param bool $searchDescendentGroups
406 * @param bool $smartGroupCache
407 * @param null $displayRelationshipType
408 * @param string $operator
409 * @param string $apiEntity
411 * @return \CRM_Contact_BAO_Query
413 public function __construct(
414 $params = NULL, $returnProperties = NULL, $fields = NULL,
415 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
416 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
417 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
421 $this->_params
= &$params;
422 if ($this->_params
== NULL) {
423 $this->_params
= array();
426 if ($returnProperties === self
::NO_RETURN_PROPERTIES
) {
427 $this->_returnProperties
= array();
429 elseif (empty($returnProperties)) {
430 $this->_returnProperties
= self
::defaultReturnProperties($mode);
433 $this->_returnProperties
= &$returnProperties;
436 $this->_includeContactIds
= $includeContactIds;
437 $this->_strict
= $strict;
438 $this->_mode
= $mode;
439 $this->_skipPermission
= $skipPermission;
440 $this->_smartGroupCache
= $smartGroupCache;
441 $this->_displayRelationshipType
= $displayRelationshipType;
442 $this->setOperator($operator);
445 $this->_fields
= &$fields;
446 $this->_search
= FALSE;
447 $this->_skipPermission
= TRUE;
450 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE, FALSE, !$skipPermission);
452 $fields = CRM_Core_Component
::getQueryFields(!$this->_skipPermission
);
453 unset($fields['note']);
454 $this->_fields
= array_merge($this->_fields
, $fields);
456 // add activity fields
457 $fields = CRM_Activity_BAO_Activity
::exportableFields();
458 $this->_fields
= array_merge($this->_fields
, $fields);
460 // add any fields provided by hook implementers
461 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
462 $this->_fields
= array_merge($this->_fields
, $extFields);
465 // basically do all the work once, and then reuse it
466 $this->initialize($apiEntity);
470 * Function which actually does all the work for the constructor.
472 public function initialize($apiEntity = NULL) {
473 $this->_select
= array();
474 $this->_element
= array();
475 $this->_tables
= array();
476 $this->_whereTables
= array();
477 $this->_where
= array();
478 $this->_qill
= array();
479 $this->_options
= array();
480 $this->_cfIDs
= array();
481 $this->_paramLookup
= array();
482 $this->_having
= array();
484 $this->_customQuery
= NULL;
486 // reset cached static variables - CRM-5803
487 self
::$_activityRole = NULL;
488 self
::$_considerCompActivities = NULL;
489 self
::$_withContactActivitiesOnly = NULL;
491 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
492 $this->_element
['contact_id'] = 1;
493 $this->_tables
['civicrm_contact'] = 1;
495 if (!empty($this->_params
)) {
496 $this->buildParamsLookup();
499 $this->_whereTables
= $this->_tables
;
501 $this->selectClause($apiEntity);
502 $this->_whereClause
= $this->whereClause($apiEntity);
503 if (array_key_exists('civicrm_contribution', $this->_whereTables
)) {
504 $component = 'contribution';
506 if (array_key_exists('civicrm_membership', $this->_whereTables
)) {
507 $component = 'membership';
509 if (isset($component)) {
510 CRM_Financial_BAO_FinancialType
::buildPermissionedClause($this->_whereClause
, $component);
513 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
514 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
516 $this->openedSearchPanes(TRUE);
520 * Function for same purpose as convertFormValues.
522 * Like convert form values this function exists to pre-Process parameters from the form.
524 * It is unclear why they are different functions & likely relates to advances search
525 * versus search builder.
527 * The direction we are going is having the form convert values to a standardised format &
528 * moving away from wierd & wonderful where clause switches.
530 * Fix and handle contact deletion nicely.
532 * this code is primarily for search builder use case where different clauses can specify if they want deleted.
536 public function buildParamsLookup() {
537 $trashParamExists = FALSE;
538 $paramByGroup = array();
539 foreach ($this->_params
as $k => $param) {
540 if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
541 $trashParamExists = TRUE;
543 if (!empty($param[3])) {
544 $paramByGroup[$param[3]][$k] = $param;
548 if ($trashParamExists) {
549 $this->_skipDeleteClause
= TRUE;
551 //cycle through group sets and explicitly add trash param if not set
552 foreach ($paramByGroup as $setID => $set) {
554 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params
) &&
555 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params
)
557 $this->_params
[] = array(
558 'contact_is_deleted',
568 foreach ($this->_params
as $value) {
569 if (empty($value[0])) {
572 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
574 if (!array_key_exists($cfID, $this->_cfIDs
)) {
575 $this->_cfIDs
[$cfID] = array();
577 // Set wildcard value based on "and/or" selection
578 foreach ($this->_params
as $key => $param) {
579 if ($param[0] == $value[0] . '_operator') {
580 $value[4] = $param[2] == 'or';
584 $this->_cfIDs
[$cfID][] = $value;
587 if (!array_key_exists($value[0], $this->_paramLookup
)) {
588 $this->_paramLookup
[$value[0]] = array();
590 if ($value[0] !== 'group') {
591 // Just trying to unravel how group interacts here! This whole function is wieid.
592 $this->_paramLookup
[$value[0]][] = $value;
598 * Some composite fields do not appear in the fields array hack to make them part of the query.
600 public function addSpecialFields($apiEntity) {
601 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
602 // if get called via Contact.get API having address_id as return parameter
603 if ($apiEntity == 'Contact') {
604 $special[] = 'address_id';
606 foreach ($special as $name) {
607 if (!empty($this->_returnProperties
[$name])) {
608 if ($name == 'address_id') {
609 $this->_tables
['civicrm_address'] = 1;
610 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
611 $this->_element
['address_id'] = 1;
614 $this->_select
[$name] = "contact_a.{$name} as $name";
615 $this->_element
[$name] = 1;
622 * Given a list of conditions in params and a list of desired
623 * return Properties generate the required select and from
624 * clauses. Note that since the where clause introduces new
625 * tables, the initial attempt also retrieves all variables used
628 public function selectClause($apiEntity = NULL) {
630 $this->addSpecialFields($apiEntity);
632 foreach ($this->_fields
as $name => $field) {
633 // skip component fields
634 // there are done by the alter query below
635 // and need not be done on every field
637 (substr($name, 0, 12) == 'participant_') ||
638 (substr($name, 0, 7) == 'pledge_') ||
639 (substr($name, 0, 5) == 'case_') ||
640 (substr($name, 0, 13) == 'contribution_' &&
641 (strpos($name, 'source') !== FALSE && strpos($name, 'recur') !== FALSE)) ||
642 (substr($name, 0, 8) == 'payment_')
647 // redirect to activity select clause
649 (substr($name, 0, 9) == 'activity_') ||
650 ($name == 'parent_id')
652 CRM_Activity_BAO_Query
::select($this);
656 // if this is a hierarchical name, we ignore it
657 $names = explode('-', $name);
658 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
662 // make an exception for special cases, to add the field in select clause
663 $makeException = FALSE;
665 //special handling for groups/tags
666 if (in_array($name, array('groups', 'tags', 'notes'))
667 && isset($this->_returnProperties
[substr($name, 0, -1)])
669 $makeException = TRUE;
672 // since note has 3 different options we need special handling
673 // note / note_subject / note_body
674 if ($name == 'notes') {
675 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
676 if (isset($this->_returnProperties
[$noteField])) {
677 $makeException = TRUE;
683 if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id', 'communication_style_id'))) {
684 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
685 $makeException = TRUE;
689 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
690 if (!empty($this->_paramLookup
[$name]) ||
!empty($this->_returnProperties
[$name]) ||
694 // add to cfIDs array if not present
695 if (!array_key_exists($cfID, $this->_cfIDs
)) {
696 $this->_cfIDs
[$cfID] = array();
699 elseif (isset($field['where'])) {
700 list($tableName, $fieldName) = explode('.', $field['where'], 2);
701 if (isset($tableName)) {
702 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
703 $this->_tables
['civicrm_address'] = 1;
704 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
705 $this->_element
['address_id'] = 1;
708 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
709 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
711 if ($tableName == 'im_provider') {
712 CRM_Core_OptionValue
::select($this);
715 if (in_array($tableName,
716 array('email_greeting', 'postal_greeting', 'addressee'))) {
717 $this->_element
["{$name}_id"] = 1;
718 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
719 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
720 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
721 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
723 if ($tableName == 'email_greeting') {
724 $this->_pseudoConstantsSelect
[$name]['join']
725 = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
726 $this->_pseudoConstantsSelect
[$name]['join'] .=
727 " 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 ) ";
729 elseif ($tableName == 'postal_greeting') {
730 $this->_pseudoConstantsSelect
[$name]['join']
731 = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
732 $this->_pseudoConstantsSelect
[$name]['join'] .=
733 " 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 ) ";
735 elseif ($tableName == 'addressee') {
736 $this->_pseudoConstantsSelect
[$name]['join']
737 = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
738 $this->_pseudoConstantsSelect
[$name]['join'] .=
739 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
741 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
744 $greetField = "{$name}_display";
745 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
746 $this->_element
[$greetField] = 1;
748 $greetField = "{$name}_custom";
749 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
750 $this->_element
[$greetField] = 1;
754 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
755 $this->_tables
[$tableName] = 1;
758 // also get the id of the tableName
759 $tName = substr($tableName, 8);
760 if (in_array($tName, array('country', 'state_province', 'county'))) {
761 if ($tName == 'state_province') {
762 $this->_pseudoConstantsSelect
['state_province_name'] = array(
763 'pseudoField' => "{$tName}",
764 'idCol' => "{$tName}_id",
765 'bao' => 'CRM_Core_BAO_Address',
766 'table' => "civicrm_{$tName}",
767 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
770 $this->_pseudoConstantsSelect
[$tName] = array(
771 'pseudoField' => 'state_province_abbreviation',
772 'idCol' => "{$tName}_id",
773 'table' => "civicrm_{$tName}",
774 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
778 $this->_pseudoConstantsSelect
[$name] = array(
779 'pseudoField' => "{$tName}_id",
780 'idCol' => "{$tName}_id",
781 'bao' => 'CRM_Core_BAO_Address',
782 'table' => "civicrm_{$tName}",
783 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
787 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
788 $this->_element
["{$tName}_id"] = 1;
790 elseif ($tName != 'contact') {
791 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
792 $this->_element
["{$tName}_id"] = 1;
795 //special case for phone
796 if ($name == 'phone') {
797 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
798 $this->_element
['phone_type_id'] = 1;
801 // if IM then select provider_id also
802 // to get "IM Service Provider" in a file to be exported, CRM-3140
804 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
805 $this->_element
['provider_id'] = 1;
808 if ($tName == 'contact') {
809 // special case, when current employer is set for Individual contact
810 if ($fieldName == 'organization_name') {
811 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
813 elseif ($fieldName != 'id') {
814 if ($fieldName == 'prefix_id') {
815 $this->_pseudoConstantsSelect
['individual_prefix'] = array(
816 'pseudoField' => 'prefix_id',
817 'idCol' => "prefix_id",
818 'bao' => 'CRM_Contact_BAO_Contact',
821 if ($fieldName == 'suffix_id') {
822 $this->_pseudoConstantsSelect
['individual_suffix'] = array(
823 'pseudoField' => 'suffix_id',
824 'idCol' => "suffix_id",
825 'bao' => 'CRM_Contact_BAO_Contact',
828 if ($fieldName == 'gender_id') {
829 $this->_pseudoConstantsSelect
['gender'] = array(
830 'pseudoField' => 'gender_id',
831 'idCol' => "gender_id",
832 'bao' => 'CRM_Contact_BAO_Contact',
835 if ($name == 'communication_style_id') {
836 $this->_pseudoConstantsSelect
['communication_style'] = array(
837 'pseudoField' => 'communication_style_id',
838 'idCol' => "communication_style_id",
839 'bao' => 'CRM_Contact_BAO_Contact',
842 $this->_select
[$name] = "contact_a.{$fieldName} as `$name`";
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 $this->_select
[$name] = "{$field['where']} as `$name`";
861 if (!in_array($tName, array('state_province', 'country', 'county'))) {
862 $this->_element
[$name] = 1;
867 elseif ($name === 'tags') {
868 $this->_useGroupBy
= TRUE;
869 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
870 $this->_element
[$name] = 1;
871 $this->_tables
['civicrm_tag'] = 1;
872 $this->_tables
['civicrm_entity_tag'] = 1;
874 elseif ($name === 'groups') {
875 $this->_useGroupBy
= TRUE;
876 // Duplicates will be created here but better to sort them out in php land.
877 $this->_select
[$name] = "
879 GROUP_CONCAT(DISTINCT IF(civicrm_group_contact.status = 'Added', civicrm_group_contact.group_id, '')),
880 GROUP_CONCAT(DISTINCT civicrm_group_contact_cache.group_id)
883 $this->_element
[$name] = 1;
884 $this->_tables
['civicrm_group_contact'] = 1;
885 $this->_tables
['civicrm_group_contact_cache'] = 1;
886 $this->_pseudoConstantsSelect
["{$name}"] = array(
887 'pseudoField' => "groups",
891 elseif ($name === 'notes') {
892 // if note field is subject then return subject else body of the note
893 $noteColumn = 'note';
894 if (isset($noteField) && $noteField == 'note_subject') {
895 $noteColumn = 'subject';
898 $this->_useGroupBy
= TRUE;
899 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
900 $this->_element
[$name] = 1;
901 $this->_tables
['civicrm_note'] = 1;
903 elseif ($name === 'current_employer') {
904 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
905 $this->_element
[$name] = 1;
909 if ($cfID && !empty($field['is_search_range'])) {
910 // this is a custom field with range search enabled, so we better check for two/from values
911 if (!empty($this->_paramLookup
[$name . '_from'])) {
912 if (!array_key_exists($cfID, $this->_cfIDs
)) {
913 $this->_cfIDs
[$cfID] = array();
915 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
916 // search in the cdID array for the same grouping
918 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
919 if ($c[3] == $p[3]) {
920 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
925 $p[2] = array('from' => $p[2]);
926 $this->_cfIDs
[$cfID][] = $p;
930 if (!empty($this->_paramLookup
[$name . '_to'])) {
931 if (!array_key_exists($cfID, $this->_cfIDs
)) {
932 $this->_cfIDs
[$cfID] = array();
934 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
935 // search in the cdID array for the same grouping
937 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
938 if ($c[4] == $p[4]) {
939 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
944 $p[2] = array('to' => $p[2]);
945 $this->_cfIDs
[$cfID][] = $p;
952 // add location as hierarchical elements
953 $this->addHierarchicalElements();
955 // add multiple field like website
956 $this->addMultipleElements();
959 CRM_Core_Component
::alterQuery($this, 'select');
961 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
963 if (!empty($this->_cfIDs
)) {
964 // @todo This function is the select function but instead of running 'select' it
965 // is running the whole query.
966 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
967 $this->_customQuery
->query();
968 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
969 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
970 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
971 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
972 $this->_options
= $this->_customQuery
->_options
;
977 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
979 public function addHierarchicalElements() {
980 if (empty($this->_returnProperties
['location'])) {
983 if (!is_array($this->_returnProperties
['location'])) {
987 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
988 $processed = array();
991 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
992 $addressCustomFieldIds = array();
994 foreach ($this->_returnProperties
['location'] as $name => $elements) {
995 $lCond = self
::getPrimaryCondition($name);
998 $locationTypeId = array_search($name, $locationTypes);
999 if ($locationTypeId === FALSE) {
1002 $lCond = "location_type_id = $locationTypeId";
1003 $this->_useDistinct
= TRUE;
1005 //commented for CRM-3256
1006 $this->_useGroupBy
= TRUE;
1009 $name = str_replace(' ', '_', $name);
1011 $tName = "$name-location_type";
1012 $ltName = "`$name-location_type`";
1013 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1014 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
1015 $this->_element
["{$tName}_id"] = 1;
1016 $this->_element
["{$tName}"] = 1;
1018 $locationTypeName = $tName;
1019 $locationTypeJoin = array();
1021 $addAddress = FALSE;
1023 foreach ($elements as $elementFullName => $dontCare) {
1025 $elementName = $elementCmpName = $elementFullName;
1027 if (substr($elementCmpName, 0, 5) == 'phone') {
1028 $elementCmpName = 'phone';
1031 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
1032 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
1033 $addressCustomFieldIds[$cfID][$name] = 1;
1036 //add address table only once
1037 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
1039 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
1041 $tName = "$name-address";
1042 $aName = "`$name-address`";
1043 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1044 $this->_element
["{$tName}_id"] = 1;
1045 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
1046 $this->_tables
[$tName] = $addressJoin;
1047 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1048 $processed[$aName] = 1;
1052 $cond = $elementType = '';
1053 if (strpos($elementName, '-') !== FALSE) {
1054 // this is either phone, email or IM
1055 list($elementName, $elementType) = explode('-', $elementName);
1057 if (($elementName != 'phone') && ($elementName != 'im')) {
1058 $cond = self
::getPrimaryCondition($elementType);
1060 // CRM-13011 : If location type is primary, do not restrict search to the phone
1061 // type id - we want the primary phone, regardless of what type it is.
1062 // Otherwise, restrict to the specified phone type for the given field.
1063 if ((!$cond) && ($elementName == 'phone')) {
1064 $cond = "phone_type_id = '$elementType'";
1066 elseif ((!$cond) && ($elementName == 'im')) {
1067 // IM service provider id, CRM-3140
1068 $cond = "provider_id = '$elementType'";
1070 $elementType = '-' . $elementType;
1073 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
1075 // hack for profile, add location id
1078 // fix for CRM-882( to handle phone types )
1079 !is_numeric($elementType)
1081 if (is_numeric($name)) {
1082 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1085 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1088 elseif (is_numeric($name)) {
1089 //this for phone type to work
1090 if (in_array($elementName, array('phone', 'phone_ext'))) {
1091 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1094 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1098 //this is for phone type to work for profile edit
1099 if (in_array($elementName, array('phone', 'phone_ext'))) {
1100 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1103 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1108 // Check if there is a value, if so also add to where Clause
1110 if ($this->_params
) {
1112 if (isset($locationTypeId)) {
1113 $nm .= "-$locationTypeId";
1115 if (!is_numeric($elementType)) {
1116 $nm .= "$elementType";
1119 foreach ($this->_params
as $id => $values) {
1120 if ((is_array($values) && $values[0] == $nm) ||
1121 (in_array($elementName, array('phone', 'im'))
1122 && (strpos($values[0], $nm) !== FALSE)
1132 if ($field && isset($field['where'])) {
1133 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1134 $pf = substr($tableName, 8);
1135 $tName = $name . '-' . $pf . $elementType;
1136 if (isset($tableName)) {
1137 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1138 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1141 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1144 $this->_element
["{$tName}_id"] = 1;
1145 if (substr($tName, -15) == '-state_province') {
1146 // FIXME: hack to fix CRM-1900
1147 $a = Civi
::settings()->get('address_format');
1149 if (substr_count($a, 'state_province_name') > 0) {
1150 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1151 'pseudoField' => "{$pf}_id",
1152 'idCol' => "{$tName}_id",
1153 'bao' => 'CRM_Core_BAO_Address',
1155 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1158 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1159 'pseudoField' => 'state_province_abbreviation',
1160 'idCol' => "{$tName}_id",
1162 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1166 if (substr($elementFullName, 0, 2) == 'im') {
1167 $provider = "{$name}-{$elementFullName}-provider_id";
1168 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1169 $this->_element
[$provider] = 1;
1171 if ($pf == 'country' ||
$pf == 'county') {
1172 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1173 'pseudoField' => "{$pf}_id",
1174 'idCol' => "{$tName}_id",
1175 'bao' => 'CRM_Core_BAO_Address',
1177 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1180 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1184 if (in_array($pf, array('state_province', 'country', 'county'))) {
1185 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1188 $this->_element
["{$name}-{$elementFullName}"] = 1;
1191 if (empty($processed["`$tName`"])) {
1192 $processed["`$tName`"] = 1;
1193 $newName = $tableName . '_' . $index;
1194 switch ($tableName) {
1195 case 'civicrm_phone':
1196 case 'civicrm_email':
1198 case 'civicrm_openid':
1200 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1201 if ($tableName != 'civicrm_phone') {
1202 $this->_tables
[$tName] .= " AND `$tName`.$lCond";
1204 elseif (is_numeric($name)) {
1205 $this->_select
[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1208 // this special case to add phone type
1210 $phoneTypeCondition = " AND `$tName`.$cond ";
1211 //gross hack to pickup corrupted data also, CRM-7603
1212 if (strpos($cond, 'phone_type_id') !== FALSE) {
1213 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1214 if (!empty($lCond)) {
1215 $phoneTypeCondition .= " AND ( `$tName`.$lCond ) ";
1218 $this->_tables
[$tName] .= $phoneTypeCondition;
1221 //build locationType join
1222 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1225 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1229 case 'civicrm_state_province':
1230 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1231 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1232 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1234 $this->_whereTables
["{$name}-address"] = $addressJoin;
1238 case 'civicrm_country':
1239 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1240 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1241 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1243 $this->_whereTables
["{$name}-address"] = $addressJoin;
1247 case 'civicrm_county':
1248 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1249 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1250 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1252 $this->_whereTables
["{$name}-address"] = $addressJoin;
1258 $this->_whereTables
["{$name}-address"] = $addressJoin;
1267 // add location type join
1268 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1269 $this->_tables
[$locationTypeName] = $ltypeJoin;
1271 // table should be present in $this->_whereTables,
1272 // to add its condition in location type join, CRM-3939.
1273 if ($addWhereCount) {
1274 $locClause = array();
1275 foreach ($this->_whereTables
as $tableName => $clause) {
1276 if (!empty($locationTypeJoin[$tableName])) {
1277 $locClause[] = $locationTypeJoin[$tableName];
1281 if (!empty($locClause)) {
1282 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1287 if (!empty($addressCustomFieldIds)) {
1288 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1289 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1290 foreach ($locTypeName as $name => $dnc) {
1291 $this->_locationSpecificCustomFields
[$cfID] = array($name, array_search($name, $locationTypes));
1292 $fieldName = "$name-custom_{$cfID}";
1293 $tName = "$name-address-custom-{$cfID}";
1294 $aName = "`$name-address-custom-{$cfID}`";
1295 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1296 $this->_element
["{$tName}_id"] = 1;
1297 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1298 $this->_element
[$fieldName] = 1;
1299 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1306 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1308 public function addMultipleElements() {
1309 if (empty($this->_returnProperties
['website'])) {
1312 if (!is_array($this->_returnProperties
['website'])) {
1316 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1317 foreach ($elements as $elementFullName => $dontCare) {
1318 $tName = "website-{$key}-{$elementFullName}";
1319 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1320 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1321 $this->_element
["{$tName}_id"] = 1;
1322 $this->_element
["{$tName}"] = 1;
1324 $type = "website-{$key}-website_type_id";
1325 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1326 $this->_element
[$type] = 1;
1327 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1333 * Generate the query based on what type of query we need.
1335 * @param bool $count
1336 * @param bool $sortByChar
1337 * @param bool $groupContacts
1338 * @param bool $onlyDeleted
1341 * sql query parts as an array
1343 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1344 // build permission clause
1345 $this->generatePermissionClause($onlyDeleted, $count);
1348 if (isset($this->_rowCountClause
)) {
1349 $select = "SELECT {$this->_rowCountClause}";
1351 elseif (isset($this->_distinctComponentClause
)) {
1352 // we add distinct to get the right count for components
1353 // for the more complex result set, we use GROUP BY the same id
1355 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} ) as rowCount";
1358 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1360 $from = $this->_simpleFromClause
;
1361 if ($this->_useDistinct
) {
1362 $this->_useGroupBy
= TRUE;
1365 elseif ($sortByChar) {
1366 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1367 $from = $this->_simpleFromClause
;
1369 elseif ($groupContacts) {
1370 $select = 'SELECT contact_a.id as id';
1371 if ($this->_useDistinct
) {
1372 $this->_useGroupBy
= TRUE;
1374 $from = $this->_simpleFromClause
;
1377 if (!empty($this->_paramLookup
['group'])) {
1379 list($name, $op, $value, $grouping, $wildcard) = $this->_paramLookup
['group'][0];
1381 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
1382 $this->_paramLookup
['group'][0][1] = key($value);
1385 // Presumably the lines below come into manage groups screen.
1386 // make sure there is only one element
1387 // this is used when we are running under smog and need to know
1388 // how the contact was added (CRM-1203)
1389 $groups = (array) CRM_Utils_Array
::value($this->_paramLookup
['group'][0][1], $this->_paramLookup
['group'][0][2], $this->_paramLookup
['group'][0][2]);
1390 if ((count($this->_paramLookup
['group']) == 1) &&
1391 (count($groups) == 1)
1393 $groupId = $groups[0];
1395 //check if group is saved search
1396 $group = new CRM_Contact_BAO_Group();
1397 $group->id
= $groupId;
1400 if (!isset($group->saved_search_id
)) {
1401 $tbName = "`civicrm_group_contact-{$groupId}`";
1402 // CRM-17254 don't retrieve extra fields if contact_id is specifically requested
1403 // as this will add load to an intentionally light query.
1404 // ideally this code would be removed as it appears to be to support CRM-1203
1405 // and passing in the required returnProperties from the url would
1406 // make more sense that globally applying the requirements of one form.
1407 if (($this->_returnProperties
!= array('contact_id'))) {
1408 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1409 $this->_element
['group_contact_id'] = 1;
1410 $this->_select
['status'] = "$tbName.status as status";
1411 $this->_element
['status'] = 1;
1415 $this->_useGroupBy
= TRUE;
1417 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1418 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1420 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1421 $this->_useDistinct
= FALSE;
1422 $this->_useGroupBy
= TRUE;
1426 $select = "SELECT ";
1427 if (isset($this->_distinctComponentClause
)) {
1428 $select .= "{$this->_distinctComponentClause}, ";
1430 $select .= implode(', ', $this->_select
);
1431 $from = $this->_fromClause
;
1435 if (!empty($this->_whereClause
)) {
1436 $where = "WHERE {$this->_whereClause}";
1439 if (!empty($this->_permissionWhereClause
) && empty($this->_displayRelationshipType
)) {
1440 if (empty($where)) {
1441 $where = "WHERE $this->_permissionWhereClause";
1444 $where = "$where AND $this->_permissionWhereClause";
1449 if (!empty($this->_having
)) {
1450 foreach ($this->_having
as $havingSets) {
1451 foreach ($havingSets as $havingSet) {
1452 $havingValue[] = $havingSet;
1455 $having = ' HAVING ' . implode(' AND ', $havingValue);
1458 // if we are doing a transform, do it here
1459 // use the $from, $where and $having to get the contact ID
1460 if ($this->_displayRelationshipType
) {
1461 $this->filterRelatedContacts($from, $where, $having);
1464 return array($select, $from, $where, $having);
1468 * Get where values from the parameters.
1470 * @param string $name
1471 * @param mixed $grouping
1475 public function getWhereValues($name, $grouping) {
1477 foreach ($this->_params
as $values) {
1478 if ($values[0] == $name && $values[3] == $grouping) {
1489 * @param bool $relative
1490 * @param string $from
1493 public static function fixDateValues($relative, &$from, &$to) {
1495 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1500 * Convert values from form-appropriate to query-object appropriate.
1502 * The query object is increasingly supporting the sql-filter syntax which is the most flexible syntax.
1503 * So, ideally we would convert all fields to look like
1506 * // Set the operator for legacy reasons, but it is ignored
1508 * // array in sql filter syntax
1509 * 2 => array('BETWEEN' => array(1,60),
1514 * There are some examples of the syntax in
1515 * https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples/Relationship
1517 * More notes at CRM_Core_DAO::createSQLFilter
1519 * and a list of supported operators in CRM_Core_DAO
1521 * @param array $formValues
1522 * @param int $wildcard
1523 * @param bool $useEquals
1525 * @param string $apiEntity
1527 * @param array $entityReferenceFields
1528 * Field names of any entity reference fields (which will need reformatting to IN syntax).
1532 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL,
1533 $entityReferenceFields = array()) {
1535 if (empty($formValues)) {
1539 self
::filterCountryFromValuesIfStateExists($formValues);
1541 foreach ($formValues as $id => &$val) {
1542 // CRM-19374 - we don't want to change $val in $formValues.
1543 // Assign it to a temp variable which operates while iteration.
1546 if (self
::isAlreadyProcessedForQueryFormat($values)) {
1547 $params[] = $values;
1551 self
::legacyConvertFormValues($id, $values);
1553 // The form uses 1 field to represent two db fields
1554 if ($id == 'contact_type' && $values && (!is_array($values) ||
!array_intersect(array_keys($values), CRM_Core_DAO
::acceptedSQLOperators()))) {
1555 $contactType = array();
1557 foreach ((array) $values as $key => $type) {
1558 $types = explode('__', is_numeric($type) ?
$key : $type);
1559 $contactType[$types[0]] = $types[0];
1560 // Add sub-type if specified
1561 if (!empty($types[1])) {
1562 $subType[$types[1]] = $types[1];
1565 $params[] = array('contact_type', 'IN', $contactType, 0, 0);
1567 $params[] = array('contact_sub_type', 'IN', $subType, 0, 0);
1570 elseif ($id == 'privacy') {
1571 if (is_array($formValues['privacy'])) {
1572 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1573 foreach ($formValues['privacy'] as $key => $value) {
1575 $params[] = array($key, $op, $value, 0, 0);
1580 elseif ($id == 'email_on_hold') {
1581 if ($formValues['email_on_hold']['on_hold']) {
1582 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1585 elseif (substr($id, 0, 7) == 'custom_'
1587 substr($id, -9, 9) == '_relative'
1588 ||
substr($id, -5, 5) == '_from'
1589 ||
substr($id, -3, 3) == '_to'
1592 self
::convertCustomRelativeFields($formValues, $params, $values, $id);
1594 elseif (preg_match('/_date_relative$/', $id) ||
1595 $id == 'event_relative' ||
1596 $id == 'case_from_relative' ||
1597 $id == 'case_to_relative' ||
1598 $id == 'participant_relative'
1600 if ($id == 'event_relative') {
1601 $fromRange = 'event_start_date_low';
1602 $toRange = 'event_end_date_high';
1604 elseif ($id == 'participant_relative') {
1605 $fromRange = 'participant_register_date_low';
1606 $toRange = 'participant_register_date_high';
1608 elseif ($id == 'case_from_relative') {
1609 $fromRange = 'case_from_start_date_low';
1610 $toRange = 'case_from_start_date_high';
1612 elseif ($id == 'case_to_relative') {
1613 $fromRange = 'case_to_end_date_low';
1614 $toRange = 'case_to_end_date_high';
1617 $dateComponent = explode('_date_relative', $id);
1618 $fromRange = "{$dateComponent[0]}_date_low";
1619 $toRange = "{$dateComponent[0]}_date_high";
1622 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1623 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1627 elseif (in_array($id, $entityReferenceFields) && !empty($values) && is_string($values) && (strpos($values, ',') !=
1629 $params[] = array($id, 'IN', explode(',', $values), 0, 0);
1632 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
1637 $params[] = $values;
1644 * Function to support legacy format for groups and tags.
1647 * @param array|int $values
1650 public static function legacyConvertFormValues($id, &$values) {
1651 $legacyElements = array(
1656 'membership_type_id',
1657 'membership_status_id',
1659 if (in_array($id, $legacyElements) && is_array($values)) {
1660 // prior to 4.7, formValues for some attributes (e.g. group, tag) are stored in array(id1 => 1, id2 => 1),
1661 // as per the recent Search fixes $values need to be in standard array(id1, id2) format
1662 $values = CRM_Utils_Array
::convertCheckboxFormatToArray($values);
1667 * Fix values from query from/to something no-one cared enough to document.
1670 * @param array $values
1671 * @param int $wildcard
1672 * @param bool $useEquals
1674 * @param string $apiEntity
1676 * @return array|null
1678 public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1679 // skip a few search variables
1680 static $skipWhere = NULL;
1681 static $likeNames = NULL;
1684 // Change camelCase EntityName to lowercase with underscores
1685 $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity);
1687 // check if $value is in OK (Operator as Key) format as used by Get API
1688 if (CRM_Utils_System
::isNull($values)) {
1700 'display_relationship_type',
1704 if (in_array($id, $skipWhere) ||
1705 substr($id, 0, 4) == '_qf_' ||
1706 substr($id, 0, 7) == 'hidden_'
1712 (substr($id, 0, strlen($apiEntity)) != $apiEntity) &&
1713 (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_') &&
1714 (substr($id, 0, 7) != 'custom_')
1716 $id = $apiEntity . '_' . $id;
1720 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1723 // email comes in via advanced search
1724 // so use wildcard always
1725 if ($id == 'email') {
1729 if (!$useEquals && in_array($id, $likeNames)) {
1730 $result = array($id, 'LIKE', $values, 0, 1);
1732 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1733 $result = array($id, 'LIKE', $values, 0, 0);
1735 elseif ($id == 'contact_type' ||
1736 (!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO
::acceptedSQLOperators(), TRUE))
1738 $result = array($id, 'IN', $values, 0, $wildcard);
1741 $result = array($id, '=', $values, 0, $wildcard);
1748 * Get the where clause for a single field.
1750 * @param array $values
1751 * @param string $apiEntity
1753 public function whereClauseSingle(&$values, $apiEntity = NULL) {
1754 // do not process custom fields or prefixed contact ids or component params
1755 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1756 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1757 (substr($values[0], 0, 13) == 'contribution_') ||
1758 (substr($values[0], 0, 6) == 'event_') ||
1759 (substr($values[0], 0, 12) == 'participant_') ||
1760 (substr($values[0], 0, 7) == 'member_') ||
1761 (substr($values[0], 0, 6) == 'grant_') ||
1762 (substr($values[0], 0, 7) == 'pledge_') ||
1763 (substr($values[0], 0, 5) == 'case_') ||
1764 (substr($values[0], 0, 10) == 'financial_') ||
1765 (substr($values[0], 0, 8) == 'payment_') ||
1766 (substr($values[0], 0, 11) == 'membership_')
1771 // skip for hook injected fields / params
1772 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1773 if (array_key_exists($values[0], $extFields)) {
1777 switch ($values[0]) {
1778 case 'deleted_contacts':
1779 $this->deletedContacts($values);
1782 case 'contact_sub_type':
1783 $this->contactSubType($values);
1787 $this->group($values);
1791 // so we resolve this into a list of groups & proceed as if they had been
1793 list($name, $op, $value, $grouping, $wildcard) = $values;
1794 $values[0] = 'group';
1796 $this->_paramLookup
['group'][0][0] = 'group';
1797 $this->_paramLookup
['group'][0][1] = 'IN';
1798 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1799 $this->group($values);
1802 // case tag comes from find contacts
1804 $this->tagSearch($values);
1808 case 'contact_tags':
1809 $this->tag($values);
1814 case 'note_subject':
1815 $this->notes($values);
1819 $this->ufUser($values);
1823 case 'display_name':
1824 $this->sortName($values);
1828 case 'postal_greeting':
1829 case 'email_greeting':
1830 $this->greetings($values);
1835 $this->email($values, $apiEntity);
1838 case 'phone_numeric':
1839 $this->phone_numeric($values);
1842 case 'phone_phone_type_id':
1843 case 'phone_location_type_id':
1844 $this->phone_option_group($values);
1847 case 'street_address':
1848 $this->street_address($values);
1851 case 'street_number':
1852 $this->street_number($values);
1855 case 'sortByCharacter':
1856 $this->sortByCharacter($values);
1859 case 'location_type':
1860 $this->locationType($values);
1864 $this->county($values);
1867 case 'state_province':
1868 case 'state_province_id':
1869 case 'state_province_name':
1870 $this->stateProvince($values);
1875 $this->country($values, FALSE);
1879 case 'postal_code_low':
1880 case 'postal_code_high':
1881 $this->postalCode($values);
1884 case 'activity_date':
1885 case 'activity_date_low':
1886 case 'activity_date_high':
1887 case 'activity_role':
1888 case 'activity_status_id':
1889 case 'activity_status':
1890 case 'followup_parent_id':
1892 case 'source_contact_id':
1893 case 'activity_subject':
1894 case 'test_activities':
1895 case 'activity_type_id':
1896 case 'activity_type':
1897 case 'activity_survey_id':
1898 case 'activity_tags':
1899 case 'activity_taglist':
1900 case 'activity_test':
1901 case 'activity_campaign_id':
1902 case 'activity_engagement_level':
1904 case 'activity_result':
1905 case 'source_contact':
1906 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1911 case 'birth_date_low':
1912 case 'birth_date_high':
1913 case 'deceased_date_low':
1914 case 'deceased_date_high':
1915 $this->demographics($values);
1918 case 'age_asof_date':
1919 // handled by demographics
1922 case 'log_date_low':
1923 case 'log_date_high':
1924 $this->modifiedDates($values);
1928 $this->changeLog($values);
1931 case 'do_not_phone':
1932 case 'do_not_email':
1935 case 'do_not_trade':
1937 $this->privacy($values);
1940 case 'privacy_options':
1941 $this->privacyOptions($values);
1944 case 'privacy_operator':
1945 case 'privacy_toggle':
1946 // these are handled by privacy options
1949 case 'preferred_communication_method':
1950 $this->preferredCommunication($values);
1953 case 'relation_type_id':
1954 case 'relation_start_date_high':
1955 case 'relation_start_date_low':
1956 case 'relation_end_date_high':
1957 case 'relation_end_date_low':
1958 case 'relation_target_name':
1959 case 'relation_status':
1960 case 'relation_date_low':
1961 case 'relation_date_high':
1962 $this->relationship($values);
1963 $this->_relationshipValuesAdded
= TRUE;
1966 case 'task_status_id':
1967 $this->task($values);
1971 // since this case is handled with the above
1974 case 'prox_distance':
1975 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1978 case 'prox_street_address':
1980 case 'prox_postal_code':
1981 case 'prox_state_province_id':
1982 case 'prox_country_id':
1983 // handled by the proximity_distance clause
1987 $this->restWhere($values);
1993 * Given a list of conditions in params generate the required where clause.
1995 * @param string $apiEntity
1999 public function whereClause($apiEntity = NULL) {
2000 $this->_where
[0] = array();
2001 $this->_qill
[0] = array();
2003 $this->includeContactIds();
2004 if (!empty($this->_params
)) {
2005 foreach (array_keys($this->_params
) as $id) {
2006 if (empty($this->_params
[$id][0])) {
2009 // check for both id and contact_id
2010 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
2011 $this->_where
[0][] = self
::buildClause("contact_a.id", $this->_params
[$id][1], $this->_params
[$id][2]);
2014 $this->whereClauseSingle($this->_params
[$id], $apiEntity);
2018 CRM_Core_Component
::alterQuery($this, 'where');
2020 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
2023 if ($this->_customQuery
) {
2024 // Added following if condition to avoid the wrong value display for 'my account' / any UF info.
2025 // Hope it wont affect the other part of civicrm.. if it does please remove it.
2026 if (!empty($this->_customQuery
->_where
)) {
2027 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
2030 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
2034 $andClauses = array();
2037 if (!empty($this->_where
)) {
2038 foreach ($this->_where
as $grouping => $values) {
2039 if ($grouping > 0 && !empty($values)) {
2040 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
2045 if (!empty($this->_where
[0])) {
2046 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
2048 if (!empty($clauses)) {
2049 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
2052 if ($validClauses > 1) {
2053 $this->_useDistinct
= TRUE;
2057 return implode(' AND ', $andClauses);
2061 * Generate where clause for any parameters not already handled.
2063 * @param array $values
2067 public function restWhere(&$values) {
2068 $name = CRM_Utils_Array
::value(0, $values);
2069 $op = CRM_Utils_Array
::value(1, $values);
2070 $value = CRM_Utils_Array
::value(2, $values);
2071 $grouping = CRM_Utils_Array
::value(3, $values);
2072 $wildcard = CRM_Utils_Array
::value(4, $values);
2074 if (isset($grouping) && empty($this->_where
[$grouping])) {
2075 $this->_where
[$grouping] = array();
2078 $multipleFields = array('url');
2080 //check if the location type exists for fields
2082 $locType = explode('-', $name);
2084 if (!in_array($locType[0], $multipleFields)) {
2085 //add phone type if exists
2086 if (isset($locType[2]) && $locType[2]) {
2087 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
2091 $field = CRM_Utils_Array
::value($name, $this->_fields
);
2094 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
2103 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2104 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2105 if (isset($locType[1]) && is_numeric($locType[1])) {
2106 $lType = $locationType[$locType[1]];
2109 $field['title'] .= " ($lType)";
2112 if (substr($name, 0, 14) === 'state_province') {
2113 if (isset($locType[1]) && is_numeric($locType[1])) {
2115 $aName = "{$lType}-address";
2116 $where = "`$aName`.state_province_id";
2119 $where = "civicrm_address.state_province_id";
2122 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value);
2123 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
2124 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
2126 elseif (!empty($field['pseudoconstant'])) {
2127 $this->optionValueQuery(
2128 $name, $op, $value, $grouping,
2129 'CRM_Contact_DAO_Contact',
2135 if ($name == 'gender_id') {
2136 self
::$_openedPanes[ts('Demographics')] = TRUE;
2139 elseif (substr($name, 0, 7) === 'country' ||
substr($name, 0, 6) === 'county') {
2140 $name = (substr($name, 0, 7) === 'country') ?
"country_id" : "county_id";
2141 if (isset($locType[1]) && is_numeric($locType[1])) {
2143 $aName = "{$lType}-address";
2144 $where = "`$aName`.$name";
2147 $where = "civicrm_address.$name";
2150 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2152 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
2153 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
2155 elseif ($name === 'world_region') {
2156 $this->optionValueQuery(
2157 $name, $op, $value, $grouping,
2165 elseif ($name === 'is_deceased') {
2166 $this->setQillAndWhere($name, $op, $value, $grouping, $field);
2167 self
::$_openedPanes[ts('Demographics')] = TRUE;
2169 elseif ($name === 'created_date' ||
$name === 'modified_date' ||
$name === 'deceased_date' ||
$name === 'birth_date') {
2170 $appendDateTime = TRUE;
2171 if ($name === 'deceased_date' ||
$name === 'birth_date') {
2172 $appendDateTime = FALSE;
2173 self
::$_openedPanes[ts('Demographics')] = TRUE;
2175 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2177 elseif ($name === 'contact_id') {
2178 if (is_int($value)) {
2179 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2180 $this->_qill
[$grouping][] = "$field[title] $op $value";
2183 elseif ($name === 'name') {
2184 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2187 $value = self
::getWildCardedValue($wildcard, $op, $value);
2189 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2190 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2191 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2193 elseif ($name === 'current_employer') {
2194 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2197 $value = self
::getWildCardedValue($wildcard, $op, $value);
2199 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
2200 $ceWhereClause = self
::buildClause($wc, $op,
2203 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2204 $this->_where
[$grouping][] = $ceWhereClause;
2205 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2207 elseif ($name === 'email_greeting') {
2208 $filterCondition = array('greeting_type' => 'email_greeting');
2209 $this->optionValueQuery(
2210 $name, $op, $value, $grouping,
2211 CRM_Core_PseudoConstant
::greeting($filterCondition),
2213 ts('Email Greeting')
2216 elseif ($name === 'postal_greeting') {
2217 $filterCondition = array('greeting_type' => 'postal_greeting');
2218 $this->optionValueQuery(
2219 $name, $op, $value, $grouping,
2220 CRM_Core_PseudoConstant
::greeting($filterCondition),
2222 ts('Postal Greeting')
2225 elseif ($name === 'addressee') {
2226 $filterCondition = array('greeting_type' => 'addressee');
2227 $this->optionValueQuery(
2228 $name, $op, $value, $grouping,
2229 CRM_Core_PseudoConstant
::greeting($filterCondition),
2234 elseif (substr($name, 0, 4) === 'url-') {
2235 $tName = 'civicrm_website';
2236 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2237 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2240 $value = self
::getWildCardedValue($wildcard, $op, $value);
2243 $this->_where
[$grouping][] = $d = self
::buildClause('civicrm_website.url', $op, $value);
2244 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2246 elseif ($name === 'contact_is_deleted') {
2247 $this->setQillAndWhere('is_deleted', $op, $value, $grouping, $field);
2249 elseif (!empty($field['where'])) {
2251 if (!empty($field['type'])) {
2252 $type = CRM_Utils_Type
::typeToString($field['type']);
2255 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2257 if (isset($locType[1]) &&
2258 is_numeric($locType[1])
2262 //get the location name
2263 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2265 $fieldName = "LOWER(`$tName`.$fldName)";
2267 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2268 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2272 if ($tableName == 'civicrm_contact') {
2273 $fieldName = "LOWER(contact_a.{$fieldName})";
2276 if ($op != 'IN' && !is_numeric($value) && !is_array($value)) {
2277 $fieldName = "LOWER({$field['where']})";
2280 $fieldName = "{$field['where']}";
2285 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2286 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(
2287 1 => $field['title'],
2289 3 => (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) ?
$qillVal : "'$qillVal'"));
2291 if (is_array($value)) {
2292 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2293 // for api style operators for functions that hit this point without worrying about regression
2294 // (the previous comments indicated the condition for hitting this point were unknown
2295 // per CRM-14743 we are adding modified_date & created_date operator support
2296 $operations = array_keys($value);
2297 foreach ($operations as $operator) {
2298 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2299 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2300 //so this condition will satisfy the search for now
2301 if (strpos($op, 'IN') !== FALSE) {
2302 $value = array($op => $value);
2304 // we don't know when this might happen
2306 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $operator)));
2310 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($fieldName, $value, $type);
2313 if (!strpos($op, 'IN')) {
2314 $value = $strtolower($value);
2318 $value = self
::getWildCardedValue($wildcard, $op, $value);
2321 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2325 if ($setTables && isset($field['where'])) {
2326 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2327 if (isset($tableName)) {
2328 $this->_tables
[$tableName] = 1;
2329 $this->_whereTables
[$tableName] = 1;
2342 public static function getLocationTableName(&$where, &$locType) {
2343 if (isset($locType[1]) && is_numeric($locType[1])) {
2344 list($tbName, $fldName) = explode(".", $where);
2346 //get the location name
2347 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2348 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2349 if (in_array($locType[0], $specialFields)) {
2350 //hack to fix / special handing for phone_ext
2351 if ($locType[0] == 'phone_ext') {
2352 $locType[0] = 'phone';
2354 if (isset($locType[2]) && $locType[2]) {
2355 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2358 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2361 elseif (in_array($locType[0],
2366 'street_number_suffix',
2368 'supplemental_address_1',
2369 'supplemental_address_2',
2372 'postal_code_suffix',
2378 //fix for search by profile with address fields.
2379 $tName = "{$locationType[$locType[1]]}-address";
2381 elseif (in_array($locType[0],
2389 $tName = "{$locationType[$locType[1]]}-email";
2391 elseif ($locType[0] == 'provider_id') {
2392 $tName = "{$locationType[$locType[1]]}-im";
2394 elseif ($locType[0] == 'openid') {
2395 $tName = "{$locationType[$locType[1]]}-openid";
2398 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2400 $tName = str_replace(' ', '_', $tName);
2401 return array($tName, $fldName);
2403 CRM_Core_Error
::fatal();
2407 * Given a result dao, extract the values and return that array
2409 * @param CRM_Core_DAO $dao
2412 * values for this query
2414 public function store($dao) {
2417 foreach ($this->_element
as $key => $dontCare) {
2418 if (property_exists($dao, $key)) {
2419 if (strpos($key, '-') !== FALSE) {
2420 $values = explode('-', $key);
2421 $lastElement = array_pop($values);
2423 $cnt = count($values);
2425 foreach ($values as $v) {
2426 if (!array_key_exists($v, $current)) {
2427 $current[$v] = array();
2429 //bad hack for im_provider
2430 if ($lastElement == 'provider_id') {
2431 if ($count < $cnt) {
2432 $current = &$current[$v];
2435 $lastElement = "{$v}_{$lastElement}";
2439 $current = &$current[$v];
2444 $current[$lastElement] = $dao->$key;
2447 $value[$key] = $dao->$key;
2455 * Getter for tables array.
2459 public function tables() {
2460 return $this->_tables
;
2464 * Where tables is sometimes used to create the from clause, but, not reliably, set this AND set tables
2465 * It's unclear the intent - there is a 'simpleFrom' clause which takes whereTables into account & a fromClause which doesn't
2466 * logic may have eroded
2469 public function whereTables() {
2470 return $this->_whereTables
;
2474 * Generate the where clause (used in match contacts and permissions)
2476 * @param array $params
2477 * @param array $fields
2478 * @param array $tables
2479 * @param $whereTables
2480 * @param bool $strict
2484 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2485 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2489 $tables = array_merge($query->tables(), $tables);
2490 $whereTables = array_merge($query->whereTables(), $whereTables);
2492 return $query->_whereClause
;
2496 * Create the from clause.
2498 * @param array $tables
2499 * Tables that need to be included in this from clause.
2500 * if null, return mimimal from clause (i.e. civicrm_contact)
2501 * @param array $inner
2502 * Tables that should be inner-joined.
2503 * @param array $right
2504 * Tables that should be right-joined.
2506 * @param bool $primaryLocation
2512 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2514 $from = ' FROM civicrm_contact contact_a';
2515 if (empty($tables)) {
2519 if (!empty($tables['civicrm_worldregion'])) {
2520 $tables = array_merge(array('civicrm_country' => 1), $tables);
2523 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2524 CRM_Utils_Array
::value('civicrm_county', $tables)
2525 ) && empty($tables['civicrm_address'])
2527 $tables = array_merge(array('civicrm_address' => 1),
2532 // add group_contact and group table is subscription history is present
2533 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2534 $tables = array_merge(array(
2535 'civicrm_group' => 1,
2536 'civicrm_group_contact' => 1,
2542 // to handle table dependencies of components
2543 CRM_Core_Component
::tableNames($tables);
2544 // to handle table dependencies of hook injected tables
2545 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2547 //format the table list according to the weight
2548 $info = CRM_Core_TableHierarchy
::info();
2550 foreach ($tables as $key => $value) {
2552 if (strpos($key, '-') !== FALSE) {
2553 $keyArray = explode('-', $key);
2554 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2556 elseif (strpos($key, '_') !== FALSE) {
2557 $keyArray = explode('_', $key);
2558 if (is_numeric(array_pop($keyArray))) {
2559 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2562 $k = CRM_Utils_Array
::value($key, $info, 99);
2566 $k = CRM_Utils_Array
::value($key, $info, 99);
2568 $tempTable[$k . ".$key"] = $key;
2571 $newTables = array();
2572 foreach ($tempTable as $key) {
2573 $newTables[$key] = $tables[$key];
2576 $tables = $newTables;
2578 foreach ($tables as $name => $value) {
2583 if (!empty($inner[$name])) {
2586 elseif (!empty($right[$name])) {
2594 // if there is already a join statement in value, use value itself
2595 if (strpos($value, 'JOIN')) {
2596 $from .= " $value ";
2599 $from .= " $side JOIN $name ON ( $value ) ";
2604 case 'civicrm_address':
2605 if ($primaryLocation) {
2606 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2609 //CRM-14263 further handling of address joins further down...
2610 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2614 case 'civicrm_phone':
2615 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2618 case 'civicrm_email':
2619 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2623 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2627 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2628 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2629 $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)";
2632 case 'civicrm_openid':
2633 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2636 case 'civicrm_worldregion':
2637 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2638 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2641 case 'civicrm_location_type':
2642 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2645 case 'civicrm_group':
2646 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2649 case 'civicrm_group_contact':
2650 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2653 case 'civicrm_group_contact_cache':
2654 $from .= " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
2657 case 'civicrm_activity':
2658 case 'civicrm_activity_tag':
2659 case 'activity_type':
2660 case 'activity_status':
2662 case 'civicrm_activity_contact':
2663 case 'source_contact':
2664 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2667 case 'civicrm_entity_tag':
2668 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2669 civicrm_entity_tag.entity_id = contact_a.id ) ";
2672 case 'civicrm_note':
2673 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2674 contact_a.id = civicrm_note.entity_id ) ";
2677 case 'civicrm_subscription_history':
2678 $from .= " $side JOIN civicrm_subscription_history
2679 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2680 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2683 case 'civicrm_relationship':
2684 if (self
::$_relType == 'reciprocal') {
2685 if (self
::$_relationshipTempTable) {
2686 // we have a temptable to join on
2687 $tbl = self
::$_relationshipTempTable;
2688 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2691 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2692 $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)";
2695 elseif (self
::$_relType == 'b') {
2696 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2697 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2700 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2701 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2706 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2707 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2711 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2714 case 'civicrm_grant':
2715 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2718 case 'civicrm_website':
2719 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2723 $locationTypeName = '';
2724 if (strpos($name, '-address') != 0) {
2725 $locationTypeName = 'address';
2727 elseif (strpos($name, '-phone') != 0) {
2728 $locationTypeName = 'phone';
2730 elseif (strpos($name, '-email') != 0) {
2731 $locationTypeName = 'email';
2733 elseif (strpos($name, '-im') != 0) {
2734 $locationTypeName = 'im';
2736 elseif (strpos($name, '-openid') != 0) {
2737 $locationTypeName = 'openid';
2740 if ($locationTypeName) {
2741 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2742 $parts = explode('-', $name);
2743 $locationID = array_search($parts[0], CRM_Core_BAO_Address
::buildOptions('location_type_id', 'get', array('name' => $parts[0])));
2744 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2747 $from .= CRM_Core_Component
::from($name, $mode, $side);
2749 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2758 * WHERE / QILL clause for deleted_contacts
2760 * @param array $values
2762 public function deletedContacts($values) {
2763 list($_, $_, $value, $grouping, $_) = $values;
2765 // *prepend* to the relevant grouping as this is quite an important factor
2766 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2771 * Where / qill clause for contact_type
2775 public function contactType(&$values) {
2776 list($name, $op, $value, $grouping, $wildcard) = $values;
2778 $subTypes = array();
2781 // account for search builder mapping multiple values
2782 if (!is_array($value)) {
2783 $values = self
::parseSearchBuilderString($value, 'String');
2784 if (is_array($values)) {
2785 $value = array_flip($values);
2789 if (is_array($value)) {
2790 foreach ($value as $k => $v) {
2795 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2796 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2799 if (!empty($subType)) {
2800 $subTypes[$subType] = 1;
2802 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2807 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2808 $contactType = $contactTypeANDSubType[0];
2809 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2810 if (!empty($subType)) {
2811 $subTypes[$subType] = 1;
2813 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2817 if (!empty($clause)) {
2819 if ($op == 'IN' ||
$op == 'NOT IN') {
2820 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2823 $type = array_pop($clause);
2824 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2827 $this->_qill
[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2829 if (!empty($subTypes)) {
2830 $this->includeContactSubTypes($subTypes, $grouping);
2836 * Where / qill clause for contact_sub_type
2840 public function contactSubType(&$values) {
2841 list($name, $op, $value, $grouping, $wildcard) = $values;
2842 $this->includeContactSubTypes($value, $grouping, $op);
2850 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2852 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2854 $value = $value[$op];
2858 $alias = "contact_a.contact_sub_type";
2859 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
2861 $op = str_replace('IN', 'LIKE', $op);
2862 $op = str_replace('=', 'LIKE', $op);
2863 $op = str_replace('!', 'NOT ', $op);
2865 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2866 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
2868 elseif (is_array($value)) {
2869 foreach ($value as $k => $v) {
2871 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($v, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2876 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2879 if (!empty($clause)) {
2880 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2882 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', array(1 => $qillOperators[$op])) . implode(' ' . ts('or') . ' ', array_keys($clause));
2886 * Where / qill clause for groups.
2890 public function group($values) {
2891 list($name, $op, $value, $grouping, $wildcard) = $values;
2893 // If the $value is in OK (operator as key) array format we need to extract the key as operator and value first
2894 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2896 $value = $value[$op];
2899 // Replace pseudo operators from search builder
2900 $op = str_replace('EMPTY', 'NULL', $op);
2902 if (strpos($op, 'NULL')) {
2906 if (count($value) > 1) {
2907 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
2908 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $op)));
2910 $this->_useDistinct
= TRUE;
2913 if (isset($value)) {
2914 $value = CRM_Utils_Array
::value($op, $value, $value);
2919 $isNotOp = ($op == 'NOT IN' ||
$op == '!=');
2922 $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
2924 is_array($gcsValues[2])
2926 foreach ($gcsValues[2] as $k => $v) {
2928 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2933 $statii[] = '"Added"';
2936 $ssClause = $this->addGroupContactCache($value, NULL, "contact_a", $op);
2937 $isSmart = (!$ssClause) ?
FALSE : TRUE;
2938 if (!is_array($value) &&
2939 count($statii) == 1 &&
2940 $statii[0] == '"Added"' &&
2943 if (!empty($value) && CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $value, 'saved_search_id')) {
2947 $groupClause = NULL;
2950 $groupIds = implode(',', (array) $value);
2951 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2952 $joinClause = array("contact_a.id = {$gcTable}.contact_id");
2954 $joinClause[] = "{$gcTable}.status IN (" . implode(', ', $statii) . ")";
2956 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
2957 if (strpos($op, 'IN') !== FALSE) {
2958 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2960 elseif ($op == '!=') {
2961 $groupClause = "{$gcTable}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact cgc WHERE cgc.group_id = $groupIds)";
2964 $groupClause = "{$gcTable}.group_id $op $groupIds";
2969 $and = ($op == 'IS NULL') ?
'AND' : 'OR';
2971 $groupClause = "( ( $groupClause ) $and ( $ssClause ) )";
2974 $groupClause = $ssClause;
2978 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
2979 $this->_qill
[$grouping][] = ts("Group(s) %1 %2", array(1 => $qillop, 2 => $qillVal));
2980 if (strpos($op, 'NULL') === FALSE) {
2981 $this->_qill
[$grouping][] = ts("Group Status %1", array(1 => implode(' ' . ts('or') . ' ', $statii)));
2984 $this->_where
[$grouping][] = $groupClause;
2989 * Function translates selection of group type into a list of groups.
2994 public function getGroupsFromTypeCriteria($value) {
2995 $groupIds = array();
2996 foreach ((array) $value as $groupTypeValue) {
2997 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2998 $groupIds = ($groupIds +
$groupList);
3004 * @param array $groups
3005 * @param string $tableAlias
3006 * @param string $joinTable
3009 * @return null|string
3011 public function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a", $op) {
3012 $isNullOp = (strpos($op, 'NULL') !== FALSE);
3013 $groupsIds = $groups;
3014 if (!$isNullOp && !$groups) {
3017 elseif (strpos($op, 'IN') !== FALSE) {
3018 $groups = array($op => $groups);
3020 elseif (is_array($groups) && count($groups)) {
3021 $groups = array('IN' => $groups);
3024 // Find all the groups that are part of a saved search.
3025 $smartGroupClause = self
::buildClause("id", $op, $groups, 'Int');
3027 SELECT id, cache_date, saved_search_id, children
3029 WHERE $smartGroupClause
3030 AND ( saved_search_id != 0
3031 OR saved_search_id IS NOT NULL
3032 OR children IS NOT NULL )
3035 $group = CRM_Core_DAO
::executeQuery($sql);
3037 while ($group->fetch()) {
3038 $this->_useDistinct
= TRUE;
3039 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
3040 CRM_Contact_BAO_GroupContactCache
::load($group);
3043 if ($group->N
== 0) {
3048 $tableAlias = "`civicrm_group_contact_cache_";
3049 $tableAlias .= ($isNullOp) ?
"a`" : implode(',', (array) $groupsIds) . "`";
3052 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.id = {$tableAlias}.contact_id ";
3053 return self
::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
3057 * Where / qill clause for cms users
3061 public function ufUser(&$values) {
3062 list($name, $op, $value, $grouping, $wildcard) = $values;
3065 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3067 $this->_qill
[$grouping][] = ts('CMS User');
3069 elseif ($value == 0) {
3070 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3072 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3073 $this->_qill
[$grouping][] = ts('Not a CMS User');
3078 * All tag search specific.
3080 * @param array $values
3082 public function tagSearch(&$values) {
3083 list($name, $op, $value, $grouping, $wildcard) = $values;
3086 $value = "%{$value}%";
3088 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3089 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3091 $etTable = "`civicrm_entity_tag-" . $value . "`";
3092 $tTable = "`civicrm_tag-" . $value . "`";
3094 if ($useAllTagTypes[2]) {
3095 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3096 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3097 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3099 // search tag in cases
3100 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3101 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
3102 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3103 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3104 LEFT JOIN civicrm_case
3105 ON (civicrm_case_contact.case_id = civicrm_case.id
3106 AND civicrm_case.is_deleted = 0 )
3107 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3108 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3109 // search tag in activities
3110 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3111 $tActTable = "`civicrm_act_tag-" . $value . "`";
3112 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3113 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3115 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3116 = " LEFT JOIN civicrm_activity_contact
3117 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3118 LEFT JOIN civicrm_activity
3119 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3120 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3121 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3122 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3124 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $value . "' OR {$tCaseTable}.name $op '" . $value . "' OR {$tActTable}.name $op '" . $value . "')";
3125 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
3128 $etTable = "`civicrm_entity_tag-" . $value . "`";
3129 $tTable = "`civicrm_tag-" . $value . "`";
3130 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3131 {$etTable}.entity_table = 'civicrm_contact' )
3132 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3134 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3135 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
3140 * Where / qill clause for tag
3142 * @param array $values
3144 public function tag(&$values) {
3145 list($name, $op, $value, $grouping, $wildcard) = $values;
3147 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, array('onlyActive' => FALSE));
3148 // API/Search Builder format array(operator => array(values))
3149 if (is_array($value)) {
3150 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3152 $value = $value[$op];
3154 if (count($value) > 1) {
3155 $this->_useDistinct
= TRUE;
3157 $value = implode(',', (array) $value);
3160 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3161 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3163 $etTable = "`civicrm_entity_tag-" . $value . "`";
3165 if ($useAllTagTypes[2]) {
3166 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3167 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3169 // search tag in cases
3170 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3171 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3172 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3174 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3175 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3176 LEFT JOIN civicrm_case
3177 ON (civicrm_case_contact.case_id = civicrm_case.id
3178 AND civicrm_case.is_deleted = 0 )
3179 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3180 // search tag in activities
3181 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3182 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3183 = " LEFT JOIN civicrm_activity_contact
3184 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3185 LEFT JOIN civicrm_activity
3186 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3187 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3188 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3191 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3192 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3195 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3199 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3200 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3203 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3204 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3205 $op = str_replace('EMPTY', 'NULL', $op);
3206 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3208 // CRM-16941: for tag tried with != operator we don't show contact who don't have given $value AND also in other tag
3209 elseif ($op == '!=') {
3210 $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') . ")";
3212 elseif ($op == '=' ||
strstr($op, 'IN')) {
3213 $op = ($op == '=') ?
'IN' : $op;
3214 $this->_where
[$grouping][] = "{$etTable}.tag_id $op ( $value )";
3217 $this->_qill
[$grouping][] = ts('Tagged %1 %2', array(1 => $qillop, 2 => $qillVal));
3221 * Where/qill clause for notes
3223 * @param array $values
3225 public function notes(&$values) {
3226 list($name, $op, $value, $grouping, $wildcard) = $values;
3228 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3229 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3230 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3232 $this->_useDistinct
= TRUE;
3234 $this->_tables
['civicrm_note'] = $this->_whereTables
['civicrm_note']
3235 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3237 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3239 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3241 if (strpos($value, '%') === FALSE) {
3242 $value = "%$value%";
3246 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3252 if ($noteOption %
2 == 0) {
3253 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3254 $label = ts('Note: Body Only');
3256 if ($noteOption %
3 == 0) {
3257 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3258 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3260 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3261 list($qillOp, $qillVal) = self
::buildQillForFieldValue(NULL, $name, $n, $op);
3262 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillOp, 3 => $qillVal));
3266 * @param string $name
3272 public function nameNullOrEmptyOp($name, $op, $grouping) {
3276 $this->_where
[$grouping][] = "contact_a.$name $op";
3277 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3281 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3282 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3285 case 'IS NOT EMPTY':
3286 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3287 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3296 * Where / qill clause for sort_name
3298 * @param array $values
3300 public function sortName(&$values) {
3301 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3303 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3304 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3308 $input = $value = trim($value);
3310 if (!strlen($value)) {
3314 $config = CRM_Core_Config
::singleton();
3318 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3321 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3323 $firstChar = substr($value, 0, 1);
3324 $lastChar = substr($value, -1, 1);
3325 $quotes = array("'", '"');
3326 // If string is quoted, strip quotes and otherwise don't alter it
3327 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3328 $value = trim($value, implode('', $quotes));
3330 // Replace spaces with wildcards for a LIKE operation
3331 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3332 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3333 $value = str_replace(' ', '%', $value);
3335 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($value)));
3336 if (strlen($value)) {
3337 $fieldsub = array();
3338 $value = "'" . self
::getWildCardedValue($wildcard, $op, $value) . "'";
3339 if ($fieldName == 'sort_name') {
3340 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3343 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3345 $fieldsub[] = " ( $wc $op $value )";
3346 if ($config->includeNickNameInName
) {
3347 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3348 $fieldsub[] = " ( $wc $op $value )";
3350 if ($config->includeEmailInName
) {
3351 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3353 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3356 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3358 $this->_where
[$grouping][] = $sub;
3359 if ($config->includeEmailInName
) {
3360 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3361 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3364 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3369 * Where/qill clause for greeting fields.
3371 * @param array $values
3373 public function greetings(&$values) {
3374 list($name, $op, $value, $grouping, $wildcard) = $values;
3375 $name .= '_display';
3377 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
3378 $this->_qill
[$grouping][] = ts('Greeting %1 %2', array(1 => $qillop, 2 => $qillVal));
3379 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value, 'String');
3383 * Where / qill clause for email
3385 * @param array $values
3386 * @param string $apiEntity
3388 protected function email(&$values, $apiEntity) {
3389 list($name, $op, $value, $grouping, $wildcard) = $values;
3390 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3392 // CRM-18147: for Contact's GET API, email fieldname got appended with its entity as in {$apiEntiy}_{$name}
3393 // so following code is use build whereClause for contact's primart email id
3394 if (!empty($apiEntity)) {
3395 $dataType = 'String';
3396 if ($name == 'email_id') {
3397 $dataType = 'Integer';
3401 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.is_primary', '=', 1, 'Integer');
3402 $this->_where
[$grouping][] = self
::buildClause("civicrm_email.$name", $op, $value, $dataType);
3406 $n = strtolower(trim($value));
3408 if (substr($n, 0, 1) == '"' &&
3409 substr($n, -1, 1) == '"'
3411 $n = substr($n, 1, -1);
3412 $value = CRM_Core_DAO
::escapeString($n);
3416 $value = self
::getWildCardedValue($wildcard, $op, $n);
3418 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3419 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3422 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3423 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3428 * Where / qill clause for phone number
3430 * @param array $values
3432 public function phone_numeric(&$values) {
3433 list($name, $op, $value, $grouping, $wildcard) = $values;
3434 // Strip non-numeric characters; allow wildcards
3435 $number = preg_replace('/[^\d%]/', '', $value);
3437 if (strpos($number, '%') === FALSE) {
3438 $number = "%$number%";
3441 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3442 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3443 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3448 * Where / qill clause for phone type/location
3450 * @param array $values
3452 public function phone_option_group($values) {
3453 list($name, $op, $value, $grouping, $wildcard) = $values;
3454 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3455 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3456 $optionName = $options[$value];
3457 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3458 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3459 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3463 * Where / qill clause for street_address.
3465 * @param array $values
3467 public function street_address(&$values) {
3468 list($name, $op, $value, $grouping, $wildcard) = $values;
3477 $value = strtolower($n);
3478 if (strpos($value, '%') === FALSE) {
3479 // only add wild card if not there
3480 $value = "%{$value}%";
3483 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3484 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3487 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3488 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3491 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3495 * Where / qill clause for street_unit.
3497 * @param array $values
3499 public function street_number(&$values) {
3500 list($name, $op, $value, $grouping, $wildcard) = $values;
3508 if (strtolower($n) == 'odd') {
3509 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3510 $this->_qill
[$grouping][] = ts('Street Number is odd');
3512 elseif (strtolower($n) == 'even') {
3513 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3514 $this->_qill
[$grouping][] = ts('Street Number is even');
3517 $value = strtolower($n);
3519 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3520 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3523 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3527 * Where / qill clause for sorting by character.
3529 * @param array $values
3531 public function sortByCharacter(&$values) {
3532 list($name, $op, $value, $grouping, $wildcard) = $values;
3534 $name = trim($value);
3535 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3536 $this->_where
[$grouping][] = $cond;
3537 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3541 * Where / qill clause for including contact ids.
3543 public function includeContactIDs() {
3544 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3548 $contactIds = array();
3549 foreach ($this->_params
as $id => $values) {
3550 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3551 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3554 if (!empty($contactIds)) {
3555 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3560 * Where / qill clause for postal code.
3562 * @param array $values
3564 public function postalCode(&$values) {
3565 // skip if the fields dont have anything to do with postal_code
3566 if (empty($this->_fields
['postal_code'])) {
3570 list($name, $op, $value, $grouping, $wildcard) = $values;
3572 // Handle numeric postal code range searches properly by casting the column as numeric
3573 if (is_numeric($value)) {
3574 $field = "IF (civicrm_address.postal_code REGEXP '^[0-9]+$', CAST(civicrm_address.postal_code AS UNSIGNED), 0)";
3575 $val = CRM_Utils_Type
::escape($value, 'Integer');
3578 $field = 'civicrm_address.postal_code';
3579 // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string.
3580 if (!is_array($value)) {
3581 $val = CRM_Utils_Type
::escape($value, 'String');
3584 // Do we need to escape values here? I would expect buildClause does.
3589 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3591 if ($name == 'postal_code') {
3592 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3593 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3595 elseif ($name == 'postal_code_low') {
3596 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3597 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3599 elseif ($name == 'postal_code_high') {
3600 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3601 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3606 * Where / qill clause for location type.
3608 * @param array $values
3609 * @param null $status
3613 public function locationType(&$values, $status = NULL) {
3614 list($name, $op, $value, $grouping, $wildcard) = $values;
3616 if (is_array($value)) {
3617 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3618 $this->_tables
['civicrm_address'] = 1;
3619 $this->_whereTables
['civicrm_address'] = 1;
3621 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3623 foreach ($value as $id) {
3624 $names[] = $locationType[$id];
3627 $this->_primaryLocation
= FALSE;
3630 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3633 return implode(' ' . ts('or') . ' ', $names);
3640 * @param bool $fromStateProvince
3642 * @return array|NULL
3644 public function country(&$values, $fromStateProvince = TRUE) {
3645 list($name, $op, $value, $grouping, $wildcard) = $values;
3647 if (!$fromStateProvince) {
3648 $stateValues = $this->getWhereValues('state_province', $grouping);
3649 if (!empty($stateValues)) {
3650 // return back to caller if there are state province values
3651 // since that handles this case
3656 $countryClause = $countryQill = NULL;
3657 if ($values && !empty($value)) {
3658 $this->_tables
['civicrm_address'] = 1;
3659 $this->_whereTables
['civicrm_address'] = 1;
3661 $countryClause = self
::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
3662 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, 'country_id', $value, $op);
3663 $countryQill = ts("%1 %2 %3", array(1 => 'Country', 2 => $qillop, 3 => $qillVal));
3665 if (!$fromStateProvince) {
3666 $this->_where
[$grouping][] = $countryClause;
3667 $this->_qill
[$grouping][] = $countryQill;
3671 if ($fromStateProvince) {
3672 if (!empty($countryClause)) {
3675 " ...AND... " . $countryQill,
3679 return array(NULL, NULL);
3685 * Where / qill clause for county (if present).
3687 * @param array $values
3688 * @param null $status
3692 public function county(&$values, $status = NULL) {
3693 list($name, $op, $value, $grouping, $wildcard) = $values;
3695 if (!is_array($value)) {
3696 // force the county to be an array
3697 $value = array($value);
3700 // check if the values are ids OR names of the counties
3701 $inputFormat = 'id';
3702 foreach ($value as $v) {
3703 if (!is_numeric($v)) {
3704 $inputFormat = 'name';
3712 elseif ($op == '!=') {
3716 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3717 $op = str_replace('EMPTY', 'NULL', $op);
3720 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3721 $clause = "civicrm_address.county_id $op";
3723 elseif ($inputFormat == 'id') {
3724 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3726 $county = CRM_Core_PseudoConstant
::county();
3727 foreach ($value as $id) {
3728 $names[] = CRM_Utils_Array
::value($id, $county);
3732 $inputClause = array();
3733 $county = CRM_Core_PseudoConstant
::county();
3734 foreach ($value as $name) {
3735 $name = trim($name);
3736 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3738 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3741 $this->_tables
['civicrm_address'] = 1;
3742 $this->_whereTables
['civicrm_address'] = 1;
3744 $this->_where
[$grouping][] = $clause;
3746 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3749 return implode(' ' . ts('or') . ' ', $names);
3754 * Where / qill clause for state/province AND country (if present).
3756 * @param array $values
3757 * @param null $status
3761 public function stateProvince(&$values, $status = NULL) {
3762 list($name, $op, $value, $grouping, $wildcard) = $values;
3764 $stateClause = self
::buildClause('civicrm_address.state_province_id', $op, $value, 'Positive');
3765 $this->_tables
['civicrm_address'] = 1;
3766 $this->_whereTables
['civicrm_address'] = 1;
3768 $countryValues = $this->getWhereValues('country', $grouping);
3769 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3770 if ($countryClause) {
3771 $clause = "( $stateClause AND $countryClause )";
3774 $clause = $stateClause;
3777 $this->_where
[$grouping][] = $clause;
3778 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
3780 $this->_qill
[$grouping][] = ts("State/Province %1 %2 %3", array(1 => $qillop, 2 => $qillVal, 3 => $countryQill));
3783 return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill;
3788 * Where / qill clause for change log.
3790 * @param array $values
3792 public function changeLog(&$values) {
3793 list($name, $op, $value, $grouping, $wildcard) = $values;
3795 $targetName = $this->getWhereValues('changed_by', $grouping);
3800 $name = trim($targetName[2]);
3801 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3802 $name = $targetName[4] ?
"%$name%" : $name;
3803 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3804 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3805 $this->_qill
[$grouping][] = ts('Modified By') . " $name";
3811 public function modifiedDates($values) {
3812 $this->_useDistinct
= TRUE;
3814 // CRM-11281, default to added date if not set
3815 $fieldTitle = ts('Added Date');
3816 $fieldName = 'created_date';
3817 foreach (array_keys($this->_params
) as $id) {
3818 if ($this->_params
[$id][0] == 'log_date') {
3819 if ($this->_params
[$id][2] == 2) {
3820 $fieldTitle = ts('Modified Date');
3821 $fieldName = 'modified_date';
3826 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3828 self
::$_openedPanes[ts('Change Log')] = TRUE;
3834 public function demographics(&$values) {
3835 list($name, $op, $value, $grouping, $wildcard) = $values;
3837 if (($name == 'age_low') ||
($name == 'age_high')) {
3838 $this->ageRangeQueryBuilder($values,
3839 'contact_a', 'age', 'birth_date', ts('Age')
3842 elseif (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3844 $this->dateQueryBuilder($values,
3845 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3848 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3850 $this->dateQueryBuilder($values,
3851 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3855 self
::$_openedPanes[ts('Demographics')] = TRUE;
3861 public function privacy(&$values) {
3862 list($name, $op, $value, $grouping, $wildcard) = $values;
3863 //fixed for profile search listing CRM-4633
3864 if (strpbrk($value, "[")) {
3865 $value = "'{$value}'";
3867 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3870 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3872 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3873 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
3874 $title = $field ?
$field['title'] : $name;
3875 $this->_qill
[$grouping][] = "$title $op $value";
3881 public function privacyOptions($values) {
3882 list($name, $op, $value, $grouping, $wildcard) = $values;
3884 if (empty($value) ||
!is_array($value)) {
3888 // get the operator and toggle values
3889 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3892 strtolower($opValues[2] == 'AND')
3897 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3899 if ($toggleValues &&
3900 $toggleValues[2] == 2
3907 foreach ($value as $dontCare => $pOption) {
3908 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
3909 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3910 $title = $field ?
$field['title'] : $pOption;
3911 $qill[] = " $title = 1 ";
3914 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
3915 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
3921 public function preferredCommunication(&$values) {
3922 list($name, $op, $value, $grouping, $wildcard) = $values;
3924 if (!is_array($value)) {
3925 $value = str_replace(array('(', ')'), '', explode(",", $value));
3927 elseif (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3929 $value = $value[$op];
3931 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Contact', $name, $value, $op);
3933 if (self
::caseImportant($op)) {
3934 $value = implode("[[:cntrl:]]|[[:cntrl:]]", (array) $value);
3935 $op = (strstr($op, '!') ||
strstr($op, 'NOT')) ?
'NOT RLIKE' : 'RLIKE';
3936 $value = "[[:cntrl:]]" . $value . "[[:cntrl:]]";
3939 $this->_where
[$grouping][] = self
::buildClause("contact_a.preferred_communication_method", $op, $value);
3940 $this->_qill
[$grouping][] = ts('Preferred Communication Method %1 %2', array(1 => $qillop, 2 => $qillVal));
3944 * Where / qill clause for relationship.
3946 * @param array $values
3948 public function relationship(&$values) {
3949 list($name, $op, $value, $grouping, $wildcard) = $values;
3950 if ($this->_relationshipValuesAdded
) {
3953 // also get values array for relation_target_name
3954 // for relationship search we always do wildcard
3955 $relationType = $this->getWhereValues('relation_type_id', $grouping);
3956 $targetName = $this->getWhereValues('relation_target_name', $grouping);
3957 $relStatus = $this->getWhereValues('relation_status', $grouping);
3958 $relPermission = $this->getWhereValues('relation_permission', $grouping);
3959 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
3961 $nameClause = $name = NULL;
3963 $name = trim($targetName[2]);
3964 if (substr($name, 0, 1) == '"' &&
3965 substr($name, -1, 1) == '"'
3967 $name = substr($name, 1, -1);
3968 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3969 $nameClause = "= '$name'";
3972 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3973 $nameClause = "LIKE '%{$name}%'";
3977 $rTypeValues = array();
3978 if (!empty($relationType)) {
3979 $rel = explode('_', $relationType[2]);
3980 self
::$_relType = $rel[1];
3981 $params = array('id' => $rel[0]);
3982 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
3984 if (!empty($rTypeValues) && $rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
3985 // if we don't know which end of the relationship we are dealing with we'll create a temp table
3986 //@todo unless we are dealing with a target group
3987 self
::$_relType = 'reciprocal';
3989 // if we are creating a temp table we build our own where for the relationship table
3990 $relationshipTempTable = NULL;
3991 if (self
::$_relType == 'reciprocal' && empty($targetGroup)) {
3993 self
::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO
::createTempTableName('civicrm_rel');
3995 $where[$grouping][] = " sort_name $nameClause ";
3999 $where = &$this->_where
;
4001 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4005 $allRelationshipType = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE);
4007 if ($nameClause ||
!$targetGroup) {
4008 if (!empty($relationType)) {
4009 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " $name";
4012 $this->_qill
[$grouping][] = $name;
4016 //check to see if the target contact is in specified group
4018 //add contacts from static groups
4019 $this->_tables
['civicrm_relationship_group_contact'] = $this->_whereTables
['civicrm_relationship_group_contact']
4020 = " 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'";
4021 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4022 implode(",", $targetGroup[2]) . ") ) ";
4024 //add contacts from saved searches
4025 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b", $op);
4027 //set the group where clause
4029 $groupWhere[] = "( " . $ssWhere . " )";
4031 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4033 //Get the names of the target groups for the qill
4034 $groupNames = CRM_Core_PseudoConstant
::group();
4035 $qillNames = array();
4036 foreach ($targetGroup[2] as $groupId) {
4037 if (array_key_exists($groupId, $groupNames)) {
4038 $qillNames[] = $groupNames[$groupId];
4041 if (!empty($relationType)) {
4042 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " ( " . implode(", ", $qillNames) . " )";
4045 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4049 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4050 $today = date('Ymd');
4051 //check for active, inactive and all relation status
4052 if ($relStatus[2] == 0) {
4053 $where[$grouping][] = "(
4054 civicrm_relationship.is_active = 1 AND
4055 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4056 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4058 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4060 elseif ($relStatus[2] == 1) {
4061 $where[$grouping][] = "(
4062 civicrm_relationship.is_active = 0 OR
4063 civicrm_relationship.end_date < {$today} OR
4064 civicrm_relationship.start_date > {$today}
4066 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4070 if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
)) {
4073 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4075 //check for permissioned, non-permissioned and all permissioned relations
4076 if ($relPermission[2] == 1) {
4077 $where[$grouping][] = "(
4078 civicrm_relationship.is_permission_a_b = 1
4080 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4082 elseif ($relPermission[2] == 2) {
4083 //non-allowed permission relationship.
4084 $where[$grouping][] = "(
4085 civicrm_relationship.is_permission_a_b = 0
4087 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4090 $this->addRelationshipDateClauses($grouping, $where);
4091 if (!empty($relationType) && !empty($rType) && isset($rType->id
)) {
4092 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
4094 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4095 $this->_useDistinct
= TRUE;
4096 $this->_relationshipValuesAdded
= TRUE;
4097 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4099 // @todo creating a temp table could be expanded to group filter
4100 // as even creating a temp table of all relationships is much much more efficient than
4101 // an OR in the join
4102 if ($relationshipTempTable) {
4104 if (!empty($where[$grouping])) {
4105 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4106 $whereClause = str_replace('contact_b', 'c', $whereClause);
4109 CREATE TEMPORARY TABLE {$relationshipTempTable}
4110 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4111 FROM civicrm_relationship
4112 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4115 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4116 FROM civicrm_relationship
4117 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4120 CRM_Core_DAO
::executeQuery($sql);
4126 * Add start & end date criteria in
4127 * @param string $grouping
4128 * @param array $where
4129 * = array to add where clauses to, in case you are generating a temp table.
4130 * not the main query.
4132 public function addRelationshipDateClauses($grouping, &$where) {
4133 $dateValues = array();
4139 foreach ($dateTypes as $dateField) {
4140 $dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping);
4141 $dateValueHigh = $this->getWhereValues('relation_' . $dateField . '_high', $grouping);
4142 if (!empty($dateValueLow)) {
4143 $date = date('Ymd', strtotime($dateValueLow[2]));
4144 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4145 $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);
4147 if (!empty($dateValueHigh)) {
4148 $date = date('Ymd', strtotime($dateValueHigh[2]));
4149 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4150 $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);
4156 * Default set of return properties.
4161 * derault return properties
4163 public static function &defaultReturnProperties($mode = 1) {
4164 if (!isset(self
::$_defaultReturnProperties)) {
4165 self
::$_defaultReturnProperties = array();
4168 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4169 // add activity return properties
4170 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4171 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4174 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4177 if (empty(self
::$_defaultReturnProperties[$mode])) {
4178 self
::$_defaultReturnProperties[$mode] = array(
4181 'legal_identifier' => 1,
4182 'external_identifier' => 1,
4183 'contact_type' => 1,
4184 'contact_sub_type' => 1,
4186 'display_name' => 1,
4187 'preferred_mail_format' => 1,
4194 'formal_title' => 1,
4195 'communication_style_id' => 1,
4198 'street_address' => 1,
4199 'supplemental_address_1' => 1,
4200 'supplemental_address_2' => 1,
4203 'postal_code_suffix' => 1,
4204 'state_province' => 1,
4206 'world_region' => 1,
4213 'household_name' => 1,
4214 'organization_name' => 1,
4215 'deceased_date' => 1,
4220 'current_employer' => 1,
4221 // FIXME: should we use defaultHierReturnProperties() for the below?
4222 'do_not_email' => 1,
4225 'do_not_phone' => 1,
4226 'do_not_trade' => 1,
4228 'contact_is_deleted' => 1,
4229 'preferred_communication_method' => 1,
4230 'preferred_language' => 1,
4234 return self
::$_defaultReturnProperties[$mode];
4238 * Get primary condition for a sql clause.
4242 * @return string|NULL
4244 public static function getPrimaryCondition($value) {
4245 if (is_numeric($value)) {
4246 $value = (int ) $value;
4247 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4253 * Wrapper for a simple search query.
4255 * @param array $params
4256 * @param array $returnProperties
4257 * @param bool $count
4261 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4262 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4263 list($select, $from, $where, $having) = $query->query();
4264 $groupBy = ($query->_useGroupBy
) ?
'GROUP BY contact_a.id' : '';
4266 return "$select $from $where $groupBy $having";
4270 * These are stub comments as this function needs more explanation - particularly in terms of how it
4271 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4273 * This function was originally written as a wrapper for the api query but is called from multiple places
4274 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4275 * but it is unclear as to whehter that is historical or there is a reason
4276 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4278 * @param array $params
4279 * @param array $returnProperties
4280 * @param null $fields
4281 * @param string $sort
4282 * @param int $offset
4283 * @param int $row_count
4284 * @param bool $smartGroupCache
4285 * ?? update smart group cache?.
4286 * @param bool $count
4287 * Return count obnly.
4288 * @param bool $skipPermissions
4289 * Should permissions be ignored or should the logged in user's permissions be applied.
4291 * This basically correlates to the component.
4295 public static function apiQuery(
4297 $returnProperties = NULL,
4302 $smartGroupCache = TRUE,
4304 $skipPermissions = TRUE,
4309 $query = new CRM_Contact_BAO_Query(
4310 $params, $returnProperties,
4311 NULL, TRUE, FALSE, $mode,
4313 TRUE, $smartGroupCache,
4318 //this should add a check for view deleted if permissions are enabled
4319 if ($skipPermissions) {
4320 $query->_skipDeleteClause
= TRUE;
4322 $query->generatePermissionClause(FALSE, $count);
4324 // note : this modifies _fromClause and _simpleFromClause
4325 $query->includePseudoFieldsJoin($sort);
4327 list($select, $from, $where, $having) = $query->query($count);
4329 $options = $query->_options
;
4330 if (!empty($query->_permissionWhereClause
)) {
4331 if (empty($where)) {
4332 $where = "WHERE $query->_permissionWhereClause";
4335 $where = "$where AND $query->_permissionWhereClause";
4339 $sql = "$select $from $where $having";
4342 if ($query->_useGroupBy
) {
4343 $sql .= self
::getGroupByFromSelectColumns($query->_select
, 'contact_a.id');
4345 if (!empty($sort)) {
4346 $sort = CRM_Utils_Type
::escape($sort, 'String');
4347 $sql .= " ORDER BY $sort ";
4349 if ($row_count > 0 && $offset >= 0) {
4350 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4351 $row_count = CRM_Utils_Type
::escape($row_count, 'Int');
4352 $sql .= " LIMIT $offset, $row_count ";
4355 $dao = CRM_Core_DAO
::executeQuery($sql);
4357 // @todo derive this from the component class rather than hard-code two options.
4358 $entityIDField = ($mode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) ?
'contribution_id' : 'contact_id';
4361 while ($dao->fetch()) {
4363 $noRows = $dao->rowCount
;
4365 return array($noRows, NULL);
4367 $val = $query->store($dao);
4368 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4370 if (!empty($convertedVals)) {
4371 $val = array_replace_recursive($val, $convertedVals);
4373 $values[$dao->$entityIDField] = $val;
4376 return array($values, $options);
4380 * Get the actual custom field name by stripping off the appended string.
4382 * The string could be _relative, _from, or _to
4384 * @todo use metadata rather than convention to do this.
4386 * @param string $parameterName
4387 * The name of the parameter submitted to the form.
4394 public static function getCustomFieldName($parameterName) {
4395 if (substr($parameterName, -5, 5) == '_from') {
4396 return substr($parameterName, 0, strpos($parameterName, '_from'));
4398 if (substr($parameterName, -9, 9) == '_relative') {
4399 return substr($parameterName, 0, strpos($parameterName, '_relative'));
4401 if (substr($parameterName, -3, 3) == '_to') {
4402 return substr($parameterName, 0, strpos($parameterName, '_to'));
4407 * Convert submitted values for relative custom fields to query object format.
4409 * The query will support the sqlOperator format so convert to that format.
4411 * @param array $formValues
4413 * @param array $params
4414 * Converted parameters for the query object.
4415 * @param string $values
4417 * @param string $fieldName
4418 * Submitted field name. (Matches form field not DB field.)
4420 protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) {
4421 if (empty($values)) {
4422 // e.g we might have relative set & from & to empty. The form flow is a bit funky &
4423 // this function gets called again after they fields have been converted which can get ugly.
4426 $customFieldName = self
::getCustomFieldName($fieldName);
4428 if (substr($fieldName, -9, 9) == '_relative') {
4429 list($from, $to) = CRM_Utils_Date
::getFromTo($values, NULL, NULL);
4432 if ($fieldName == $customFieldName . '_to' && CRM_Utils_Array
::value($customFieldName . '_from', $formValues)) {
4433 // Both to & from are set. We only need to acton one, choosing from.
4437 $from = CRM_Utils_Array
::value($customFieldName . '_from', $formValues, NULL);
4438 $to = CRM_Utils_Array
::value($customFieldName . '_to', $formValues, NULL);
4440 if (self
::isCustomDateField($customFieldName)) {
4441 list($from, $to) = CRM_Utils_Date
::getFromTo(NULL, $from, $to);
4447 $relativeFunction = array('BETWEEN' => array($from, $to));
4450 $relativeFunction = array('>=' => $from);
4454 $relativeFunction = array('<=' => $to);
4466 * Are we dealing with custom field of type date.
4472 public static function isCustomDateField($fieldName) {
4473 if (($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($fieldName)) == FALSE) {
4476 if ('Date' == civicrm_api3('CustomField', 'getvalue', array('id' => $customFieldID, 'return' => 'data_type'))) {
4483 * Has this field already been reformatting to Query object syntax.
4485 * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems
4486 * to come with associated double queries & is possibly damaging performance.
4488 * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns
4491 * @param mixed $values
4492 * Value in formValues for the field.
4496 public static function isAlreadyProcessedForQueryFormat($values) {
4497 if (!is_array($values)) {
4500 if (($operator = CRM_Utils_Array
::value(1, $values)) == FALSE) {
4503 return in_array($operator, CRM_Core_DAO
::acceptedSQLOperators());
4507 * If the state and country are passed remove state.
4509 * Country is implicit from the state, but including both results in
4510 * a poor query as there is no combined index on state AND country.
4514 * @param array $formValues
4516 public static function filterCountryFromValuesIfStateExists(&$formValues) {
4517 if (!empty($formValues['country']) && !empty($formValues['state_province'])) {
4518 // The use of array map sanitises the data by ensuring we are dealing with integers.
4519 $states = implode(', ', array_map('intval', $formValues['state_province']));
4520 $countryList = CRM_Core_DAO
::singleValueQuery(
4521 "SELECT GROUP_CONCAT(country_id) FROM civicrm_state_province WHERE id IN ($states)"
4523 if ($countryList == $formValues['country']) {
4524 unset($formValues['country']);
4530 * For some special cases, grouping by subset of select fields becomes mandatory.
4531 * Hence, full_group_by mode is handled by appending any_value
4532 * keyword to select fields not present in groupBy
4534 * @param array $selectClauses
4535 * @param array $groupBy - Columns already included in GROUP By clause.
4539 public static function appendAnyValueToSelect($selectClauses, $groupBy) {
4540 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4541 $sqlMode = explode(',', CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode'));
4543 // Disable only_full_group_by mode for lower sql versions.
4544 if (version_compare($mysqlVersion, '5.7', '<') ||
(!empty($sqlMode) && !in_array('ONLY_FULL_GROUP_BY', $sqlMode))) {
4545 $key = array_search('ONLY_FULL_GROUP_BY', $sqlMode);
4546 unset($sqlMode[$key]);
4547 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = '" . implode(',', $sqlMode) . "'");
4550 $groupBy = array_map('trim', (array) $groupBy);
4551 $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN)\(/i';
4552 foreach ($selectClauses as $key => &$val) {
4553 list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL);
4554 // append ANY_VALUE() keyword
4555 if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) {
4556 $val = str_replace($selectColumn, "ANY_VALUE({$selectColumn})", $val);
4561 return "SELECT " . implode(', ', $selectClauses) . " ";
4565 * Include Select columns in groupBy clause.
4567 * @param array $selectClauses
4568 * @param array $groupBy - Columns already included in GROUP By clause.
4572 public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NULL) {
4573 $groupBy = (array) $groupBy;
4574 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4575 $sqlMode = CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode');
4577 //return if ONLY_FULL_GROUP_BY is not enabled.
4578 if (!version_compare($mysqlVersion, '5.7', '<') && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
4579 $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN)\(/i';
4580 foreach ($selectClauses as $key => $val) {
4581 $aliasArray = preg_split('/ as /i', $val);
4582 // if more than 1 alias we need to split by ','.
4583 if (count($aliasArray) > 2) {
4584 $aliasArray = preg_split('/,/', $val);
4585 foreach ($aliasArray as $key => $value) {
4586 $alias = current(preg_split('/ as /i', $value));
4587 if (!in_array($alias, $groupBy) && preg_match($regexToExclude, trim($alias)) !== 1) {
4588 $groupBy[] = $alias;
4593 list($selectColumn, $alias) = array_pad($aliasArray, 2, NULL);
4594 $dateRegex = '/^(DATE_FORMAT|DATE_ADD|CASE)/i';
4595 $tableName = current(explode('.', $selectColumn));
4596 $primaryKey = "{$tableName}.id";
4597 // exclude columns which are already included in groupBy and aggregate functions from select
4598 // CRM-18439 - Also exclude the columns which are functionally dependent on columns in $groupBy (MySQL 5.7+)
4599 if (!in_array($selectColumn, $groupBy) && !in_array($primaryKey, $groupBy) && preg_match($regexToExclude, trim($selectColumn)) !== 1) {
4600 if (!empty($alias) && preg_match($dateRegex, trim($selectColumn))) {
4601 $groupBy[] = $alias;
4604 $groupBy[] = $selectColumn;
4611 if (!empty($groupBy)) {
4612 return " GROUP BY " . implode(', ', $groupBy);
4618 * Create and query the db for an contact search.
4620 * @param int $offset
4621 * The offset for the query.
4622 * @param int $rowCount
4623 * The number of rows to return.
4624 * @param string|CRM_Utils_Sort $sort
4625 * The order by string.
4626 * @param bool $count
4627 * Is this a count only query ?.
4628 * @param bool $includeContactIds
4629 * Should we include contact ids?.
4630 * @param bool $sortByChar
4631 * If true returns the distinct array of first characters for search results.
4632 * @param bool $groupContacts
4633 * If true, return only the contact ids.
4634 * @param bool $returnQuery
4635 * Should we return the query as a string.
4636 * @param string $additionalWhereClause
4637 * If the caller wants to further restrict the search (used for components).
4638 * @param null $sortOrder
4639 * @param string $additionalFromClause
4640 * Should be clause with proper joins, effective to reduce where clause load.
4642 * @param bool $skipOrderAndLimit
4644 * @return CRM_Core_DAO
4646 public function searchQuery(
4647 $offset = 0, $rowCount = 0, $sort = NULL,
4648 $count = FALSE, $includeContactIds = FALSE,
4649 $sortByChar = FALSE, $groupContacts = FALSE,
4650 $returnQuery = FALSE,
4651 $additionalWhereClause = NULL, $sortOrder = NULL,
4652 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4655 if ($includeContactIds) {
4656 $this->_includeContactIds
= TRUE;
4657 $this->_whereClause
= $this->whereClause();
4660 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4662 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4663 // and that contact happens to be deleted, set $onlyDeleted to true
4664 foreach ($this->_params
as $values) {
4665 $name = CRM_Utils_Array
::value(0, $values);
4666 $op = CRM_Utils_Array
::value(1, $values);
4667 $value = CRM_Utils_Array
::value(2, $values);
4668 if ($name == 'contact_id' and $op == '=') {
4669 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4670 $onlyDeleted = TRUE;
4676 // building the query string
4677 $groupBy = $groupByCol = NULL;
4679 if (isset($this->_groupByComponentClause
)) {
4680 $groupBy = $this->_groupByComponentClause
;
4681 $groupCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause
));
4682 $groupByCol = explode(', ', $groupCols);
4684 elseif ($this->_useGroupBy
) {
4685 $groupByCol = 'contact_a.id';
4686 $groupBy = ' GROUP BY contact_a.id';
4689 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4690 $groupByCol = 'civicrm_activity.id';
4691 $groupBy = 'GROUP BY civicrm_activity.id ';
4694 $order = $orderBy = $limit = '';
4696 list($order, $additionalFromClause) = $this->prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause);
4698 if ($rowCount > 0 && $offset >= 0) {
4699 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4700 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4701 $limit = " LIMIT $offset, $rowCount ";
4706 $this->_sort
= $sort;
4709 $this->includePseudoFieldsJoin($sort);
4711 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4713 if (!empty($groupByCol)) {
4714 $groupBy = self
::getGroupByFromSelectColumns($this->_select
, $groupByCol);
4717 if ($additionalWhereClause) {
4718 $where = $where . ' AND ' . $additionalWhereClause;
4721 //additional from clause should be w/ proper joins.
4722 if ($additionalFromClause) {
4723 $from .= "\n" . $additionalFromClause;
4726 // if we are doing a transform, do it here
4727 // use the $from, $where and $having to get the contact ID
4728 if ($this->_displayRelationshipType
) {
4729 $this->filterRelatedContacts($from, $where, $having);
4732 if ($skipOrderAndLimit) {
4733 $query = "$select $from $where $having $groupBy";
4736 $query = "$select $from $where $having $groupBy $order $limit";
4743 return CRM_Core_DAO
::singleValueQuery($query);
4746 $dao = CRM_Core_DAO
::executeQuery($query);
4747 if ($groupContacts) {
4749 while ($dao->fetch()) {
4753 return implode(',', $ids);
4760 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4762 * @param string $cacheKey
4763 * @param int $offset
4764 * @param int $rowCount
4765 * @param bool $includeContactIds
4766 * @return CRM_Core_DAO
4768 public function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4769 $this->_includeContactIds
= $includeContactIds;
4770 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4771 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
4772 $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);
4773 $order = " ORDER BY pnc.id";
4774 $groupByCol = array('contact_a.id', 'pnc.id');
4775 $groupBy = self
::getGroupByFromSelectColumns($this->_select
, $groupByCol);
4776 $limit = " LIMIT $offset, $rowCount";
4777 $query = "$select $from $where $groupBy $order $limit";
4779 return CRM_Core_DAO
::executeQuery($query);
4783 * Populate $this->_permissionWhereClause with permission related clause and update other
4784 * query related properties.
4786 * Function calls ACL permission class and hooks to filter the query appropriately
4788 * Note that these 2 params were in the code when extracted from another function
4789 * and a second round extraction would be to make them properties of the class
4791 * @param bool $onlyDeleted
4792 * Only get deleted contacts.
4793 * @param bool $count
4794 * Return Count only.
4796 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4797 if (!$this->_skipPermission
) {
4798 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4799 CRM_Core_Permission
::VIEW
,
4801 $this->_whereTables
,
4804 $this->_skipDeleteClause
4807 // regenerate fromClause since permission might have added tables
4808 if ($this->_permissionWhereClause
) {
4809 //fix for row count in qill (in contribute/membership find)
4811 $this->_useDistinct
= TRUE;
4814 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4815 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4816 // note : this modifies _fromClause and _simpleFromClause
4817 $this->includePseudoFieldsJoin($this->_sort
);
4821 // add delete clause if needed even if we are skipping permission
4823 if (!$this->_skipDeleteClause
) {
4824 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4825 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4829 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4838 public function setSkipPermission($val) {
4839 $this->_skipPermission
= $val;
4843 * @param null $context
4847 public function &summaryContribution($context = NULL) {
4848 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4852 SELECT COUNT( conts.total_amount ) as total_count,
4853 SUM( conts.total_amount ) as total_amount,
4854 AVG( conts.total_amount ) as total_avg,
4855 conts.currency as currency";
4856 if ($this->_permissionWhereClause
) {
4857 $where .= " AND " . $this->_permissionWhereClause
;
4859 if ($context == 'search') {
4860 $where .= " AND contact_a.is_deleted = 0 ";
4862 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
4863 if (!empty($financialTypes)) {
4864 $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
4865 $from .= " LEFT JOIN civicrm_line_item li
4866 ON civicrm_contribution.id = li.contribution_id AND
4867 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
4870 $where .= " AND civicrm_contribution.financial_type_id IN (0)";
4873 // make sure contribution is completed - CRM-4989
4874 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4877 $summary['total'] = array();
4878 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4879 $innerQuery = "SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
4880 civicrm_contribution.currency $from $completedWhere";
4881 $query = "$select FROM (
4882 $innerQuery GROUP BY civicrm_contribution.id
4886 $dao = CRM_Core_DAO
::executeQuery($query);
4888 $summary['total']['count'] = 0;
4889 $summary['total']['amount'] = $summary['total']['avg'] = array();
4890 while ($dao->fetch()) {
4891 $summary['total']['count'] +
= $dao->total_count
;
4892 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4893 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4896 $orderBy = 'ORDER BY civicrm_contribution_total_amount_count DESC';
4897 $groupBy = 'GROUP BY currency, civicrm_contribution.total_amount';
4898 $modeSQL = "$select, SUBSTRING_INDEX(GROUP_CONCAT(conts.total_amount
4899 ORDER BY conts.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
4900 MAX(conts.civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count
4902 $groupBy $orderBy) as conts
4905 $summary['total']['mode'] = CRM_Contribute_BAO_Contribution
::computeStats('mode', $modeSQL);
4907 $medianSQL = "{$from} {$completedWhere}";
4908 $summary['total']['median'] = CRM_Contribute_BAO_Contribution
::computeStats('median', $medianSQL, 'civicrm_contribution');
4909 $summary['total']['currencyCount'] = count($summary['total']['median']);
4911 if (!empty($summary['total']['amount'])) {
4912 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4913 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4914 $summary['total']['mode'] = implode(', ', $summary['total']['mode']);
4915 $summary['total']['median'] = implode(', ', $summary['total']['median']);
4918 $summary['total']['amount'] = $summary['total']['avg'] = $summary['total']['median'] = 0;
4921 // soft credit summary
4922 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
4923 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
4926 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
4927 GROUP BY civicrm_contribution_soft.id
4930 $dao = CRM_Core_DAO
::executeQuery($query);
4931 $summary['soft_credit']['count'] = 0;
4932 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
4933 while ($dao->fetch()) {
4934 $summary['soft_credit']['count'] +
= $dao->total_count
;
4935 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4936 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4938 if (!empty($summary['soft_credit']['amount'])) {
4939 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
4940 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
4943 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
4948 //@todo - this could be one query using the IF in mysql - eg
4949 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
4950 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
4951 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
4952 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
4953 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
4954 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
4955 // FROM civicrm_contact contact_a
4956 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
4957 // WHERE ( ... where clause....
4958 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
4962 SELECT COUNT( conts.total_amount ) as cancel_count,
4963 SUM( conts.total_amount ) as cancel_amount,
4964 AVG( conts.total_amount ) as cancel_avg,
4965 conts.currency as currency";
4967 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4968 if ($context == 'search') {
4969 $where .= " AND contact_a.is_deleted = 0 ";
4972 $query = "$select FROM (
4973 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
4974 GROUP BY civicrm_contribution.id
4978 $dao = CRM_Core_DAO
::executeQuery($query);
4981 if ($dao->fetch()) {
4982 $summary['cancel']['count'] = $dao->cancel_count
;
4983 $summary['cancel']['amount'] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4984 $summary['cancel']['avg'] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4988 $summary['cancel']['count'] = 0;
4989 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4990 while ($dao->fetch()) {
4991 $summary['cancel']['count'] +
= $dao->cancel_count
;
4992 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4993 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4995 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4996 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
5003 * Getter for the qill object.
5007 public function qill() {
5008 return $this->_qill
;
5012 * Default set of return default hier return properties.
5016 public static function &defaultHierReturnProperties() {
5017 if (!isset(self
::$_defaultHierReturnProperties)) {
5018 self
::$_defaultHierReturnProperties = array(
5021 'legal_identifier' => 1,
5022 'external_identifier' => 1,
5023 'contact_type' => 1,
5024 'contact_sub_type' => 1,
5026 'display_name' => 1,
5033 'formal_title' => 1,
5034 'communication_style_id' => 1,
5035 'email_greeting' => 1,
5036 'postal_greeting' => 1,
5040 'preferred_communication_method' => 1,
5041 'do_not_phone' => 1,
5042 'do_not_email' => 1,
5045 'do_not_trade' => 1,
5046 'location' => array(
5048 'location_type' => 1,
5049 'street_address' => 1,
5051 'state_province' => 1,
5053 'postal_code_suffix' => 1,
5056 'phone-Mobile' => 1,
5069 'location_type' => 1,
5070 'street_address' => 1,
5072 'state_province' => 1,
5074 'postal_code_suffix' => 1,
5077 'phone-Mobile' => 1,
5091 return self
::$_defaultHierReturnProperties;
5095 * Build query for a date field.
5097 * @param array $values
5098 * @param string $tableName
5099 * @param string $fieldName
5100 * @param string $dbFieldName
5101 * @param string $fieldTitle
5102 * @param bool $appendTimeStamp
5104 public function dateQueryBuilder(
5105 &$values, $tableName, $fieldName,
5106 $dbFieldName, $fieldTitle,
5107 $appendTimeStamp = TRUE
5109 list($name, $op, $value, $grouping, $wildcard) = $values;
5111 if ($name == "{$fieldName}_low" ||
5112 $name == "{$fieldName}_high"
5114 if (isset($this->_rangeCache
[$fieldName]) ||
!$value) {
5117 $this->_rangeCache
[$fieldName] = 1;
5119 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
5121 if ($name == $fieldName . '_low') {
5123 $firstPhrase = ts('greater than or equal to');
5124 $firstDate = CRM_Utils_Date
::processDate($value);
5126 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5127 if (!empty($secondValues) && $secondValues[2]) {
5129 $secondPhrase = ts('less than or equal to');
5130 $secondValue = $secondValues[2];
5132 if ($appendTimeStamp && strlen($secondValue) == 10) {
5133 $secondValue .= ' 23:59:59';
5135 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5138 elseif ($name == $fieldName . '_high') {
5140 $firstPhrase = ts('less than or equal to');
5142 if ($appendTimeStamp && strlen($value) == 10) {
5143 $value .= ' 23:59:59';
5145 $firstDate = CRM_Utils_Date
::processDate($value);
5147 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5148 if (!empty($secondValues) && $secondValues[2]) {
5150 $secondPhrase = ts('greater than or equal to');
5151 $secondValue = $secondValues[2];
5152 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5156 if (!$appendTimeStamp) {
5157 $firstDate = substr($firstDate, 0, 8);
5159 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5162 if (!$appendTimeStamp) {
5163 $secondDate = substr($secondDate, 0, 8);
5165 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5168 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5170 $this->_where
[$grouping][] = "
5171 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5172 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5174 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5177 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5178 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5182 if ($name == $fieldName) {
5183 //In Get API, for operators other then '=' the $value is in array(op => value) format
5184 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5186 $value = $value[$op];
5189 $date = $format = NULL;
5190 if (strstr($op, 'IN')) {
5192 foreach ($value as &$date) {
5193 $date = CRM_Utils_Date
::processDate($date);
5194 if (!$appendTimeStamp) {
5195 $date = substr($date, 0, 8);
5197 $format[] = CRM_Utils_Date
::customFormat($date);
5199 $date = "('" . implode("','", $value) . "')";
5200 $format = implode(', ', $format);
5202 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5203 $date = CRM_Utils_Date
::processDate($value);
5204 if (!$appendTimeStamp) {
5205 $date = substr($date, 0, 8);
5207 $format = CRM_Utils_Date
::customFormat($date);
5212 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5215 $this->_where
[$grouping][] = self
::buildClause("{$tableName}.{$dbFieldName}", $op);
5218 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5220 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
5221 $this->_qill
[$grouping][] = "$fieldTitle $op $format";
5227 * @param string $tableName
5228 * @param string $fieldName
5229 * @param string $dbFieldName
5230 * @param $fieldTitle
5231 * @param null $options
5233 public function numberRangeBuilder(
5235 $tableName, $fieldName,
5236 $dbFieldName, $fieldTitle,
5239 list($name, $op, $value, $grouping, $wildcard) = $values;
5241 if ($name == "{$fieldName}_low" ||
5242 $name == "{$fieldName}_high"
5244 if (isset($this->_rangeCache
[$fieldName])) {
5247 $this->_rangeCache
[$fieldName] = 1;
5249 $secondOP = $secondPhrase = $secondValue = NULL;
5251 if ($name == "{$fieldName}_low") {
5253 $firstPhrase = ts('greater than');
5255 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5256 if (!empty($secondValues)) {
5258 $secondPhrase = ts('less than');
5259 $secondValue = $secondValues[2];
5264 $firstPhrase = ts('less than');
5266 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5267 if (!empty($secondValues)) {
5269 $secondPhrase = ts('greater than');
5270 $secondValue = $secondValues[2];
5275 $this->_where
[$grouping][] = "
5276 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5277 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5279 $displayValue = $options ?
$options[$value] : $value;
5280 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5282 $this->_qill
[$grouping][]
5283 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5286 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5287 $displayValue = $options ?
$options[$value] : $value;
5288 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5290 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5295 if ($name == $fieldName) {
5299 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5301 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5302 $displayValue = $options ?
$options[$value] : $value;
5303 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5310 * @param string $tableName
5311 * @param string $fieldName
5312 * @param string $dbFieldName
5313 * @param $fieldTitle
5314 * @param null $options
5316 public function ageRangeQueryBuilder(
5318 $tableName, $fieldName,
5319 $dbFieldName, $fieldTitle,
5322 list($name, $op, $value, $grouping, $wildcard) = $values;
5324 $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
5325 $asofDate = NULL; // will be treated as current day
5326 if ($asofDateValues) {
5327 $asofDate = CRM_Utils_Date
::processDate($asofDateValues[2]);
5328 $asofDateFormat = CRM_Utils_Date
::customFormat(substr($asofDate, 0, 8));
5329 $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat;
5332 if ($name == "{$fieldName}_low" ||
5333 $name == "{$fieldName}_high"
5335 if (isset($this->_rangeCache
[$fieldName])) {
5338 $this->_rangeCache
[$fieldName] = 1;
5340 $secondOP = $secondPhrase = $secondValue = NULL;
5342 if ($name == "{$fieldName}_low") {
5343 $firstPhrase = ts('greater than or equal to');
5344 // NB: age > X means date of birth < Y
5346 $firstDate = self
::calcDateFromAge($asofDate, $value, 'min');
5348 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5349 if (!empty($secondValues)) {
5351 $secondPhrase = ts('less than or equal to');
5352 $secondValue = $secondValues[2];
5353 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'max');
5358 $firstPhrase = ts('less than or equal to');
5359 $firstDate = self
::calcDateFromAge($asofDate, $value, 'max');
5361 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5362 if (!empty($secondValues)) {
5364 $secondPhrase = ts('greater than or equal to');
5365 $secondValue = $secondValues[2];
5366 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'min');
5371 $this->_where
[$grouping][] = "
5372 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5373 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5375 $displayValue = $options ?
$options[$value] : $value;
5376 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5378 $this->_qill
[$grouping][]
5379 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5382 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5383 $displayValue = $options ?
$options[$value] : $value;
5384 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5386 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5392 * Calculate date from age.
5394 * @param string $asofDate
5396 * @param string $type
5400 public static function calcDateFromAge($asofDate, $age, $type) {
5401 $date = new DateTime($asofDate);
5402 if ($type == "min") {
5403 // minimum age is $age: dob <= date - age "235959"
5404 $date->sub(new DateInterval("P" . $age . "Y"));
5405 return $date->format('Ymd') . "235959";
5408 // max age is $age: dob >= date - (age + 1y) + 1d "000000"
5409 $date->sub(new DateInterval("P" . ($age +
1) . "Y"))->add(new DateInterval("P1D"));
5410 return $date->format('Ymd') . "000000";
5415 * Given the field name, operator, value & its data type
5416 * builds the where Clause for the query
5417 * used for handling 'IS NULL'/'IS NOT NULL' operators
5419 * @param string $field
5423 * @param string $value
5425 * @param string $dataType
5426 * Data type of the field.
5429 * Where clause for the query.
5431 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5433 $clause = "$field $op";
5441 $clause = " (NULLIF($field, '') IS NULL) ";
5444 case 'IS NOT EMPTY':
5445 $clause = " (NULLIF($field, '') IS NOT NULL) ";
5450 // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
5451 if (!empty($value) && (!is_array($value) ||
!array_key_exists($op, $value))) {
5452 $value = array($op => (array) $value);
5456 if (empty($dataType)) {
5457 $dataType = 'String';
5459 if (is_array($value)) {
5460 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5461 // widely used and consistent across the codebase
5462 // adding this here won't accept the search functions which don't submit an array
5463 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, $value, $dataType)) != FALSE) {
5465 return $queryString;
5468 // 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))
5469 // but we got only array(2,5) from the form.
5470 // We could get away with keeping this in 4.6 if we make it such that it throws an enotice in 4.7 so
5471 // people have to de-slopify it.
5472 if (!empty($value[0])) {
5473 if ($op != 'BETWEEN') {
5474 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReport;
5476 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => $value), $dataType)) != FALSE) {
5477 return $queryString;
5482 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReportUsingOldFormat;
5483 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => array_keys($value)), $dataType)) != FALSE) {
5484 return $queryString;
5489 $value = CRM_Utils_Type
::escape($value, $dataType);
5490 // if we don't have a dataType we should assume
5491 if ($dataType == 'String' ||
$dataType == 'Text') {
5492 $value = "'" . strtolower($value) . "'";
5494 return "$clause $value";
5499 * @param bool $reset
5503 public function openedSearchPanes($reset = FALSE) {
5504 if (!$reset ||
empty($this->_whereTables
)) {
5505 return self
::$_openedPanes;
5508 // pane name to table mapper
5509 $panesMapper = array(
5510 ts('Contributions') => 'civicrm_contribution',
5511 ts('Memberships') => 'civicrm_membership',
5512 ts('Events') => 'civicrm_participant',
5513 ts('Relationships') => 'civicrm_relationship',
5514 ts('Activities') => 'civicrm_activity',
5515 ts('Pledges') => 'civicrm_pledge',
5516 ts('Cases') => 'civicrm_case',
5517 ts('Grants') => 'civicrm_grant',
5518 ts('Address Fields') => 'civicrm_address',
5519 ts('Notes') => 'civicrm_note',
5520 ts('Change Log') => 'civicrm_log',
5521 ts('Mailings') => 'civicrm_mailing',
5523 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5525 foreach (array_keys($this->_whereTables
) as $table) {
5526 if ($panName = array_search($table, $panesMapper)) {
5527 self
::$_openedPanes[$panName] = TRUE;
5531 return self
::$_openedPanes;
5537 public function setOperator($operator) {
5538 $validOperators = array('AND', 'OR');
5539 if (!in_array($operator, $validOperators)) {
5542 $this->_operator
= $operator;
5548 public function getOperator() {
5549 return $this->_operator
;
5557 public function filterRelatedContacts(&$from, &$where, &$having) {
5558 static $_rTypeProcessed = NULL;
5559 static $_rTypeFrom = NULL;
5560 static $_rTypeWhere = NULL;
5562 if (!$_rTypeProcessed) {
5563 $_rTypeProcessed = TRUE;
5565 // create temp table with contact ids
5566 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5567 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5568 CRM_Core_DAO
::executeQuery($sql);
5571 REPLACE INTO $tableName ( contact_id )
5577 CRM_Core_DAO
::executeQuery($sql);
5579 $qillMessage = ts('Contacts with a Relationship Type of: ');
5580 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5582 if (is_numeric($this->_displayRelationshipType
)) {
5583 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5585 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5586 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5589 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5590 AND displayRelType.is_active = 1
5594 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5595 if ($dirOne == 'a') {
5596 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5598 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5599 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5603 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5605 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5606 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5610 WHERE displayRelType.relationship_type_id = $relType
5611 AND displayRelType.is_active = 1
5614 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5617 if (!empty($this->_permissionWhereClause
)) {
5618 $_rTypeWhere .= "AND $this->_permissionWhereClause";
5621 if (strpos($from, $_rTypeFrom) === FALSE) {
5622 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5623 // this happens when we have an event_type in the quert (CRM-7969)
5624 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5625 $from .= $_rTypeFrom;
5626 $where = $_rTypeWhere;
5637 public static function caseImportant($op) {
5639 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5643 * @param $returnProperties
5648 public static function componentPresent(&$returnProperties, $prefix) {
5649 foreach ($returnProperties as $name => $dontCare) {
5650 if (substr($name, 0, strlen($prefix)) == $prefix) {
5658 * Builds the necessary structures for all fields that are similar to option value look-ups.
5660 * @param string $name
5661 * the name of the field.
5663 * the sql operator, this function should handle ALL SQL operators.
5664 * @param string $value
5665 * depends on the operator and who's calling the query builder.
5666 * @param int $grouping
5667 * the index where to place the where clause.
5668 * @param string $daoName
5670 * @param array $field
5671 * an array that contains various properties of the field identified by $name.
5672 * @param string $label
5673 * The label for this field element.
5674 * @param string $dataType
5675 * The data type for this element.
5676 * @param bool $useIDsOnly
5678 public function optionValueQuery(
5686 $dataType = 'String',
5690 $pseudoFields = array(
5697 'communication_style_id',
5701 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5702 if ($tableName == 'civicrm_contact') {
5703 $wc = "contact_a.$fieldName";
5706 $wc = "$tableName.id";
5710 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5712 if (in_array($name, $pseudoFields)) {
5713 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5714 $wc = "contact_a.{$name}_id";
5716 $dataType = 'Positive';
5717 $value = (!$value) ?
0 : $value;
5719 if ($name == "world_region") {
5720 $field['name'] = $name;
5723 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue($daoName, $field['name'], $value, $op);
5724 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillop, 3 => $qillVal));
5725 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5729 * Check and explode a user defined numeric string into an array
5730 * this was the protocol used by search builder in the old old days before we had
5731 * super nice js widgets to do the hard work
5733 * @param string $string
5734 * @param string $dataType
5735 * The dataType we should check for the values, default integer.
5737 * @return bool|array
5738 * false if string does not match the pattern
5739 * array of numeric values if string does match the pattern
5741 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5742 $string = trim($string);
5743 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5747 $string = substr($string, 1, -1);
5748 $values = explode(',', $string);
5749 if (empty($values)) {
5753 $returnValues = array();
5754 foreach ($values as $v) {
5755 if ($dataType == 'Integer' && !is_numeric($v)) {
5758 elseif ($dataType == 'String' && !is_string($v)) {
5761 $returnValues[] = trim($v);
5764 if (empty($returnValues)) {
5768 return $returnValues;
5772 * Convert the pseudo constants id's to their names
5774 * @param CRM_Core_DAO $dao
5775 * @param bool $return
5776 * @param bool $usedForAPI
5778 * @return array|NULL
5780 public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) {
5781 if (empty($this->_pseudoConstantsSelect
)) {
5785 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5786 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5790 if (is_object($dao) && property_exists($dao, $value['idCol'])) {
5791 $val = $dao->{$value['idCol']};
5792 if ($key == 'groups') {
5793 $dao->groups
= $this->convertGroupIDStringToLabelString($dao, $val);
5797 if (CRM_Utils_System
::isNull($val)) {
5800 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5802 $idColumn = "{$key}_id";
5803 $dao->$idColumn = $val;
5805 if ($key == 'state_province_name') {
5806 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5809 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5812 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5813 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5815 // FIX ME: we should potentially move this to component Query and write a wrapper function that
5816 // handles pseudoconstant fixes for all component
5817 elseif (in_array($value['pseudoField'], array('participant_role_id', 'participant_role'))) {
5818 $viewValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val);
5820 if ($value['pseudoField'] == 'participant_role') {
5821 $pseudoOptions = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'role_id');
5822 foreach ($viewValues as $k => $v) {
5823 $viewValues[$k] = $pseudoOptions[$v];
5826 $dao->$key = ($usedForAPI && count($viewValues) > 1) ?
$viewValues : implode(', ', $viewValues);
5829 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5830 $dao->$key = $labels[$val];
5833 // return converted values in array format
5835 if (strpos($key, '-') !== FALSE) {
5836 $keyVal = explode('-', $key);
5837 $current = &$values;
5838 $lastElement = array_pop($keyVal);
5839 foreach ($keyVal as $v) {
5840 if (!array_key_exists($v, $current)) {
5841 $current[$v] = array();
5843 $current = &$current[$v];
5845 $current[$lastElement] = $dao->$key;
5848 $values[$key] = $dao->$key;
5857 * Include pseudo fields LEFT JOIN.
5858 * @param string|array $sort can be a object or string
5860 * @return array|NULL
5862 public function includePseudoFieldsJoin($sort) {
5863 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5866 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5869 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5870 if (!empty($value['table'])) {
5871 $regex = "/({$value['table']}\.|{$name})/";
5872 if (preg_match($regex, $sort)) {
5873 $this->_elemnt
[$value['element']] = 1;
5874 $this->_select
[$value['element']] = $value['select'];
5875 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5876 $present[$value['table']] = $value['join'];
5880 $presentSimpleFrom = $present;
5882 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5883 array_key_exists('civicrm_country', $presentSimpleFrom)
5885 unset($presentSimpleFrom['civicrm_country']);
5887 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5888 array_key_exists('civicrm_country', $present)
5890 unset($present['civicrm_country']);
5893 $presentClause = $presentSimpleFromClause = NULL;
5894 if (!empty($present)) {
5895 $presentClause = implode(' ', $present);
5897 if (!empty($presentSimpleFrom)) {
5898 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5901 $this->_fromClause
= $this->_fromClause
. $presentClause;
5902 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5904 return array($presentClause, $presentSimpleFromClause);
5908 * Build qill for field.
5910 * Qill refers to the query detail visible on the UI.
5912 * @param string $daoName
5913 * @param string $fieldName
5914 * @param mixed $fieldValue
5916 * @param array $pseudoExtraParam
5918 * Type of the field per CRM_Utils_Type
5922 public static function buildQillForFieldValue(
5927 $pseudoExtraParam = array(),
5928 $type = CRM_Utils_Type
::T_STRING
5930 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
5932 // if Operator chosen is NULL/EMPTY then
5933 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
5934 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), '');
5937 if ($fieldName == 'activity_type_id') {
5938 $pseudoOptions = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
5940 elseif ($fieldName == 'country_id') {
5941 $pseudoOptions = CRM_Core_PseudoConstant
::country();
5943 elseif ($fieldName == 'county_id') {
5944 $pseudoOptions = CRM_Core_PseudoConstant
::county();
5946 elseif ($fieldName == 'world_region') {
5947 $pseudoOptions = CRM_Core_PseudoConstant
::worldRegion();
5949 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
5950 $pseudoOptions = CRM_Event_BAO_Event
::getEvents(0, $fieldValue, TRUE, TRUE, TRUE);
5952 elseif ($fieldName == 'contribution_product_id') {
5953 $pseudoOptions = CRM_Contribute_PseudoConstant
::products();
5955 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
5956 $pseudoOptions = CRM_Core_PseudoConstant
::group();
5959 $pseudoOptions = CRM_Core_PseudoConstant
::get($daoName, $fieldName, $pseudoExtraParam);
5962 //API usually have fieldValue format as array(operator => array(values)),
5963 //so we need to separate operator out of fieldValue param
5964 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5965 $op = key($fieldValue);
5966 $fieldValue = $fieldValue[$op];
5969 if (is_array($fieldValue)) {
5970 $qillString = array();
5971 if (!empty($pseudoOptions)) {
5972 foreach ((array) $fieldValue as $val) {
5973 $qillString[] = CRM_Utils_Array
::value($val, $pseudoOptions, $val);
5975 $fieldValue = implode(', ', $qillString);
5978 if ($type == CRM_Utils_Type
::T_DATE
) {
5979 foreach ($fieldValue as $index => $value) {
5980 $fieldValue[$index] = CRM_Utils_Date
::customFormat($value);
5984 // @todo - this is a bit specific (one operator).
5985 // However it is covered by a unit test so can be altered later with
5987 if ($op == 'BETWEEN') {
5988 $separator = ' AND ';
5990 $fieldValue = implode($separator, $fieldValue);
5993 elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) {
5994 $fieldValue = $pseudoOptions[$fieldValue];
5996 elseif ($type === CRM_Utils_Type
::T_DATE
) {
5997 $fieldValue = CRM_Utils_Date
::customFormat($fieldValue);
6000 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), $fieldValue);
6004 * Alter value to reflect wildcard settings.
6006 * The form will have tried to guess whether this is a good field to wildcard but there is
6007 * also a site-wide setting that specifies whether it is OK to append the wild card to the beginning
6008 * or only the end of the string
6010 * @param bool $wildcard
6011 * This is a bool made on an assessment 'elsewhere' on whether this is a good field to wildcard.
6013 * Generally '=' or 'LIKE'.
6014 * @param string $value
6015 * The search string.
6019 public static function getWildCardedValue($wildcard, $op, $value) {
6020 if ($wildcard && $op == 'LIKE') {
6021 if (CRM_Core_Config
::singleton()->includeWildCardInName
&& (substr($value, 0, 1) != '%')) {
6034 * Process special fields of Search Form in OK (Operator in Key) format
6036 * @param array $formValues
6037 * @param array $specialFields
6038 * Special params to be processed
6039 * @param array $changeNames
6040 * Array of fields whose name should be changed
6042 public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = array()) {
6043 foreach ($specialFields as $element) {
6044 $value = CRM_Utils_Array
::value($element, $formValues);
6046 if (is_array($value)) {
6047 if (in_array($element, array_keys($changeNames))) {
6048 unset($formValues[$element]);
6049 $element = $changeNames[$element];
6051 $formValues[$element] = array('IN' => $value);
6054 // if wildcard is already present return searchString as it is OR append and/or prepend with wildcard
6055 $isWilcard = strstr($value, '%') ?
FALSE : CRM_Core_Config
::singleton()->includeWildCardInName
;
6056 $formValues[$element] = array('LIKE' => self
::getWildCardedValue($isWilcard, 'LIKE', $value));
6063 * Parse and assimilate the various sort options.
6065 * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`,
6066 * `email`), the related table may be joined automatically.
6068 * At time of writing, this code is deeply flawed and should be rewritten. For the moment,
6069 * it's been extracted to a standalone function.
6071 * @param string|CRM_Utils_Sort $sort
6072 * The order by string.
6073 * @param bool $sortByChar
6074 * If true returns the distinct array of first characters for search results.
6075 * @param null $sortOrder
6076 * Who knows? Hu knows. He who knows Hu knows who.
6077 * @param string $additionalFromClause
6078 * Should be clause with proper joins, effective to reduce where clause load.
6080 * list(string $orderByClause, string $additionalFromClause).
6082 protected function prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause) {
6084 $config = CRM_Core_Config
::singleton();
6085 if ($config->includeOrderByClause ||
6086 isset($this->_distinctComponentClause
)
6089 if (is_string($sort)) {
6093 $orderBy = trim($sort->orderBy());
6095 // Deliberately remove the backticks again, as they mess up the evil
6096 // string munging below. This balanced by re-escaping before use.
6097 $orderBy = str_replace('`', '', $orderBy);
6099 if (!empty($orderBy)) {
6100 // this is special case while searching for
6101 // change log CRM-1718
6102 if (preg_match('/sort_name/i', $orderBy)) {
6103 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
6106 $order = " ORDER BY $orderBy";
6109 $order .= " $sortOrder";
6112 // always add contact_a.id to the ORDER clause
6113 // so the order is deterministic
6114 if (strpos('contact_a.id', $order) === FALSE) {
6115 $order .= ", contact_a.id";
6119 elseif ($sortByChar) {
6120 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
6123 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
6127 // hack for order clause
6129 $fieldStr = trim(str_replace('ORDER BY', '', $order));
6130 $fieldOrder = explode(' ', $fieldStr);
6131 $field = $fieldOrder[0];
6137 $this->_tables
["civicrm_address"] = $this->_whereTables
["civicrm_address"] = 1;
6138 $order = str_replace($field, "civicrm_address.{$field}", $order);
6142 case 'state_province':
6143 $this->_tables
["civicrm_{$field}"] = $this->_whereTables
["civicrm_{$field}"] = 1;
6144 if (is_array($this->_returnProperties
) && empty($this->_returnProperties
)) {
6145 $additionalFromClause .= " LEFT JOIN civicrm_{$field} ON civicrm_{$field}.id = civicrm_address.{$field}_id";
6147 $order = str_replace($field, "civicrm_{$field}.name", $order);
6151 $this->_tables
["civicrm_email"] = $this->_whereTables
["civicrm_email"] = 1;
6152 $order = str_replace($field, "civicrm_email.{$field}", $order);
6156 //CRM-12565 add "`" around $field if it is a pseudo constant
6157 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
6158 if (!empty($value['element']) && $value['element'] == $field) {
6159 $order = str_replace($field, "`{$field}`", $order);
6163 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6164 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6168 // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
6169 // clause. But this magic helper which forgivingly reescapes ORDER BY.
6170 // Note: $sortByChar implies that $order was hard-coded/trusted, so it can do funky things.
6171 if ($order && !$sortByChar) {
6172 $order = ' ORDER BY ' . CRM_Utils_Type
::escape(preg_replace('/^\s*ORDER BY\s*/', '', $order), 'MysqlOrderBy');
6173 return array($order, $additionalFromClause);
6175 return array($order, $additionalFromClause);
6179 * Convert a string of group IDs to a string of group labels.
6181 * The original string may include duplicates and groups the user does not have
6182 * permission to see.
6184 * @param CRM_Core_DAO $dao
6185 * @param string $val
6189 public function convertGroupIDStringToLabelString(&$dao, $val) {
6190 $groupIDs = explode(',', $val);
6192 // The pseudoConstant function does not actually cache.
6195 $allGroups = CRM_Core_PseudoConstant
::group();
6197 // Note that groups that the user does not have permission to will be excluded (good).
6198 $groups = array_intersect_key($allGroups, array_flip($groupIDs));
6199 return implode(', ', $groups);
6204 * Set the qill and where properties for a field.
6206 * This function is intended as a short-term function to encourage refactoring
6207 * & re-use - but really we should just have less special-casing.
6209 * @param string $name
6211 * @param string|array $value
6212 * @param string $grouping
6213 * @param string $field
6215 public function setQillAndWhere($name, $op, $value, $grouping, $field) {
6216 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
6217 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
6218 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(
6219 1 => $field['title'],