3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
37 * This is the heart of the search query building mechanism.
39 class CRM_Contact_BAO_Query
{
42 * The various search modes.
52 MODE_PLEDGEBANK
= 256,
61 * The default set of return properties.
65 static $_defaultReturnProperties = NULL;
68 * The default set of hier return properties.
72 static $_defaultHierReturnProperties;
75 * The set of input params.
87 * The set of output params
91 public $_returnProperties;
101 * The name of the elements that are in the select clause
102 * used to extract the values
109 * The tables involved in the query
116 * The table involved in the where clause
120 public $_whereTables;
134 public $_whereClause;
137 * Additional permission Where Clause
141 public $_permissionWhereClause;
151 * Additional permission from clause
155 public $_permissionFromClause;
158 * The from clause for the simple select and alphabetical
163 public $_simpleFromClause;
173 * The english language version of the query
180 * All the fields that could potentially be involved in
188 * The cache to translate the option values into labels.
195 * Are we in search mode.
199 public $_search = TRUE;
202 * Should we skip permission checking.
206 public $_skipPermission = FALSE;
209 * Should we skip adding of delete clause.
213 public $_skipDeleteClause = FALSE;
216 * Are we in strict mode (use equality over LIKE)
220 public $_strict = FALSE;
223 * What operator to use to group the clauses.
227 public $_operator = 'AND';
232 * Should we only search on primary location.
236 public $_primaryLocation = TRUE;
239 * Are contact ids part of the query.
243 public $_includeContactIds = FALSE;
246 * Should we use the smart group cache.
250 public $_smartGroupCache = TRUE;
253 * Should we display contacts with a specific relationship type.
257 public $_displayRelationshipType = NULL;
260 * Reference to the query object for custom values.
264 public $_customQuery;
267 * Should we enable the distinct clause, used if we are including
268 * more than one group
272 public $_useDistinct = FALSE;
275 * Should we just display one contact record
277 public $_useGroupBy = FALSE;
280 * The relationship type direction
291 static $_activityRole;
294 * Consider the component activity type
295 * during activity search.
299 static $_considerCompActivities;
302 * Consider with contact activities only,
303 * during activity search.
307 static $_withContactActivitiesOnly;
310 * Use distinct component clause for component searches
314 public $_distinctComponentClause;
316 public $_rowCountClause;
319 * Use groupBy component clause for component searches
323 public $_groupByComponentClause;
326 * Track open panes, useful in advance search
330 public static $_openedPanes = array();
333 * For search builder - which custom fields are location-dependent
336 public $_locationSpecificCustomFields = array();
339 * The tables which have a dependency on location and/or address
343 static $_dependencies = array(
344 'civicrm_state_province' => 1,
345 'civicrm_country' => 1,
346 'civicrm_county' => 1,
347 'civicrm_address' => 1,
348 'civicrm_location_type' => 1,
352 * List of location specific fields.
354 static $_locationSpecificFields = array(
359 'supplemental_address_1',
360 'supplemental_address_2',
363 '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
410 * @return \CRM_Contact_BAO_Query
412 public function __construct(
413 $params = NULL, $returnProperties = NULL, $fields = NULL,
414 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
415 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
416 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
419 $this->_params
= &$params;
420 if ($this->_params
== NULL) {
421 $this->_params
= array();
424 if (empty($returnProperties)) {
425 $this->_returnProperties
= self
::defaultReturnProperties($mode);
428 $this->_returnProperties
= &$returnProperties;
431 $this->_includeContactIds
= $includeContactIds;
432 $this->_strict
= $strict;
433 $this->_mode
= $mode;
434 $this->_skipPermission
= $skipPermission;
435 $this->_smartGroupCache
= $smartGroupCache;
436 $this->_displayRelationshipType
= $displayRelationshipType;
437 $this->setOperator($operator);
440 $this->_fields
= &$fields;
441 $this->_search
= FALSE;
442 $this->_skipPermission
= TRUE;
445 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE);
447 $fields = CRM_Core_Component
::getQueryFields();
448 unset($fields['note']);
449 $this->_fields
= array_merge($this->_fields
, $fields);
451 // add activity fields
452 $fields = CRM_Activity_BAO_Activity
::exportableFields();
453 $this->_fields
= array_merge($this->_fields
, $fields);
455 // add any fields provided by hook implementers
456 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
457 $this->_fields
= array_merge($this->_fields
, $extFields);
460 // basically do all the work once, and then reuse it
465 * Function which actually does all the work for the constructor.
469 public function initialize() {
470 $this->_select
= array();
471 $this->_element
= array();
472 $this->_tables
= array();
473 $this->_whereTables
= array();
474 $this->_where
= array();
475 $this->_qill
= array();
476 $this->_options
= array();
477 $this->_cfIDs
= array();
478 $this->_paramLookup
= array();
479 $this->_having
= array();
481 $this->_customQuery
= NULL;
483 // reset cached static variables - CRM-5803
484 self
::$_activityRole = NULL;
485 self
::$_considerCompActivities = NULL;
486 self
::$_withContactActivitiesOnly = NULL;
488 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
489 $this->_element
['contact_id'] = 1;
490 $this->_tables
['civicrm_contact'] = 1;
492 if (!empty($this->_params
)) {
493 $this->buildParamsLookup();
496 $this->_whereTables
= $this->_tables
;
498 $this->selectClause();
499 $this->_whereClause
= $this->whereClause();
501 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
502 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
504 $this->openedSearchPanes(TRUE);
507 public function buildParamsLookup() {
508 // first fix and handle contact deletion nicely
509 // this code is primarily for search builder use case
510 // where different clauses can specify if they want deleted
513 $trashParamExists = FALSE;
514 $paramByGroup = array();
515 foreach ($this->_params
as $k => $param) {
516 if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
517 $trashParamExists = TRUE;
519 if (!empty($param[3])) {
520 $paramByGroup[$param[3]][$k] = $param;
524 if ($trashParamExists) {
525 $this->_skipDeleteClause
= TRUE;
527 //cycle through group sets and explicitly add trash param if not set
528 foreach ($paramByGroup as $setID => $set) {
530 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params
) &&
531 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params
)
533 $this->_params
[] = array(
534 'contact_is_deleted',
544 foreach ($this->_params
as $value) {
545 if (empty($value[0])) {
548 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
550 if (!array_key_exists($cfID, $this->_cfIDs
)) {
551 $this->_cfIDs
[$cfID] = array();
553 // Set wildcard value based on "and/or" selection
554 foreach ($this->_params
as $key => $param) {
555 if ($param[0] == $value[0] . '_operator') {
556 $value[4] = $param[2] == 'or';
560 $this->_cfIDs
[$cfID][] = $value;
563 if (!array_key_exists($value[0], $this->_paramLookup
)) {
564 $this->_paramLookup
[$value[0]] = array();
566 $this->_paramLookup
[$value[0]][] = $value;
571 * Some composite fields do not appear in the fields array
572 * hack to make them part of the query
576 public function addSpecialFields() {
577 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
578 foreach ($special as $name) {
579 if (!empty($this->_returnProperties
[$name])) {
580 $this->_select
[$name] = "contact_a.{$name} as $name";
581 $this->_element
[$name] = 1;
587 * Given a list of conditions in params and a list of desired
588 * return Properties generate the required select and from
589 * clauses. Note that since the where clause introduces new
590 * tables, the initial attempt also retrieves all variables used
595 public function selectClause() {
597 $this->addSpecialFields();
599 foreach ($this->_fields
as $name => $field) {
600 // skip component fields
601 // there are done by the alter query below
602 // and need not be done on every field
604 (substr($name, 0, 12) == 'participant_') ||
605 (substr($name, 0, 7) == 'pledge_') ||
606 (substr($name, 0, 5) == 'case_') ||
607 (substr($name, 0, 13) == 'contribution_' &&
608 (strpos($name, 'source') !== FALSE && strpos($name, 'recur') !== FALSE)) ||
609 (substr($name, 0, 8) == 'payment_')
614 // redirect to activity select clause
616 (substr($name, 0, 9) == 'activity_') ||
617 ($name == 'parent_id')
619 CRM_Activity_BAO_Query
::select($this);
623 // if this is a hierarchical name, we ignore it
624 $names = explode('-', $name);
625 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
629 // make an exception for special cases, to add the field in select clause
630 $makeException = FALSE;
632 //special handling for groups/tags
633 if (in_array($name, array('groups', 'tags', 'notes'))
634 && isset($this->_returnProperties
[substr($name, 0, -1)])
636 $makeException = TRUE;
639 // since note has 3 different options we need special handling
640 // note / note_subject / note_body
641 if ($name == 'notes') {
642 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
643 if (isset($this->_returnProperties
[$noteField])) {
644 $makeException = TRUE;
650 if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id', 'communication_style_id'))) {
651 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
652 $makeException = TRUE;
656 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
657 if (!empty($this->_paramLookup
[$name]) ||
!empty($this->_returnProperties
[$name]) ||
661 // add to cfIDs array if not present
662 if (!array_key_exists($cfID, $this->_cfIDs
)) {
663 $this->_cfIDs
[$cfID] = array();
666 elseif (isset($field['where'])) {
667 list($tableName, $fieldName) = explode('.', $field['where'], 2);
668 if (isset($tableName)) {
669 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
670 $this->_tables
['civicrm_address'] = 1;
671 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
672 $this->_element
['address_id'] = 1;
675 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
676 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
678 if ($tableName == 'im_provider') {
679 CRM_Core_OptionValue
::select($this);
682 if (in_array($tableName,
683 array('email_greeting', 'postal_greeting', 'addressee'))) {
684 $this->_element
["{$name}_id"] = 1;
685 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
686 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
687 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
688 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
690 if ($tableName == 'email_greeting') {
691 $this->_pseudoConstantsSelect
[$name]['join']
692 = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
693 $this->_pseudoConstantsSelect
[$name]['join'] .=
694 " 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 ) ";
696 elseif ($tableName == 'postal_greeting') {
697 $this->_pseudoConstantsSelect
[$name]['join']
698 = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
699 $this->_pseudoConstantsSelect
[$name]['join'] .=
700 " 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 ) ";
702 elseif ($tableName == 'addressee') {
703 $this->_pseudoConstantsSelect
[$name]['join']
704 = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
705 $this->_pseudoConstantsSelect
[$name]['join'] .=
706 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
708 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
711 $greetField = "{$name}_display";
712 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
713 $this->_element
[$greetField] = 1;
715 $greetField = "{$name}_custom";
716 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
717 $this->_element
[$greetField] = 1;
721 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
722 $this->_tables
[$tableName] = 1;
725 // also get the id of the tableName
726 $tName = substr($tableName, 8);
727 if (in_array($tName, array('country', 'state_province', 'county'))) {
728 if ($tName == 'state_province') {
729 $this->_pseudoConstantsSelect
['state_province_name'] = array(
730 'pseudoField' => "{$tName}",
731 'idCol' => "{$tName}_id",
732 'bao' => 'CRM_Core_BAO_Address',
733 'table' => "civicrm_{$tName}",
734 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
737 $this->_pseudoConstantsSelect
[$tName] = array(
738 'pseudoField' => 'state_province_abbreviation',
739 'idCol' => "{$tName}_id",
740 'table' => "civicrm_{$tName}",
741 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
745 $this->_pseudoConstantsSelect
[$name] = array(
746 'pseudoField' => "{$tName}_id",
747 'idCol' => "{$tName}_id",
748 'bao' => 'CRM_Core_BAO_Address',
749 'table' => "civicrm_{$tName}",
750 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
754 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
755 $this->_element
["{$tName}_id"] = 1;
757 elseif ($tName != 'contact') {
758 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
759 $this->_element
["{$tName}_id"] = 1;
762 //special case for phone
763 if ($name == 'phone') {
764 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
765 $this->_element
['phone_type_id'] = 1;
768 // if IM then select provider_id also
769 // to get "IM Service Provider" in a file to be exported, CRM-3140
771 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
772 $this->_element
['provider_id'] = 1;
775 if ($tName == 'contact') {
776 // special case, when current employer is set for Individual contact
777 if ($fieldName == 'organization_name') {
778 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
780 elseif ($fieldName != 'id') {
781 if ($fieldName == 'prefix_id') {
782 $this->_pseudoConstantsSelect
['individual_prefix'] = array(
783 'pseudoField' => 'prefix_id',
784 'idCol' => "prefix_id",
785 'bao' => 'CRM_Contact_BAO_Contact',
788 if ($fieldName == 'suffix_id') {
789 $this->_pseudoConstantsSelect
['individual_suffix'] = array(
790 'pseudoField' => 'suffix_id',
791 'idCol' => "suffix_id",
792 'bao' => 'CRM_Contact_BAO_Contact',
795 if ($fieldName == 'gender_id') {
796 $this->_pseudoConstantsSelect
['gender'] = array(
797 'pseudoField' => 'gender_id',
798 'idCol' => "gender_id",
799 'bao' => 'CRM_Contact_BAO_Contact',
802 if ($name == 'communication_style_id') {
803 $this->_pseudoConstantsSelect
['communication_style'] = array(
804 'pseudoField' => 'communication_style_id',
805 'idCol' => "communication_style_id",
806 'bao' => 'CRM_Contact_BAO_Contact',
809 $this->_select
[$name] = "contact_a.{$fieldName} as `$name`";
812 elseif (in_array($tName, array('country', 'county'))) {
813 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
814 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
816 elseif ($tName == 'state_province') {
817 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
818 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
821 $this->_select
[$name] = "{$field['where']} as `$name`";
823 if (!in_array($tName, array('state_province', 'country', 'county'))) {
824 $this->_element
[$name] = 1;
829 elseif ($name === 'tags') {
830 $this->_useGroupBy
= TRUE;
831 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
832 $this->_element
[$name] = 1;
833 $this->_tables
['civicrm_tag'] = 1;
834 $this->_tables
['civicrm_entity_tag'] = 1;
836 elseif ($name === 'groups') {
837 $this->_useGroupBy
= TRUE;
838 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
839 $this->_element
[$name] = 1;
840 $this->_tables
['civicrm_group'] = 1;
842 elseif ($name === 'notes') {
843 // if note field is subject then return subject else body of the note
844 $noteColumn = 'note';
845 if (isset($noteField) && $noteField == 'note_subject') {
846 $noteColumn = 'subject';
849 $this->_useGroupBy
= TRUE;
850 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
851 $this->_element
[$name] = 1;
852 $this->_tables
['civicrm_note'] = 1;
854 elseif ($name === 'current_employer') {
855 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
856 $this->_element
[$name] = 1;
860 if ($cfID && !empty($field['is_search_range'])) {
861 // this is a custom field with range search enabled, so we better check for two/from values
862 if (!empty($this->_paramLookup
[$name . '_from'])) {
863 if (!array_key_exists($cfID, $this->_cfIDs
)) {
864 $this->_cfIDs
[$cfID] = array();
866 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
867 // search in the cdID array for the same grouping
869 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
870 if ($c[3] == $p[3]) {
871 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
876 $p[2] = array('from' => $p[2]);
877 $this->_cfIDs
[$cfID][] = $p;
881 if (!empty($this->_paramLookup
[$name . '_to'])) {
882 if (!array_key_exists($cfID, $this->_cfIDs
)) {
883 $this->_cfIDs
[$cfID] = array();
885 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
886 // search in the cdID array for the same grouping
888 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
889 if ($c[4] == $p[4]) {
890 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
895 $p[2] = array('to' => $p[2]);
896 $this->_cfIDs
[$cfID][] = $p;
903 // add location as hierarchical elements
904 $this->addHierarchicalElements();
906 // add multiple field like website
907 $this->addMultipleElements();
910 CRM_Core_Component
::alterQuery($this, 'select');
912 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
914 if (!empty($this->_cfIDs
)) {
915 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
916 $this->_customQuery
->query();
917 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
918 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
919 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
920 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
921 $this->_options
= $this->_customQuery
->_options
;
926 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
931 public function addHierarchicalElements() {
932 if (empty($this->_returnProperties
['location'])) {
935 if (!is_array($this->_returnProperties
['location'])) {
939 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
940 $processed = array();
943 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
944 $addressCustomFieldIds = array();
946 foreach ($this->_returnProperties
['location'] as $name => $elements) {
947 $lCond = self
::getPrimaryCondition($name);
950 $locationTypeId = array_search($name, $locationTypes);
951 if ($locationTypeId === FALSE) {
954 $lCond = "location_type_id = $locationTypeId";
955 $this->_useDistinct
= TRUE;
957 //commented for CRM-3256
958 $this->_useGroupBy
= TRUE;
961 $name = str_replace(' ', '_', $name);
963 $tName = "$name-location_type";
964 $ltName = "`$name-location_type`";
965 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
966 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
967 $this->_element
["{$tName}_id"] = 1;
968 $this->_element
["{$tName}"] = 1;
970 $locationTypeName = $tName;
971 $locationTypeJoin = array();
975 foreach ($elements as $elementFullName => $dontCare) {
977 $elementName = $elementCmpName = $elementFullName;
979 if (substr($elementCmpName, 0, 5) == 'phone') {
980 $elementCmpName = 'phone';
983 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
984 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
985 $addressCustomFieldIds[$cfID][$name] = 1;
988 //add address table only once
989 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
991 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
993 $tName = "$name-address";
994 $aName = "`$name-address`";
995 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
996 $this->_element
["{$tName}_id"] = 1;
997 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
998 $this->_tables
[$tName] = $addressJoin;
999 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1000 $processed[$aName] = 1;
1004 $cond = $elementType = '';
1005 if (strpos($elementName, '-') !== FALSE) {
1006 // this is either phone, email or IM
1007 list($elementName, $elementType) = explode('-', $elementName);
1009 if (($elementName != 'phone') && ($elementName != 'im')) {
1010 $cond = self
::getPrimaryCondition($elementType);
1012 // CRM-13011 : If location type is primary, do not restrict search to the phone
1013 // type id - we want the primary phone, regardless of what type it is.
1014 // Otherwise, restrict to the specified phone type for the given field.
1015 if ((!$cond) && ($elementName == 'phone')) {
1016 $cond = "phone_type_id = '$elementType'";
1018 elseif ((!$cond) && ($elementName == 'im')) {
1019 // IM service provider id, CRM-3140
1020 $cond = "provider_id = '$elementType'";
1022 $elementType = '-' . $elementType;
1025 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
1027 // hack for profile, add location id
1030 // fix for CRM-882( to handle phone types )
1031 !is_numeric($elementType)
1033 if (is_numeric($name)) {
1034 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1037 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1040 elseif (is_numeric($name)) {
1041 //this for phone type to work
1042 if (in_array($elementName, array('phone', 'phone_ext'))) {
1043 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1046 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1050 //this is for phone type to work for profile edit
1051 if (in_array($elementName, array('phone', 'phone_ext'))) {
1052 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1055 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1060 // Check if there is a value, if so also add to where Clause
1062 if ($this->_params
) {
1064 if (isset($locationTypeId)) {
1065 $nm .= "-$locationTypeId";
1067 if (!is_numeric($elementType)) {
1068 $nm .= "$elementType";
1071 foreach ($this->_params
as $id => $values) {
1072 if ((is_array($values) && $values[0] == $nm) ||
1073 (in_array($elementName, array('phone', 'im'))
1074 && (strpos($values[0], $nm) !== FALSE)
1084 if ($field && isset($field['where'])) {
1085 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1086 $pf = substr($tableName, 8);
1087 $tName = $name . '-' . $pf . $elementType;
1088 if (isset($tableName)) {
1089 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1090 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1093 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1096 $this->_element
["{$tName}_id"] = 1;
1097 if (substr($tName, -15) == '-state_province') {
1098 // FIXME: hack to fix CRM-1900
1099 $a = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1103 if (substr_count($a, 'state_province_name') > 0) {
1104 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1105 'pseudoField' => "{$pf}_id",
1106 'idCol' => "{$tName}_id",
1107 'bao' => 'CRM_Core_BAO_Address',
1109 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1112 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1113 'pseudoField' => 'state_province_abbreviation',
1114 'idCol' => "{$tName}_id",
1116 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1120 if (substr($elementFullName, 0, 2) == 'im') {
1121 $provider = "{$name}-{$elementFullName}-provider_id";
1122 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1123 $this->_element
[$provider] = 1;
1125 if ($pf == 'country' ||
$pf == 'county') {
1126 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1127 'pseudoField' => "{$pf}_id",
1128 'idCol' => "{$tName}_id",
1129 'bao' => 'CRM_Core_BAO_Address',
1131 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1134 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1138 if (in_array($pf, array('state_province', 'country', 'county'))) {
1139 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1142 $this->_element
["{$name}-{$elementFullName}"] = 1;
1145 if (empty($processed["`$tName`"])) {
1146 $processed["`$tName`"] = 1;
1147 $newName = $tableName . '_' . $index;
1148 switch ($tableName) {
1149 case 'civicrm_phone':
1150 case 'civicrm_email':
1152 case 'civicrm_openid':
1154 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1155 if ($tableName != 'civicrm_phone') {
1156 $this->_tables
[$tName] .= " AND `$tName`.$lCond";
1158 elseif (is_numeric($name)) {
1159 $this->_select
[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1162 // this special case to add phone type
1164 $phoneTypeCondition = " AND `$tName`.$cond ";
1165 //gross hack to pickup corrupted data also, CRM-7603
1166 if (strpos($cond, 'phone_type_id') !== FALSE) {
1167 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1168 if (!empty($lCond)) {
1169 $phoneTypeCondition .= " AND ( `$tName`.$lCond ) ";
1172 $this->_tables
[$tName] .= $phoneTypeCondition;
1175 //build locationType join
1176 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1179 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1183 case 'civicrm_state_province':
1184 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1185 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1186 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1188 $this->_whereTables
["{$name}-address"] = $addressJoin;
1192 case 'civicrm_country':
1193 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1194 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1195 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1197 $this->_whereTables
["{$name}-address"] = $addressJoin;
1201 case 'civicrm_county':
1202 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1203 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1204 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1206 $this->_whereTables
["{$name}-address"] = $addressJoin;
1212 $this->_whereTables
["{$name}-address"] = $addressJoin;
1221 // add location type join
1222 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1223 $this->_tables
[$locationTypeName] = $ltypeJoin;
1225 // table should be present in $this->_whereTables,
1226 // to add its condition in location type join, CRM-3939.
1227 if ($addWhereCount) {
1228 $locClause = array();
1229 foreach ($this->_whereTables
as $tableName => $clause) {
1230 if (!empty($locationTypeJoin[$tableName])) {
1231 $locClause[] = $locationTypeJoin[$tableName];
1235 if (!empty($locClause)) {
1236 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1241 if (!empty($addressCustomFieldIds)) {
1242 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1243 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1244 foreach ($locTypeName as $name => $dnc) {
1245 $this->_locationSpecificCustomFields
[$cfID] = array($name, array_search($name, $locationTypes));
1246 $fieldName = "$name-custom_{$cfID}";
1247 $tName = "$name-address-custom-{$cfID}";
1248 $aName = "`$name-address-custom-{$cfID}`";
1249 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1250 $this->_element
["{$tName}_id"] = 1;
1251 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1252 $this->_element
[$fieldName] = 1;
1253 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1260 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
1265 public function addMultipleElements() {
1266 if (empty($this->_returnProperties
['website'])) {
1269 if (!is_array($this->_returnProperties
['website'])) {
1273 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1274 foreach ($elements as $elementFullName => $dontCare) {
1275 $tName = "website-{$key}-{$elementFullName}";
1276 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1277 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1278 $this->_element
["{$tName}_id"] = 1;
1279 $this->_element
["{$tName}"] = 1;
1281 $type = "website-{$key}-website_type_id";
1282 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1283 $this->_element
[$type] = 1;
1284 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1290 * Generate the query based on what type of query we need.
1292 * @param bool $count
1293 * @param bool $sortByChar
1294 * @param bool $groupContacts
1295 * @param bool $onlyDeleted
1298 * sql query parts as an array
1300 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1301 // build permission clause
1302 $this->generatePermissionClause($onlyDeleted, $count);
1305 if (isset($this->_rowCountClause
)) {
1306 $select = "SELECT {$this->_rowCountClause}";
1308 elseif (isset($this->_distinctComponentClause
)) {
1309 // we add distinct to get the right count for components
1310 // for the more complex result set, we use GROUP BY the same id
1312 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1315 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1317 $from = $this->_simpleFromClause
;
1318 if ($this->_useDistinct
) {
1319 $this->_useGroupBy
= TRUE;
1322 elseif ($sortByChar) {
1323 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1324 $from = $this->_simpleFromClause
;
1326 elseif ($groupContacts) {
1327 $select = 'SELECT contact_a.id as id';
1328 if ($this->_useDistinct
) {
1329 $this->_useGroupBy
= TRUE;
1331 $from = $this->_simpleFromClause
;
1334 if (!empty($this->_paramLookup
['group'])) {
1335 // make sure there is only one element
1336 // this is used when we are running under smog and need to know
1337 // how the contact was added (CRM-1203)
1338 if ((count($this->_paramLookup
['group']) == 1) &&
1339 (count($this->_paramLookup
['group'][0][2]) == 1)
1341 $groups = array_keys($this->_paramLookup
['group'][0][2]);
1342 $groupId = $groups[0];
1344 //check if group is saved search
1345 $group = new CRM_Contact_BAO_Group();
1346 $group->id
= $groupId;
1349 if (!isset($group->saved_search_id
)) {
1350 $tbName = "`civicrm_group_contact-{$groupId}`";
1351 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1352 $this->_element
['group_contact_id'] = 1;
1353 $this->_select
['status'] = "$tbName.status as status";
1354 $this->_element
['status'] = 1;
1357 $this->_useGroupBy
= TRUE;
1359 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1360 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1362 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1363 $this->_useDistinct
= FALSE;
1364 $this->_useGroupBy
= TRUE;
1368 $select = "SELECT ";
1369 if (isset($this->_distinctComponentClause
)) {
1370 $select .= "{$this->_distinctComponentClause}, ";
1372 $select .= implode(', ', $this->_select
);
1373 $from = $this->_fromClause
;
1377 if (!empty($this->_whereClause
)) {
1378 $where = "WHERE {$this->_whereClause}";
1381 if (!empty($this->_permissionWhereClause
) && empty($this->_displayRelationshipType
)) {
1382 if (empty($where)) {
1383 $where = "WHERE $this->_permissionWhereClause";
1386 $where = "$where AND $this->_permissionWhereClause";
1391 if (!empty($this->_having
)) {
1392 foreach ($this->_having
as $havingSets) {
1393 foreach ($havingSets as $havingSet) {
1394 $havingValue[] = $havingSet;
1397 $having = ' HAVING ' . implode(' AND ', $havingValue);
1400 // if we are doing a transform, do it here
1401 // use the $from, $where and $having to get the contact ID
1402 if ($this->_displayRelationshipType
) {
1403 $this->filterRelatedContacts($from, $where, $having);
1406 return array($select, $from, $where, $having);
1410 * @param string $name
1415 public function &getWhereValues($name, $grouping) {
1417 foreach ($this->_params
as $values) {
1418 if ($values[0] == $name && $values[3] == $grouping) {
1431 public static function fixDateValues($relative, &$from, &$to) {
1433 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1438 * @param $formValues
1439 * @param int $wildcard
1440 * @param bool $useEquals
1442 * @param string $apiEntity
1446 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1448 if (empty($formValues)) {
1452 foreach ($formValues as $id => $values) {
1453 if ($id == 'privacy') {
1454 if (is_array($formValues['privacy'])) {
1455 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1456 foreach ($formValues['privacy'] as $key => $value) {
1458 $params[] = array($key, $op, $value, 0, 0);
1463 elseif ($id == 'email_on_hold') {
1464 if ($formValues['email_on_hold']['on_hold']) {
1465 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1468 elseif (preg_match('/_date_relative$/', $id) ||
1469 $id == 'event_relative' ||
1470 $id == 'case_from_relative' ||
1471 $id == 'case_to_relative'
1473 if ($id == 'event_relative') {
1474 $fromRange = 'event_start_date_low';
1475 $toRange = 'event_end_date_high';
1477 elseif ($id == 'case_from_relative') {
1478 $fromRange = 'case_from_start_date_low';
1479 $toRange = 'case_from_start_date_high';
1481 elseif ($id == 'case_to_relative') {
1482 $fromRange = 'case_to_end_date_low';
1483 $toRange = 'case_to_end_date_high';
1486 $dateComponent = explode('_date_relative', $id);
1487 $fromRange = "{$dateComponent[0]}_date_low";
1488 $toRange = "{$dateComponent[0]}_date_high";
1491 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1492 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1497 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
1502 $params[] = $values;
1511 * @param int $wildcard
1512 * @param bool $useEquals
1514 * @param string $apiEntity
1516 * @return array|null
1518 public static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1519 // skip a few search variables
1520 static $skipWhere = NULL;
1521 static $likeNames = NULL;
1523 // Change camelCase EntityName to lowercase with underscores
1524 $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity);
1526 if (CRM_Utils_System
::isNull($values)) {
1538 'display_relationship_type',
1542 if (in_array($id, $skipWhere) ||
1543 substr($id, 0, 4) == '_qf_' ||
1544 substr($id, 0, 7) == 'hidden_'
1550 (substr($id, 0, strlen($apiEntity)) != $apiEntity) &&
1551 (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_')
1553 $id = $apiEntity . '_' . $id;
1557 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1560 // email comes in via advanced search
1561 // so use wildcard always
1562 if ($id == 'email') {
1566 if (!$useEquals && in_array($id, $likeNames)) {
1567 $result = array($id, 'LIKE', $values, 0, 1);
1569 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1570 $result = array($id, 'LIKE', $values, 0, 0);
1572 elseif ($id == 'group') {
1573 if (is_array($values)) {
1574 foreach ($values as $groupIds => $val) {
1576 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1577 if (strlen($matches[1]) > 0) {
1578 $values[$matches[1]] = 1;
1579 unset($values[$groupIds]);
1585 $groupIds = explode(',', $values);
1587 foreach ($groupIds as $groupId) {
1588 $values[$groupId] = 1;
1592 $result = array($id, 'IN', $values, 0, 0);
1594 elseif ($id == 'contact_tags' ||
$id == 'tag') {
1595 if (!is_array($values)) {
1596 $tagIds = explode(',', $values);
1598 foreach ($tagIds as $tagId) {
1599 $values[$tagId] = 1;
1602 $result = array($id, 'IN', $values, 0, 0);
1604 elseif ($id == 'contact_type') {
1605 $result = array($id, 'IN', $values, 0, $wildcard);
1608 $result = array($id, '=', $values, 0, $wildcard);
1617 public function whereClauseSingle(&$values) {
1618 // do not process custom fields or prefixed contact ids or component params
1619 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1620 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1621 (substr($values[0], 0, 13) == 'contribution_') ||
1622 (substr($values[0], 0, 6) == 'event_') ||
1623 (substr($values[0], 0, 12) == 'participant_') ||
1624 (substr($values[0], 0, 7) == 'member_') ||
1625 (substr($values[0], 0, 6) == 'grant_') ||
1626 (substr($values[0], 0, 7) == 'pledge_') ||
1627 (substr($values[0], 0, 5) == 'case_') ||
1628 (substr($values[0], 0, 10) == 'financial_') ||
1629 (substr($values[0], 0, 8) == 'payment_') ||
1630 (substr($values[0], 0, 11) == 'membership_')
1635 // skip for hook injected fields / params
1636 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1637 if (array_key_exists($values[0], $extFields)) {
1641 switch ($values[0]) {
1642 case 'deleted_contacts':
1643 $this->deletedContacts($values);
1646 case 'contact_type':
1647 $this->contactType($values);
1650 case 'contact_sub_type':
1651 $this->contactSubType($values);
1655 $this->group($values);
1659 // so we resolve this into a list of groups & proceed as if they had been
1661 list($name, $op, $value, $grouping, $wildcard) = $values;
1662 $values[0] = 'group';
1664 $this->_paramLookup
['group'][0][0] = 'group';
1665 $this->_paramLookup
['group'][0][1] = 'IN';
1666 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1667 $this->group($values);
1670 // case tag comes from find contacts
1672 $this->tagSearch($values);
1676 case 'contact_tags':
1677 $this->tag($values);
1682 case 'note_subject':
1683 $this->notes($values);
1687 $this->ufUser($values);
1691 case 'display_name':
1692 $this->sortName($values);
1696 case 'postal_greeting':
1697 case 'email_greeting':
1698 $this->greetings($values);
1702 $this->email($values);
1705 case 'phone_numeric':
1706 $this->phone_numeric($values);
1709 case 'phone_phone_type_id':
1710 case 'phone_location_type_id':
1711 $this->phone_option_group($values);
1714 case 'street_address':
1715 $this->street_address($values);
1718 case 'street_number':
1719 $this->street_number($values);
1722 case 'sortByCharacter':
1723 $this->sortByCharacter($values);
1726 case 'location_type':
1727 $this->locationType($values);
1731 $this->county($values);
1734 case 'state_province':
1735 $this->stateProvince($values);
1739 $this->country($values, FALSE);
1743 case 'postal_code_low':
1744 case 'postal_code_high':
1745 $this->postalCode($values);
1748 case 'activity_date':
1749 case 'activity_date_low':
1750 case 'activity_date_high':
1751 case 'activity_role':
1752 case 'activity_status_id':
1753 case 'activity_status':
1754 case 'followup_parent_id':
1756 case 'source_contact_id':
1757 case 'activity_subject':
1758 case 'test_activities':
1759 case 'activity_type_id':
1760 case 'activity_type':
1761 case 'activity_survey_id':
1762 case 'activity_tags':
1763 case 'activity_taglist':
1764 case 'activity_test':
1765 case 'activity_campaign_id':
1766 case 'activity_engagement_level':
1768 case 'activity_result':
1769 case 'source_contact':
1770 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1773 case 'birth_date_low':
1774 case 'birth_date_high':
1775 case 'deceased_date_low':
1776 case 'deceased_date_high':
1777 $this->demographics($values);
1780 case 'log_date_low':
1781 case 'log_date_high':
1782 $this->modifiedDates($values);
1786 $this->changeLog($values);
1789 case 'do_not_phone':
1790 case 'do_not_email':
1793 case 'do_not_trade':
1795 $this->privacy($values);
1798 case 'privacy_options':
1799 $this->privacyOptions($values);
1802 case 'privacy_operator':
1803 case 'privacy_toggle':
1804 // these are handled by privacy options
1807 case 'preferred_communication_method':
1808 $this->preferredCommunication($values);
1811 case 'relation_type_id':
1812 case 'relation_start_date_high':
1813 case 'relation_start_date_low':
1814 case 'relation_end_date_high':
1815 case 'relation_end_date_low':
1816 case 'relation_target_name':
1817 case 'relation_status':
1818 case 'relation_date_low':
1819 case 'relation_date_high':
1820 $this->relationship($values);
1821 $this->_relationshipValuesAdded
= TRUE;
1824 case 'task_status_id':
1825 $this->task($values);
1829 // since this case is handled with the above
1832 case 'prox_distance':
1833 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1836 case 'prox_street_address':
1838 case 'prox_postal_code':
1839 case 'prox_state_province_id':
1840 case 'prox_country_id':
1841 // handled by the proximity_distance clause
1845 $this->restWhere($values);
1851 * Given a list of conditions in params generate the required.
1856 public function whereClause() {
1857 $this->_where
[0] = array();
1858 $this->_qill
[0] = array();
1860 $this->includeContactIds();
1861 if (!empty($this->_params
)) {
1862 foreach (array_keys($this->_params
) as $id) {
1863 if (empty($this->_params
[$id][0])) {
1866 // check for both id and contact_id
1867 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
1869 $this->_params
[$id][1] == 'IS NULL' ||
1870 $this->_params
[$id][1] == 'IS NOT NULL'
1872 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]}";
1874 elseif (is_array($this->_params
[$id][2])) {
1875 $idList = implode("','", $this->_params
[$id][2]);
1876 //why on earth do they put ' in the middle & not on the outside? We have to assume it's
1877 //to support 'something' so lets add them conditionally to support the api (which is a tested flow
1878 // so if you are looking to alter this check api test results
1879 if (strpos(trim($idList), "'") > 0) {
1880 $idList = "'" . $idList . "'";
1883 $this->_where
[0][] = "contact_a.id IN ({$idList})";
1886 $this->_where
[0][] = self
::buildClause("contact_a.id", "{$this->_params[$id][1]}", "{$this->_params[$id][2]}");
1890 $this->whereClauseSingle($this->_params
[$id]);
1894 CRM_Core_Component
::alterQuery($this, 'where');
1896 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
1899 if ($this->_customQuery
) {
1900 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1901 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1902 if (!empty($this->_customQuery
->_where
)) {
1903 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
1906 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
1910 $andClauses = array();
1913 if (!empty($this->_where
)) {
1914 foreach ($this->_where
as $grouping => $values) {
1915 if ($grouping > 0 && !empty($values)) {
1916 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1921 if (!empty($this->_where
[0])) {
1922 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
1924 if (!empty($clauses)) {
1925 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1928 if ($validClauses > 1) {
1929 $this->_useDistinct
= TRUE;
1933 return implode(' AND ', $andClauses);
1941 public function restWhere(&$values) {
1942 $name = CRM_Utils_Array
::value(0, $values);
1943 $op = CRM_Utils_Array
::value(1, $values);
1944 $value = CRM_Utils_Array
::value(2, $values);
1945 $grouping = CRM_Utils_Array
::value(3, $values);
1946 $wildcard = CRM_Utils_Array
::value(4, $values);
1948 if (isset($grouping) && empty($this->_where
[$grouping])) {
1949 $this->_where
[$grouping] = array();
1952 $multipleFields = array('url');
1954 //check if the location type exits for fields
1956 $locType = explode('-', $name);
1958 if (!in_array($locType[0], $multipleFields)) {
1959 //add phone type if exists
1960 if (isset($locType[2]) && $locType[2]) {
1961 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
1965 $field = CRM_Utils_Array
::value($name, $this->_fields
);
1968 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
1977 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
1978 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1980 if (substr($name, 0, 14) === 'state_province') {
1981 if (isset($locType[1]) && is_numeric($locType[1])) {
1983 $aName = "{$locationType[$locType[1]]}-address";
1984 $where = "`$aName`.state_province_id";
1987 $where = "civicrm_address.state_province_id";
1990 $states = CRM_Core_PseudoConstant
::stateProvince();
1991 if (is_numeric($value)) {
1992 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1993 $value = $states[(int ) $value];
1996 $intVal = CRM_Utils_Array
::key($value, $states);
1997 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
2000 $this->_qill
[$grouping][] = ts('State') . " $op '$value'";
2003 $this->_qill
[$grouping][] = ts('State') . " ($lType) $op '$value'";
2006 elseif (!empty($field['pseudoconstant'])) {
2007 $this->optionValueQuery(
2008 $name, $op, $value, $grouping,
2009 CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', $field['name']),
2015 if ($name == 'gender_id') {
2016 self
::$_openedPanes[ts('Demographics')] = TRUE;
2019 elseif (substr($name, 0, 7) === 'country') {
2020 if (isset($locType[1]) && is_numeric($locType[1])) {
2022 $aName = "{$locationType[$locType[1]]}-address";
2023 $where = "`$aName`.country_id";
2026 $where = "civicrm_address.country_id";
2029 $countries = CRM_Core_PseudoConstant
::country();
2030 if (is_numeric($value)) {
2031 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2032 $value = $countries[(int ) $value];
2035 $intVal = CRM_Utils_Array
::key($value, $countries);
2036 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
2040 $this->_qill
[$grouping][] = ts('Country') . " $op '$value'";
2043 $this->_qill
[$grouping][] = ts('Country') . " ($lType) $op '$value'";
2046 elseif (substr($name, 0, 6) === 'county') {
2047 if (isset($locType[1]) && is_numeric($locType[1])) {
2049 $aName = "{$locationType[$locType[1]]}-address";
2050 $where = "`$aName`.county_id";
2053 $where = "civicrm_address.county_id";
2056 $counties = CRM_Core_PseudoConstant
::county();
2057 if (is_numeric($value)) {
2058 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2059 $value = $counties[(int ) $value];
2062 $intVal = CRM_Utils_Array
::key($value, $counties);
2063 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
2067 $this->_qill
[$grouping][] = ts('County') . " $op '$value'";
2070 $this->_qill
[$grouping][] = ts('County') . " ($lType) $op '$value'";
2073 elseif ($name === 'world_region') {
2074 $field['where'] = 'civicrm_worldregion.id';
2075 $this->optionValueQuery(
2076 $name, $op, $value, $grouping,
2077 CRM_Core_PseudoConstant
::worldRegion(),
2084 elseif ($name === 'is_deceased') {
2085 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
2086 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2087 self
::$_openedPanes[ts('Demographics')] = TRUE;
2089 elseif ($name === 'created_date' ||
$name === 'modified_date' ||
$name === 'deceased_date' ||
$name === 'birth_date') {
2090 $appendDateTime = TRUE;
2091 if ($name === 'deceased_date' ||
$name === 'birth_date') {
2092 $appendDateTime = FALSE;
2093 self
::$_openedPanes[ts('Demographics')] = TRUE;
2095 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2097 elseif ($name === 'contact_id') {
2098 if (is_int($value)) {
2099 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2100 $this->_qill
[$grouping][] = "$field[title] $op $value";
2103 elseif ($name === 'name') {
2104 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2106 $value = "%$value%";
2109 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2110 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2111 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2113 elseif ($name === 'current_employer') {
2114 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2116 $value = "%$value%";
2119 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
2120 $ceWhereClause = self
::buildClause($wc, $op,
2123 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2124 $this->_where
[$grouping][] = $ceWhereClause;
2125 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2127 elseif ($name === 'email_greeting') {
2128 $filterCondition = array('greeting_type' => 'email_greeting');
2129 $this->optionValueQuery(
2130 $name, $op, $value, $grouping,
2131 CRM_Core_PseudoConstant
::greeting($filterCondition),
2133 ts('Email Greeting')
2136 elseif ($name === 'postal_greeting') {
2137 $filterCondition = array('greeting_type' => 'postal_greeting');
2138 $this->optionValueQuery(
2139 $name, $op, $value, $grouping,
2140 CRM_Core_PseudoConstant
::greeting($filterCondition),
2142 ts('Postal Greeting')
2145 elseif ($name === 'addressee') {
2146 $filterCondition = array('greeting_type' => 'addressee');
2147 $this->optionValueQuery(
2148 $name, $op, $value, $grouping,
2149 CRM_Core_PseudoConstant
::greeting($filterCondition),
2154 elseif (substr($name, 0, 4) === 'url-') {
2155 $tName = 'civicrm_website';
2156 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2157 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2159 $value = "%$value%";
2163 $wc = 'civicrm_website.url';
2164 $this->_where
[$grouping][] = $d = self
::buildClause($wc, $op, $value);
2165 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2167 elseif ($name === 'contact_is_deleted') {
2168 $this->_where
[$grouping][] = self
::buildClause("contact_a.is_deleted", $op, $value);
2169 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2171 elseif (!empty($field['where'])) {
2173 if (!empty($field['type'])) {
2174 $type = CRM_Utils_Type
::typeToString($field['type']);
2177 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2179 if (isset($locType[1]) &&
2180 is_numeric($locType[1])
2184 //get the location name
2185 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2187 $fieldName = "LOWER(`$tName`.$fldName)";
2189 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2190 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2194 if ($tableName == 'civicrm_contact') {
2195 $fieldName = "LOWER(contact_a.{$fieldName})";
2198 if ($op != 'IN' && !is_numeric($value)) {
2199 $fieldName = "LOWER({$field['where']})";
2202 $fieldName = "{$field['where']}";
2207 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2208 $this->_qill
[$grouping][] = "$field[title] $qillop '$qillVal'";
2210 if (is_array($value)) {
2211 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2212 // for api style operators for functions that hit this point without worrying about regression
2213 // (the previous comments indicated the condition for hitting this point were unknown
2214 // per CRM-14743 we are adding modified_date & created_date operator support
2215 $operations = array_keys($value);
2216 foreach ($operations as $operator) {
2217 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2218 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2219 //so this condition will satisfy the search for now
2220 if (strpos($op, 'IN') !== FALSE) {
2221 $value = array($op => $value);
2223 // we don't know when this might happen
2225 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $operator)));
2229 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($fieldName, $value, $type);
2233 $value = $strtolower($value);
2236 $value = "%$value%";
2240 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2244 if ($setTables && isset($field['where'])) {
2245 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2246 if (isset($tableName)) {
2247 $this->_tables
[$tableName] = 1;
2248 $this->_whereTables
[$tableName] = 1;
2261 public static function getLocationTableName(&$where, &$locType) {
2262 if (isset($locType[1]) && is_numeric($locType[1])) {
2263 list($tbName, $fldName) = explode(".", $where);
2265 //get the location name
2266 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2267 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2268 if (in_array($locType[0], $specialFields)) {
2269 //hack to fix / special handing for phone_ext
2270 if ($locType[0] == 'phone_ext') {
2271 $locType[0] = 'phone';
2273 if (isset($locType[2]) && $locType[2]) {
2274 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2277 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2280 elseif (in_array($locType[0],
2284 'supplemental_address_1',
2285 'supplemental_address_2',
2288 'postal_code_suffix',
2293 //fix for search by profile with address fields.
2294 $tName = "{$locationType[$locType[1]]}-address";
2296 elseif ($locType[0] == 'on_hold') {
2297 $tName = "{$locationType[$locType[1]]}-email";
2300 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2302 $tName = str_replace(' ', '_', $tName);
2303 return array($tName, $fldName);
2305 CRM_Core_Error
::fatal();
2309 * Given a result dao, extract the values and return that array
2311 * @param CRM_Core_DAO $dao
2314 * values for this query
2316 public function store($dao) {
2319 foreach ($this->_element
as $key => $dontCare) {
2320 if (property_exists($dao, $key)) {
2321 if (strpos($key, '-') !== FALSE) {
2322 $values = explode('-', $key);
2323 $lastElement = array_pop($values);
2325 $cnt = count($values);
2327 foreach ($values as $v) {
2328 if (!array_key_exists($v, $current)) {
2329 $current[$v] = array();
2331 //bad hack for im_provider
2332 if ($lastElement == 'provider_id') {
2333 if ($count < $cnt) {
2334 $current = &$current[$v];
2337 $lastElement = "{$v}_{$lastElement}";
2341 $current = &$current[$v];
2346 $current[$lastElement] = $dao->$key;
2349 $value[$key] = $dao->$key;
2357 * Getter for tables array.
2361 public function tables() {
2362 return $this->_tables
;
2366 * Where tables is sometimes used to create the from clause, but, not reliably, set this AND set tables
2367 * It's unclear the intent - there is a 'simpleFrom' clause which takes whereTables into account & a fromClause which doesn't
2368 * logic may have eroded
2371 public function whereTables() {
2372 return $this->_whereTables
;
2376 * Generate the where clause (used in match contacts and permissions)
2378 * @param array $params
2379 * @param array $fields
2380 * @param array $tables
2381 * @param $whereTables
2382 * @param bool $strict
2386 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2387 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2391 $tables = array_merge($query->tables(), $tables);
2392 $whereTables = array_merge($query->whereTables(), $whereTables);
2394 return $query->_whereClause
;
2398 * Create the from clause.
2400 * @param array $tables
2401 * Tables that need to be included in this from clause.
2402 * if null, return mimimal from clause (i.e. civicrm_contact)
2403 * @param array $inner
2404 * Tables that should be inner-joined.
2405 * @param array $right
2406 * Tables that should be right-joined.
2408 * @param bool $primaryLocation
2414 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2416 $from = ' FROM civicrm_contact contact_a';
2417 if (empty($tables)) {
2421 if (!empty($tables['civicrm_worldregion'])) {
2422 $tables = array_merge(array('civicrm_country' => 1), $tables);
2425 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2426 CRM_Utils_Array
::value('civicrm_county', $tables)
2427 ) && empty($tables['civicrm_address'])
2429 $tables = array_merge(array('civicrm_address' => 1),
2434 // add group_contact table if group table is present
2435 if (!empty($tables['civicrm_group']) && empty($tables['civicrm_group_contact'])) {
2436 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
2439 // add group_contact and group table is subscription history is present
2440 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2441 $tables = array_merge(array(
2442 'civicrm_group' => 1,
2443 'civicrm_group_contact' => 1,
2449 // to handle table dependencies of components
2450 CRM_Core_Component
::tableNames($tables);
2451 // to handle table dependencies of hook injected tables
2452 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2454 //format the table list according to the weight
2455 $info = CRM_Core_TableHierarchy
::info();
2457 foreach ($tables as $key => $value) {
2459 if (strpos($key, '-') !== FALSE) {
2460 $keyArray = explode('-', $key);
2461 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2463 elseif (strpos($key, '_') !== FALSE) {
2464 $keyArray = explode('_', $key);
2465 if (is_numeric(array_pop($keyArray))) {
2466 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2469 $k = CRM_Utils_Array
::value($key, $info, 99);
2473 $k = CRM_Utils_Array
::value($key, $info, 99);
2475 $tempTable[$k . ".$key"] = $key;
2478 $newTables = array();
2479 foreach ($tempTable as $key) {
2480 $newTables[$key] = $tables[$key];
2483 $tables = $newTables;
2485 foreach ($tables as $name => $value) {
2490 if (!empty($inner[$name])) {
2493 elseif (!empty($right[$name])) {
2501 // if there is already a join statement in value, use value itself
2502 if (strpos($value, 'JOIN')) {
2503 $from .= " $value ";
2506 $from .= " $side JOIN $name ON ( $value ) ";
2511 case 'civicrm_address':
2512 if ($primaryLocation) {
2513 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2516 //CRM-14263 further handling of address joins further down...
2517 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2521 case 'civicrm_phone':
2522 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2525 case 'civicrm_email':
2526 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2530 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2534 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2535 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2536 $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)";
2539 case 'civicrm_openid':
2540 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2543 case 'civicrm_worldregion':
2544 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2545 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2548 case 'civicrm_location_type':
2549 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2552 case 'civicrm_group':
2553 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2556 case 'civicrm_group_contact':
2557 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2560 case 'civicrm_activity':
2561 case 'civicrm_activity_tag':
2562 case 'activity_type':
2563 case 'activity_status':
2565 case 'civicrm_activity_contact':
2566 case 'source_contact':
2567 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2570 case 'civicrm_entity_tag':
2571 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2572 civicrm_entity_tag.entity_id = contact_a.id ) ";
2575 case 'civicrm_note':
2576 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2577 contact_a.id = civicrm_note.entity_id ) ";
2580 case 'civicrm_subscription_history':
2581 $from .= " $side JOIN civicrm_subscription_history
2582 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2583 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2586 case 'civicrm_relationship':
2587 if (self
::$_relType == 'reciprocal') {
2588 if (self
::$_relationshipTempTable) {
2589 // we have a temptable to join on
2590 $tbl = self
::$_relationshipTempTable;
2591 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2594 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2595 $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)";
2598 elseif (self
::$_relType == 'b') {
2599 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2600 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2603 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2604 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2609 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2610 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2614 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2617 case 'civicrm_grant':
2618 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2621 case 'civicrm_website':
2622 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2626 $locationTypeName = '';
2627 if (strpos($name, '-address') != 0) {
2628 $locationTypeName = 'address';
2630 elseif (strpos($name, '-phone') != 0) {
2631 $locationTypeName = 'phone';
2633 elseif (strpos($name, '-email') != 0) {
2634 $locationTypeName = 'email';
2636 if ($locationTypeName) {
2637 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2638 $parts = explode('-', $name);
2639 $locationID = array_search($parts[0], CRM_Core_BAO_Address
::buildOptions('location_type_id', 'get', array('name' => $parts[0])));
2640 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2643 $from .= CRM_Core_Component
::from($name, $mode, $side);
2645 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2654 * WHERE / QILL clause for deleted_contacts
2660 public function deletedContacts($values) {
2661 list($_, $_, $value, $grouping, $_) = $values;
2663 // *prepend* to the relevant grouping as this is quite an important factor
2664 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2669 * Where / qill clause for contact_type
2675 public function contactType(&$values) {
2676 list($name, $op, $value, $grouping, $wildcard) = $values;
2678 $subTypes = array();
2681 // account for search builder mapping multiple values
2682 if (!is_array($value)) {
2683 $values = self
::parseSearchBuilderString($value, 'String');
2684 if (is_array($values)) {
2685 $value = array_flip($values);
2689 if (is_array($value)) {
2690 foreach ($value as $k => $v) {
2695 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2696 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2699 if (!empty($subType)) {
2700 $subTypes[$subType] = 1;
2702 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2707 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2708 $contactType = $contactTypeANDSubType[0];
2709 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2710 if (!empty($subType)) {
2711 $subTypes[$subType] = 1;
2713 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2717 if (!empty($clause)) {
2719 if ($op == 'IN' ||
$op == 'NOT IN') {
2720 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2723 $type = array_pop($clause);
2724 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2727 $this->_qill
[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2729 if (!empty($subTypes)) {
2730 $this->includeContactSubTypes($subTypes, $grouping);
2736 * Where / qill clause for contact_sub_type
2742 public function contactSubType(&$values) {
2743 list($name, $op, $value, $grouping, $wildcard) = $values;
2744 $this->includeContactSubTypes($value, $grouping, $op);
2752 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2755 $alias = "contact_a.contact_sub_type";
2756 $qillOperators = array('NOT LIKE' => ts('Not Like')) + CRM_Core_SelectValues
::getSearchBuilderOperators();
2758 $op = str_replace('IN', 'LIKE', $op);
2759 $op = str_replace('=', 'LIKE', $op);
2760 $op = str_replace('!', 'NOT ', $op);
2762 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2763 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
2765 elseif (is_array($value)) {
2766 foreach ($value as $k => $v) {
2768 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($k, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2773 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2776 if (!empty($clause)) {
2777 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2779 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', array(1 => $qillOperators[$op])) . implode(' ' . ts('or') . ' ', array_keys($clause));
2783 * Where / qill clause for groups
2789 public function group(&$values) {
2790 list($name, $op, $value, $grouping, $wildcard) = $values;
2792 if (count($value) > 1) {
2793 $this->_useDistinct
= TRUE;
2796 // Replace pseudo operators from search builder
2797 $op = str_replace('EMPTY', 'NULL', $op);
2799 $groupNames = CRM_Core_PseudoConstant
::group();
2804 $groupIds = implode(',', array_keys($value));
2805 foreach ($value as $id => $dontCare) {
2806 if (array_key_exists($id, $groupNames) && $dontCare) {
2807 $names[] = $groupNames[$id];
2814 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2816 is_array($gcsValues[2])
2818 foreach ($gcsValues[2] as $k => $v) {
2820 if ($k == 'Added') {
2823 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2828 $statii[] = '"Added"';
2833 if (count($value) == 1 &&
2834 count($statii) == 1 &&
2835 $statii[0] == '"Added"'
2837 // check if smart group, if so we can get rid of that one additional
2839 $groupIDs = array_keys($value);
2841 if (!empty($groupIDs[0]) &&
2842 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
2852 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2853 $joinClause = array("contact_a.id = {$gcTable}.contact_id");
2854 if ($groupIds && ($op == 'IN' ||
$op == 'NOT IN')) {
2855 $joinClause[] = "{$gcTable}.group_id IN ( $groupIds )";
2857 // For NOT IN we join on groups the contact IS in, then exclude them in the where clause
2858 if ($statii && $op == 'NOT IN') {
2859 $joinClause[] = "{$gcTable}.status IN (" . implode(', ', $statii) . ")";
2861 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
2865 $qill = ts('In group');
2868 $qill = ts('Groups %1', array(1 => $op));
2870 $qill .= ' ' . implode(' ' . ts('or') . ' ', $names);
2872 $groupClause = NULL;
2875 $groupClause = "{$gcTable}.group_id $op" . ($groupIds ?
" ( $groupIds ) " : '');
2876 if (!empty($statii) && $groupIds) {
2877 $groupClause .= " AND {$gcTable}.status IN (" . implode(', ', $statii) . ")";
2878 $qill .= " " . ($op == 'NOT IN' ?
ts('WHERE') : ts('AND')) . " " . ts('Group Status') . ' - ' . implode(' ' . ts('or') . ' ', $statii);
2880 // For NOT IN op, params were set in the join
2881 if ($op == 'NOT IN') {
2882 $groupClause = "{$gcTable}.group_id IS NULL";
2887 $ssClause = $this->savedSearch($values);
2890 $groupClause = "( ( $groupClause ) OR ( $ssClause ) )";
2893 $groupClause = $ssClause;
2898 $this->_where
[$grouping][] = $groupClause;
2899 $this->_qill
[$grouping][] = $qill;
2903 * Function translates selection of group type into a list of groups.
2908 public function getGroupsFromTypeCriteria($value) {
2909 $groupIds = array();
2910 foreach ((array) $value as $groupTypeValue) {
2911 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2912 $groupIds = ($groupIds +
$groupList);
2918 * Where / qill clause for smart groups
2922 * @return string|NULL
2924 public function savedSearch(&$values) {
2925 list($name, $op, $value, $grouping, $wildcard) = $values;
2926 return $this->addGroupContactCache(array_keys((array) $value));
2930 * @param array $groups
2931 * @param string $tableAlias
2932 * @param string $joinTable
2934 * @return null|string
2936 public function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
2937 $config = CRM_Core_Config
::singleton();
2939 // Find all the groups that are part of a saved search.
2940 $groupIDs = implode(',', $groups);
2941 if (empty($groupIDs)) {
2946 SELECT id, cache_date, saved_search_id, children
2948 WHERE id IN ( $groupIDs )
2949 AND ( saved_search_id != 0
2950 OR saved_search_id IS NOT NULL
2951 OR children IS NOT NULL )
2954 $group = CRM_Core_DAO
::executeQuery($sql);
2955 $groupsFiltered = array();
2957 while ($group->fetch()) {
2958 $groupsFiltered[] = $group->id
;
2960 $this->_useDistinct
= TRUE;
2962 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
2963 CRM_Contact_BAO_GroupContactCache
::load($group);
2967 if (count($groupsFiltered)) {
2968 $groupIDsFiltered = implode(',', $groupsFiltered);
2970 if ($tableAlias == NULL) {
2971 $tableAlias = "`civicrm_group_contact_cache_{$groupIDsFiltered}`";
2974 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.id = {$tableAlias}.contact_id ";
2976 return "{$tableAlias}.group_id IN (" . $groupIDsFiltered . ")";
2983 * Where / qill clause for cms users
2989 public function ufUser(&$values) {
2990 list($name, $op, $value, $grouping, $wildcard) = $values;
2993 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2995 $this->_qill
[$grouping][] = ts('CMS User');
2997 elseif ($value == 0) {
2998 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3000 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3001 $this->_qill
[$grouping][] = ts('Not a CMS User');
3006 * All tag search specific.
3012 public function tagSearch(&$values) {
3013 list($name, $op, $value, $grouping, $wildcard) = $values;
3016 $value = "%{$value}%";
3018 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3019 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3021 $etTable = "`civicrm_entity_tag-" . $value . "`";
3022 $tTable = "`civicrm_tag-" . $value . "`";
3024 if ($useAllTagTypes[2]) {
3025 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3026 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3027 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3029 // search tag in cases
3030 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3031 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
3032 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3033 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3034 LEFT JOIN civicrm_case
3035 ON (civicrm_case_contact.case_id = civicrm_case.id
3036 AND civicrm_case.is_deleted = 0 )
3037 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3038 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3039 // search tag in activities
3040 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3041 $tActTable = "`civicrm_act_tag-" . $value . "`";
3042 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3043 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3045 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3046 = " LEFT JOIN civicrm_activity_contact
3047 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3048 LEFT JOIN civicrm_activity
3049 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3050 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3051 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3052 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3054 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $value . "' OR {$tCaseTable}.name $op '" . $value . "' OR {$tActTable}.name $op '" . $value . "')";
3055 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
3058 $etTable = "`civicrm_entity_tag-" . $value . "`";
3059 $tTable = "`civicrm_tag-" . $value . "`";
3060 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3061 {$etTable}.entity_table = 'civicrm_contact' )
3062 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3064 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3065 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
3070 * Where / qill clause for tag
3076 public function tag(&$values) {
3077 list($name, $op, $value, $grouping, $wildcard) = $values;
3079 $tagNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
3080 if (is_array($value)) {
3081 if (count($value) > 1) {
3082 $this->_useDistinct
= TRUE;
3084 foreach ($value as $id => $dontCare) {
3085 $names[] = CRM_Utils_Array
::value($id, $tagNames);
3087 $names = implode(' ' . ts('or') . ' ', $names);
3088 $value = implode(',', array_keys($value));
3091 $names = CRM_Utils_Array
::value($value, $tagNames);
3094 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3095 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3097 $etTable = "`civicrm_entity_tag-" . $value . "`";
3099 if ($useAllTagTypes[2]) {
3100 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3101 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3103 // search tag in cases
3104 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3105 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3106 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3108 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3109 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3110 LEFT JOIN civicrm_case
3111 ON (civicrm_case_contact.case_id = civicrm_case.id
3112 AND civicrm_case.is_deleted = 0 )
3113 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3114 // search tag in activities
3115 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3116 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3117 = " LEFT JOIN civicrm_activity_contact
3118 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3119 LEFT JOIN civicrm_activity
3120 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3121 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3122 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3125 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3126 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3129 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3131 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
3134 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3135 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3138 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3139 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3140 $op = str_replace('EMPTY', 'NULL', $op);
3141 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3144 $this->_where
[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
3146 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $names;
3152 * Where/qill clause for notes
3158 public function notes(&$values) {
3159 list($name, $op, $value, $grouping, $wildcard) = $values;
3161 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3162 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3163 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3165 $this->_useDistinct
= TRUE;
3167 $this->_tables
['civicrm_note'] = $this->_whereTables
['civicrm_note']
3168 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3170 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3172 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3173 if ($wildcard ||
$op == 'LIKE') {
3174 if (strpos($value, '%') === FALSE) {
3175 $value = "%$value%";
3179 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3185 if ($noteOption %
2 == 0) {
3186 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3187 $label = ts('Note: Body Only');
3189 if ($noteOption %
3 == 0) {
3190 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3191 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3193 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3194 $this->_qill
[$grouping][] = $label . " $op - '$n'";
3198 * @param string $name
3204 public function nameNullOrEmptyOp($name, $op, $grouping) {
3208 $this->_where
[$grouping][] = "contact_a.$name $op";
3209 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3213 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3214 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3217 case 'IS NOT EMPTY':
3218 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3219 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3228 * Where / qill clause for sort_name
3234 public function sortName(&$values) {
3235 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3237 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3238 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3242 $input = $value = trim($value);
3244 if (!strlen($value)) {
3248 $config = CRM_Core_Config
::singleton();
3252 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3255 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3257 $firstChar = substr($value, 0, 1);
3258 $lastChar = substr($value, -1, 1);
3259 $quotes = array("'", '"');
3260 // If string is quoted, strip quotes and otherwise don't alter it
3261 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3262 $value = trim($value, implode('', $quotes));
3264 // Replace spaces with wildcards for a LIKE operation
3265 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3266 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3267 $value = str_replace(' ', '%', $value);
3269 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($value)));
3270 if (strlen($value)) {
3271 $fieldsub = array();
3272 if ($wildcard && $op == 'LIKE') {
3273 if ($config->includeWildCardInName
) {
3274 $value = "'%$value%'";
3277 $value = "'$value%'";
3282 $value = "'$value'";
3284 if ($fieldName == 'sort_name') {
3285 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3288 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3290 $fieldsub[] = " ( $wc $op $value )";
3291 if ($config->includeNickNameInName
) {
3292 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3293 $fieldsub[] = " ( $wc $op $value )";
3295 if ($config->includeEmailInName
) {
3296 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3298 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3301 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3303 $this->_where
[$grouping][] = $sub;
3304 if ($config->includeEmailInName
) {
3305 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3306 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3309 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3314 * Where/qill clause for greeting fields.
3316 * @param array $values
3318 public function greetings(&$values) {
3319 list($name, $op, $value, $grouping, $wildcard) = $values;
3320 $name .= '_display';
3322 $this->_qill
[$grouping][] = ts('Greeting %1 %2', array(1 => $op, 2 => $value));
3323 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", 'LIKE', "$value", 'String');
3327 * Where / qill clause for email
3333 public function email(&$values) {
3334 list($name, $op, $value, $grouping, $wildcard) = $values;
3338 $config = CRM_Core_Config
::singleton();
3340 if (substr($n, 0, 1) == '"' &&
3341 substr($n, -1, 1) == '"'
3343 $n = substr($n, 1, -1);
3344 $value = strtolower(CRM_Core_DAO
::escapeString($n));
3345 $value = "'$value'";
3349 $value = strtolower($n);
3351 if (strpos($value, '%') === FALSE) {
3352 $value = "%{$value}%";
3357 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3358 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3361 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3362 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3365 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3369 * Where / qill clause for phone number
3375 public function phone_numeric(&$values) {
3376 list($name, $op, $value, $grouping, $wildcard) = $values;
3377 // Strip non-numeric characters; allow wildcards
3378 $number = preg_replace('/[^\d%]/', '', $value);
3380 if (strpos($number, '%') === FALSE) {
3381 $number = "%$number%";
3384 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3385 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3386 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3391 * Where / qill clause for phone type/location
3397 public function phone_option_group($values) {
3398 list($name, $op, $value, $grouping, $wildcard) = $values;
3399 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3400 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3401 $optionName = $options[$value];
3402 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3403 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3404 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3408 * Where / qill clause for street_address
3414 public function street_address(&$values) {
3415 list($name, $op, $value, $grouping, $wildcard) = $values;
3424 $value = strtolower($n);
3425 if (strpos($value, '%') === FALSE) {
3426 // only add wild card if not there
3427 $value = "%{$value}%";
3430 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3431 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3434 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3435 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3438 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3442 * Where / qill clause for street_unit
3448 public function street_number(&$values) {
3449 list($name, $op, $value, $grouping, $wildcard) = $values;
3457 if (strtolower($n) == 'odd') {
3458 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3459 $this->_qill
[$grouping][] = ts('Street Number is odd');
3461 elseif (strtolower($n) == 'even') {
3462 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3463 $this->_qill
[$grouping][] = ts('Street Number is even');
3466 $value = strtolower($n);
3468 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3469 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3472 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3476 * Where / qill clause for sorting by character
3482 public function sortByCharacter(&$values) {
3483 list($name, $op, $value, $grouping, $wildcard) = $values;
3485 $name = trim($value);
3486 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3487 $this->_where
[$grouping][] = $cond;
3488 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3492 * Where / qill clause for including contact ids
3496 public function includeContactIDs() {
3497 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3501 $contactIds = array();
3502 foreach ($this->_params
as $id => $values) {
3503 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3504 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3507 if (!empty($contactIds)) {
3508 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3513 * Where / qill clause for postal code
3519 public function postalCode(&$values) {
3520 // skip if the fields dont have anything to do with postal_code
3521 if (empty($this->_fields
['postal_code'])) {
3525 list($name, $op, $value, $grouping, $wildcard) = $values;
3527 // Handle numeric postal code range searches properly by casting the column as numeric
3528 if (is_numeric($value)) {
3529 $field = 'ROUND(civicrm_address.postal_code)';
3530 $val = CRM_Utils_Type
::escape($value, 'Integer');
3533 $field = 'civicrm_address.postal_code';
3534 $val = CRM_Utils_Type
::escape($value, 'String');
3537 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3539 if ($name == 'postal_code') {
3540 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3541 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3543 elseif ($name == 'postal_code_low') {
3544 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3545 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3547 elseif ($name == 'postal_code_high') {
3548 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3549 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3554 * Where / qill clause for location type
3557 * @param null $status
3561 public function locationType(&$values, $status = NULL) {
3562 list($name, $op, $value, $grouping, $wildcard) = $values;
3564 if (is_array($value)) {
3565 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3566 $this->_tables
['civicrm_address'] = 1;
3567 $this->_whereTables
['civicrm_address'] = 1;
3569 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3571 foreach ($value as $id) {
3572 $names[] = $locationType[$id];
3575 $this->_primaryLocation
= FALSE;
3578 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3581 return implode(' ' . ts('or') . ' ', $names);
3588 * @param bool $fromStateProvince
3590 * @return array|NULL
3592 public function country(&$values, $fromStateProvince = TRUE) {
3593 list($name, $op, $value, $grouping, $wildcard) = $values;
3595 if (!$fromStateProvince) {
3596 $stateValues = $this->getWhereValues('state_province', $grouping);
3597 if (!empty($stateValues)) {
3598 // return back to caller if there are state province values
3599 // since that handles this case
3604 $countryClause = $countryQill = NULL;
3610 $this->_tables
['civicrm_address'] = 1;
3611 $this->_whereTables
['civicrm_address'] = 1;
3613 $countries = CRM_Core_PseudoConstant
::country();
3614 if (is_numeric($value)) {
3615 $countryClause = self
::buildClause(
3616 'civicrm_address.country_id',
3621 $countryName = $countries[(int ) $value];
3625 $intValues = self
::parseSearchBuilderString($value);
3626 if ($intValues && ($op == 'IN' ||
$op == 'NOT IN')) {
3627 $countryClause = self
::buildClause(
3628 'civicrm_address.country_id',
3633 $countryNames = array();
3634 foreach ($intValues as $v) {
3635 $countryNames[] = $countries[$v];
3637 $countryName = implode(',', $countryNames);
3640 $countries = CRM_Core_PseudoConstant
::country();
3641 $intVal = CRM_Utils_Array
::key($value, $countries);
3642 $countryClause = self
::buildClause(
3643 'civicrm_address.country_id',
3648 $countryName = $value;
3651 $countryQill = ts('Country') . " {$op} '$countryName'";
3653 if (!$fromStateProvince) {
3654 $this->_where
[$grouping][] = $countryClause;
3655 $this->_qill
[$grouping][] = $countryQill;
3659 if ($fromStateProvince) {
3660 if (!empty($countryClause)) {
3663 " ...AND... " . $countryQill,
3667 return array(NULL, NULL);
3673 * Where / qill clause for county (if present)
3676 * @param null $status
3680 public function county(&$values, $status = NULL) {
3681 list($name, $op, $value, $grouping, $wildcard) = $values;
3683 if (!is_array($value)) {
3684 // force the county to be an array
3685 $value = array($value);
3688 // check if the values are ids OR names of the counties
3689 $inputFormat = 'id';
3690 foreach ($value as $v) {
3691 if (!is_numeric($v)) {
3692 $inputFormat = 'name';
3700 elseif ($op == '!=') {
3704 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3705 $op = str_replace('EMPTY', 'NULL', $op);
3708 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3709 $clause = "civicrm_address.county_id $op";
3711 elseif ($inputFormat == 'id') {
3712 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3714 $county = CRM_Core_PseudoConstant
::county();
3715 foreach ($value as $id) {
3716 $names[] = CRM_Utils_Array
::value($id, $county);
3720 $inputClause = array();
3721 $county = CRM_Core_PseudoConstant
::county();
3722 foreach ($value as $name) {
3723 $name = trim($name);
3724 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3726 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3729 $this->_tables
['civicrm_address'] = 1;
3730 $this->_whereTables
['civicrm_address'] = 1;
3732 $this->_where
[$grouping][] = $clause;
3734 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3737 return implode(' ' . ts('or') . ' ', $names);
3742 * Where / qill clause for state/province AND country (if present)
3745 * @param null $status
3749 public function stateProvince(&$values, $status = NULL) {
3750 list($name, $op, $value, $grouping, $wildcard) = $values;
3752 // quick escape for IS NULL
3753 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3756 elseif (!is_array($value)) {
3757 // force the state to be an array
3758 // check if its in the mapper format!
3759 $values = self
::parseSearchBuilderString($value);
3760 if (is_array($values)) {
3764 $value = array($value);
3768 // check if the values are ids OR names of the states
3769 $inputFormat = 'id';
3771 foreach ($value as $v) {
3772 if (!is_numeric($v)) {
3773 $inputFormat = 'name';
3783 elseif ($op == '!=') {
3787 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3788 $op = str_replace('EMPTY', 'NULL', $op);
3790 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3791 $stateClause = "civicrm_address.state_province_id $op";
3793 elseif ($inputFormat == 'id') {
3794 if ($op != 'NOT IN') {
3797 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
3799 foreach ($value as $id) {
3800 $names[] = CRM_Core_PseudoConstant
::stateProvince($id, FALSE);
3804 $inputClause = array();
3805 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3806 foreach ($value as $name) {
3807 $name = trim($name);
3808 $inputClause[] = CRM_Utils_Array
::key($name, $stateProvince);
3810 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
3813 $this->_tables
['civicrm_address'] = 1;
3814 $this->_whereTables
['civicrm_address'] = 1;
3816 $countryValues = $this->getWhereValues('country', $grouping);
3817 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3819 if ($countryClause) {
3820 $clause = "( $stateClause AND $countryClause )";
3823 $clause = $stateClause;
3826 $this->_where
[$grouping][] = $clause;
3828 $this->_qill
[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3831 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
3836 * Where / qill clause for change log
3842 public function changeLog(&$values) {
3843 list($name, $op, $value, $grouping, $wildcard) = $values;
3845 $targetName = $this->getWhereValues('changed_by', $grouping);
3850 $name = trim($targetName[2]);
3851 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3852 $name = $targetName[4] ?
"%$name%" : $name;
3853 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3854 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3855 $this->_qill
[$grouping][] = ts('Modified By') . " $name";
3861 public function modifiedDates($values) {
3862 $this->_useDistinct
= TRUE;
3864 // CRM-11281, default to added date if not set
3865 $fieldTitle = ts('Added Date');
3866 $fieldName = 'created_date';
3867 foreach (array_keys($this->_params
) as $id) {
3868 if ($this->_params
[$id][0] == 'log_date') {
3869 if ($this->_params
[$id][2] == 2) {
3870 $fieldTitle = ts('Modified Date');
3871 $fieldName = 'modified_date';
3876 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3878 self
::$_openedPanes[ts('Change Log')] = TRUE;
3884 public function demographics(&$values) {
3885 list($name, $op, $value, $grouping, $wildcard) = $values;
3887 if (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3889 $this->dateQueryBuilder($values,
3890 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3893 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3895 $this->dateQueryBuilder($values,
3896 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3900 self
::$_openedPanes[ts('Demographics')] = TRUE;
3906 public function privacy(&$values) {
3907 list($name, $op, $value, $grouping, $wildcard) = $values;
3908 //fixed for profile search listing CRM-4633
3909 if (strpbrk($value, "[")) {
3910 $value = "'{$value}'";
3912 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3915 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3917 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3918 $title = $field ?
$field['title'] : $name;
3919 $this->_qill
[$grouping][] = "$title $op $value";
3925 public function privacyOptions($values) {
3926 list($name, $op, $value, $grouping, $wildcard) = $values;
3928 if (empty($value) ||
!is_array($value)) {
3932 // get the operator and toggle values
3933 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3936 strtolower($opValues[2] == 'AND')
3941 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3943 if ($toggleValues &&
3944 $toggleValues[2] == 2
3951 foreach ($value as $dontCare => $pOption) {
3952 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
3953 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3954 $title = $field ?
$field['title'] : $pOption;
3955 $qill[] = " $title = 1 ";
3958 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
3959 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
3965 public function preferredCommunication(&$values) {
3966 list($name, $op, $value, $grouping, $wildcard) = $values;
3969 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3972 elseif (!is_array($value)) {
3974 $value = trim($value, ' ()');
3975 if (strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
3976 $v = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
3979 $v = explode(",", $value);
3982 foreach ($v as $item) {
3989 foreach ($value as $key => $checked) {
3996 $commPref = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
3998 $sqlValue = array();
3999 $showValue = array();
4000 $sql = "contact_a.preferred_communication_method";
4001 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
4002 $sqlValue[] = "{$sql} {$op}";
4005 foreach ($pref as $val) {
4006 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $val . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' ) ";
4007 $showValue[] = $commPref[$val];
4010 $this->_where
[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
4011 $this->_qill
[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
4015 * Where / qill clause for relationship
4021 public function relationship(&$values) {
4022 list($name, $op, $value, $grouping, $wildcard) = $values;
4023 if ($this->_relationshipValuesAdded
) {
4026 // also get values array for relation_target_name
4027 // for relationship search we always do wildcard
4028 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4029 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4030 $relStatus = $this->getWhereValues('relation_status', $grouping);
4031 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4032 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4034 $nameClause = $name = NULL;
4036 $name = trim($targetName[2]);
4037 if (substr($name, 0, 1) == '"' &&
4038 substr($name, -1, 1) == '"'
4040 $name = substr($name, 1, -1);
4041 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4042 $nameClause = "= '$name'";
4045 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4046 $nameClause = "LIKE '%{$name}%'";
4050 $rTypeValues = array();
4051 if (!empty($relationType)) {
4052 $rel = explode('_', $relationType[2]);
4053 self
::$_relType = $rel[1];
4054 $params = array('id' => $rel[0]);
4055 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
4057 if (!empty($rTypeValues) && $rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
4058 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4059 //@todo unless we are dealing with a target group
4060 self
::$_relType = 'reciprocal';
4062 // if we are creating a temp table we build our own where for the relationship table
4063 $relationshipTempTable = NULL;
4064 if (self
::$_relType == 'reciprocal' && empty($targetGroup)) {
4066 self
::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO
::createTempTableName('civicrm_rel');
4068 $where[$grouping][] = " sort_name $nameClause ";
4072 $where = &$this->_where
;
4074 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4078 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
4079 $relTypeOrg = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
4080 $relTypeHou = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Household');
4081 $allRelationshipType = array();
4082 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
4083 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
4085 if ($nameClause ||
!$targetGroup) {
4086 if (!empty($relationType)) {
4087 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " $name";
4090 $this->_qill
[$grouping][] = $name;
4094 //check to see if the target contact is in specified group
4096 //add contacts from static groups
4097 $this->_tables
['civicrm_relationship_group_contact'] = $this->_whereTables
['civicrm_relationship_group_contact']
4098 = " 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'";
4099 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4100 implode(",", $targetGroup[2]) . ") ) ";
4102 //add contacts from saved searches
4103 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
4105 //set the group where clause
4107 $groupWhere[] = "( " . $ssWhere . " )";
4109 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4111 //Get the names of the target groups for the qill
4112 $groupNames = CRM_Core_PseudoConstant
::group();
4113 $qillNames = array();
4114 foreach ($targetGroup[2] as $groupId) {
4115 if (array_key_exists($groupId, $groupNames)) {
4116 $qillNames[] = $groupNames[$groupId];
4119 if (!empty($relationType)) {
4120 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " ( " . implode(", ", $qillNames) . " )";
4123 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4127 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4128 $today = date('Ymd');
4129 //check for active, inactive and all relation status
4130 if ($relStatus[2] == 0) {
4131 $where[$grouping][] = "(
4132 civicrm_relationship.is_active = 1 AND
4133 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4134 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4136 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4138 elseif ($relStatus[2] == 1) {
4139 $where[$grouping][] = "(
4140 civicrm_relationship.is_active = 0 OR
4141 civicrm_relationship.end_date < {$today} OR
4142 civicrm_relationship.start_date > {$today}
4144 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4148 if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
)) {
4151 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4153 //check for permissioned, non-permissioned and all permissioned relations
4154 if ($relPermission[2] == 1) {
4155 $where[$grouping][] = "(
4156 civicrm_relationship.is_permission_a_b = 1
4158 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4160 elseif ($relPermission[2] == 2) {
4161 //non-allowed permission relationship.
4162 $where[$grouping][] = "(
4163 civicrm_relationship.is_permission_a_b = 0
4165 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4168 $this->addRelationshipDateClauses($grouping, $where);
4169 if (!empty($relationType) && !empty($rType) && isset($rType->id
)) {
4170 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
4172 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4173 $this->_useDistinct
= TRUE;
4174 $this->_relationshipValuesAdded
= TRUE;
4175 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4177 // @todo creating a temp table could be expanded to group filter
4178 // as even creating a temp table of all relationships is much much more efficient than
4179 // an OR in the join
4180 if ($relationshipTempTable) {
4182 if (!empty($where[$grouping])) {
4183 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4184 $whereClause = str_replace('contact_b', 'c', $whereClause);
4187 CREATE TEMPORARY TABLE {$relationshipTempTable}
4188 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4189 FROM civicrm_relationship
4190 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4193 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4194 FROM civicrm_relationship
4195 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4198 CRM_Core_DAO
::executeQuery($sql);
4204 * Add start & end date criteria in
4205 * @param string $grouping
4206 * @param array $where
4207 * = array to add where clauses to, in case you are generating a temp table.
4208 * not the main query.
4210 public function addRelationshipDateClauses($grouping, &$where) {
4211 $dateValues = array();
4217 foreach ($dateTypes as $dateField) {
4218 $dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping);
4219 $dateValueHigh = $this->getWhereValues('relation_' . $dateField . '_high', $grouping);
4220 if (!empty($dateValueLow)) {
4221 $date = date('Ymd', strtotime($dateValueLow[2]));
4222 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4223 $this->_qill
[$grouping][] = ($dateField == 'end_date' ?
ts('Relationship Ended on or After') : ts('Relationship Recorded Start Date On or Before')) . " " . CRM_Utils_Date
::customFormat($date);
4225 if (!empty($dateValueHigh)) {
4226 $date = date('Ymd', strtotime($dateValueHigh[2]));
4227 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4228 $this->_qill
[$grouping][] = ($dateField == 'end_date' ?
ts('Relationship Ended on or Before') : ts('Relationship Recorded Start Date On or After')) . " " . CRM_Utils_Date
::customFormat($date);
4234 * Default set of return properties.
4239 * derault return properties
4241 public static function &defaultReturnProperties($mode = 1) {
4242 if (!isset(self
::$_defaultReturnProperties)) {
4243 self
::$_defaultReturnProperties = array();
4246 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4247 // add activity return properties
4248 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4249 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4252 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4255 if (empty(self
::$_defaultReturnProperties[$mode])) {
4256 self
::$_defaultReturnProperties[$mode] = array(
4259 'legal_identifier' => 1,
4260 'external_identifier' => 1,
4261 'contact_type' => 1,
4262 'contact_sub_type' => 1,
4264 'display_name' => 1,
4265 'preferred_mail_format' => 1,
4272 'formal_title' => 1,
4273 'communication_style_id' => 1,
4276 'street_address' => 1,
4277 'supplemental_address_1' => 1,
4278 'supplemental_address_2' => 1,
4281 'postal_code_suffix' => 1,
4282 'state_province' => 1,
4284 'world_region' => 1,
4291 'household_name' => 1,
4292 'organization_name' => 1,
4293 'deceased_date' => 1,
4298 'current_employer' => 1,
4299 // FIXME: should we use defaultHierReturnProperties() for the below?
4300 'do_not_email' => 1,
4303 'do_not_phone' => 1,
4304 'do_not_trade' => 1,
4306 'contact_is_deleted' => 1,
4307 'preferred_communication_method' => 1,
4308 'preferred_language' => 1,
4312 return self
::$_defaultReturnProperties[$mode];
4316 * Get primary condition for a sql clause.
4320 * @return string|NULL
4322 public static function getPrimaryCondition($value) {
4323 if (is_numeric($value)) {
4324 $value = (int ) $value;
4325 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4331 * Wrapper for a simple search query.
4333 * @param array $params
4334 * @param array $returnProperties
4335 * @param bool $count
4339 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4340 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4341 list($select, $from, $where, $having) = $query->query();
4343 return "$select $from $where $having";
4347 * These are stub comments as this function needs more explanation - particularly in terms of how it
4348 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4350 * This function was originally written as a wrapper for the api query but is called from multiple places
4351 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4352 * but it is unclear as to whehter that is historical or there is a reason
4353 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4355 * @param array $params
4356 * @param array $returnProperties
4357 * @param null $fields
4358 * @param string $sort
4359 * @param int $offset
4360 * @param int $row_count
4361 * @param bool $smartGroupCache
4362 * ?? update smart group cache?.
4363 * @param bool $count
4364 * Return count obnly.
4365 * @param bool $skipPermissions
4366 * Should permissions be ignored or should the logged in user's permissions be applied.
4371 public static function apiQuery(
4373 $returnProperties = NULL,
4378 $smartGroupCache = TRUE,
4380 $skipPermissions = TRUE
4383 $query = new CRM_Contact_BAO_Query(
4384 $params, $returnProperties,
4385 NULL, TRUE, FALSE, 1,
4387 TRUE, $smartGroupCache
4390 //this should add a check for view deleted if permissions are enabled
4391 if ($skipPermissions) {
4392 $query->_skipDeleteClause
= TRUE;
4394 $query->generatePermissionClause(FALSE, $count);
4396 // note : this modifies _fromClause and _simpleFromClause
4397 $query->includePseudoFieldsJoin($sort);
4399 list($select, $from, $where, $having) = $query->query($count);
4401 $options = $query->_options
;
4402 if (!empty($query->_permissionWhereClause
)) {
4403 if (empty($where)) {
4404 $where = "WHERE $query->_permissionWhereClause";
4407 $where = "$where AND $query->_permissionWhereClause";
4411 $sql = "$select $from $where $having";
4414 if ($query->_useGroupBy
) {
4415 $sql .= ' GROUP BY contact_a.id';
4417 if (!empty($sort)) {
4418 $sort = CRM_Utils_Type
::escape($sort, 'String');
4419 $sql .= " ORDER BY $sort ";
4421 if ($row_count > 0 && $offset >= 0) {
4422 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4423 $rowCount = CRM_Utils_Type
::escape($row_count, 'Int');
4424 $sql .= " LIMIT $offset, $row_count ";
4427 $dao = CRM_Core_DAO
::executeQuery($sql);
4430 while ($dao->fetch()) {
4432 $noRows = $dao->rowCount
;
4434 return array($noRows, NULL);
4436 $val = $query->store($dao);
4437 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4439 if (!empty($convertedVals)) {
4440 $val = array_replace_recursive($val, $convertedVals);
4442 $values[$dao->contact_id
] = $val;
4445 return array($values, $options);
4449 * Create and query the db for an contact search.
4451 * @param int $offset
4452 * The offset for the query.
4453 * @param int $rowCount
4454 * The number of rows to return.
4455 * @param string $sort
4456 * The order by string.
4457 * @param bool $count
4458 * Is this a count only query ?.
4459 * @param bool $includeContactIds
4460 * Should we include contact ids?.
4461 * @param bool $sortByChar
4462 * If true returns the distinct array of first characters for search results.
4463 * @param bool $groupContacts
4464 * If true, return only the contact ids.
4465 * @param bool $returnQuery
4466 * Should we return the query as a string.
4467 * @param string $additionalWhereClause
4468 * If the caller wants to further restrict the search (used for components).
4469 * @param null $sortOrder
4470 * @param string $additionalFromClause
4471 * Should be clause with proper joins, effective to reduce where clause load.
4473 * @param bool $skipOrderAndLimit
4475 * @return CRM_Core_DAO
4477 public function searchQuery(
4478 $offset = 0, $rowCount = 0, $sort = NULL,
4479 $count = FALSE, $includeContactIds = FALSE,
4480 $sortByChar = FALSE, $groupContacts = FALSE,
4481 $returnQuery = FALSE,
4482 $additionalWhereClause = NULL, $sortOrder = NULL,
4483 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4486 if ($includeContactIds) {
4487 $this->_includeContactIds
= TRUE;
4488 $this->_whereClause
= $this->whereClause();
4491 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4493 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4494 // and that contact happens to be deleted, set $onlyDeleted to true
4495 foreach ($this->_params
as $values) {
4496 $name = CRM_Utils_Array
::value(0, $values);
4497 $op = CRM_Utils_Array
::value(1, $values);
4498 $value = CRM_Utils_Array
::value(2, $values);
4499 if ($name == 'contact_id' and $op == '=') {
4500 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4501 $onlyDeleted = TRUE;
4507 // building the query string
4510 if (isset($this->_groupByComponentClause
)) {
4511 $groupBy = $this->_groupByComponentClause
;
4513 elseif ($this->_useGroupBy
) {
4514 $groupBy = ' GROUP BY contact_a.id';
4517 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4518 $groupBy = 'GROUP BY civicrm_activity.id ';
4521 $order = $orderBy = $limit = '';
4523 $config = CRM_Core_Config
::singleton();
4524 if ($config->includeOrderByClause ||
4525 isset($this->_distinctComponentClause
)
4528 if (is_string($sort)) {
4532 $orderBy = trim($sort->orderBy());
4534 if (!empty($orderBy)) {
4535 // this is special case while searching for
4536 // change log CRM-1718
4537 if (preg_match('/sort_name/i', $orderBy)) {
4538 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4541 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
4542 $order = " ORDER BY $orderBy";
4545 $sortOrder = CRM_Utils_Type
::escape($sortOrder, 'String');
4546 $order .= " $sortOrder";
4549 // always add contact_a.id to the ORDER clause
4550 // so the order is deterministic
4551 if (strpos('contact_a.id', $order) === FALSE) {
4552 $order .= ", contact_a.id";
4556 elseif ($sortByChar) {
4557 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4560 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4564 // hack for order clause
4566 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4567 $fieldOrder = explode(' ', $fieldStr);
4568 $field = $fieldOrder[0];
4574 $this->_whereTables
["civicrm_address"] = 1;
4575 $order = str_replace($field, "civicrm_address.{$field}", $order);
4579 case 'state_province':
4580 $this->_whereTables
["civicrm_{$field}"] = 1;
4581 $order = str_replace($field, "civicrm_{$field}.name", $order);
4585 $this->_whereTables
["civicrm_email"] = 1;
4586 $order = str_replace($field, "civicrm_email.{$field}", $order);
4590 //CRM-12565 add "`" around $field if it is a pseudo constant
4591 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
4592 if (!empty($value['element']) && $value['element'] == $field) {
4593 $order = str_replace($field, "`{$field}`", $order);
4597 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4598 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4602 if ($rowCount > 0 && $offset >= 0) {
4603 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4604 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4605 $limit = " LIMIT $offset, $rowCount ";
4610 $this->_sort
= $sort;
4612 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4614 if ($additionalWhereClause) {
4615 $where = $where . ' AND ' . $additionalWhereClause;
4618 //additional from clause should be w/ proper joins.
4619 if ($additionalFromClause) {
4620 $from .= "\n" . $additionalFromClause;
4623 // if we are doing a transform, do it here
4624 // use the $from, $where and $having to get the contact ID
4625 if ($this->_displayRelationshipType
) {
4626 $this->filterRelatedContacts($from, $where, $having);
4629 if ($skipOrderAndLimit) {
4630 $query = "$select $from $where $having $groupBy";
4633 $query = "$select $from $where $having $groupBy $order $limit";
4640 return CRM_Core_DAO
::singleValueQuery($query);
4643 $dao = CRM_Core_DAO
::executeQuery($query);
4644 if ($groupContacts) {
4646 while ($dao->fetch()) {
4649 return implode(',', $ids);
4656 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4658 * @param string $cacheKey
4659 * @param int $offset
4660 * @param int $rowCount
4661 * @param bool $includeContactIds
4662 * @return CRM_Core_DAO
4664 public function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4665 $this->_includeContactIds
= $includeContactIds;
4666 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4667 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
4668 $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);
4669 $order = " ORDER BY pnc.id";
4670 $groupBy = " GROUP BY contact_a.id";
4671 $limit = " LIMIT $offset, $rowCount";
4672 $query = "$select $from $where $groupBy $order $limit";
4674 return CRM_Core_DAO
::executeQuery($query);
4678 * Populate $this->_permissionWhereClause with permission related clause and update other
4679 * query related properties.
4681 * Function calls ACL permission class and hooks to filter the query appropriately
4683 * Note that these 2 params were in the code when extracted from another function
4684 * and a second round extraction would be to make them properties of the class
4686 * @param bool $onlyDeleted
4687 * Only get deleted contacts.
4688 * @param bool $count
4689 * Return Count only.
4691 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4692 if (!$this->_skipPermission
) {
4693 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4694 CRM_Core_Permission
::VIEW
,
4696 $this->_whereTables
,
4699 $this->_skipDeleteClause
4702 // regenerate fromClause since permission might have added tables
4703 if ($this->_permissionWhereClause
) {
4704 //fix for row count in qill (in contribute/membership find)
4706 $this->_useDistinct
= TRUE;
4709 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4710 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4711 // note : this modifies _fromClause and _simpleFromClause
4712 $this->includePseudoFieldsJoin($this->_sort
);
4716 // add delete clause if needed even if we are skipping permission
4718 if (!$this->_skipDeleteClause
) {
4719 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4720 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4724 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4733 public function setSkipPermission($val) {
4734 $this->_skipPermission
= $val;
4738 * @param null $context
4742 public function &summaryContribution($context = NULL) {
4743 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4747 SELECT COUNT( conts.total_amount ) as total_count,
4748 SUM( conts.total_amount ) as total_amount,
4749 AVG( conts.total_amount ) as total_avg,
4750 conts.total_amount as amount,
4751 conts.currency as currency";
4752 if ($this->_permissionWhereClause
) {
4753 $where .= " AND " . $this->_permissionWhereClause
;
4755 if ($context == 'search') {
4756 $where .= " AND contact_a.is_deleted = 0 ";
4759 // make sure contribution is completed - CRM-4989
4760 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4763 $summary['total'] = array();
4764 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4765 $innerQuery = "SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
4766 civicrm_contribution.currency $from $completedWhere";
4768 $query = "$select FROM (
4769 $innerQuery GROUP BY civicrm_contribution.id
4773 $dao = CRM_Core_DAO
::executeQuery($query);
4775 $summary['total']['count'] = 0;
4776 $summary['total']['amount'] = $summary['total']['avg'] = array();
4777 while ($dao->fetch()) {
4778 $summary['total']['count'] +
= $dao->total_count
;
4779 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4780 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4783 $orderBy = 'ORDER BY civicrm_contribution_total_amount_count DESC';
4784 $groupBy = 'GROUP BY currency, civicrm_contribution.total_amount';
4785 $modeSQL = "$select, conts.civicrm_contribution_total_amount_count as civicrm_contribution_total_amount_count FROM ($innerQuery
4786 $groupBy $orderBy) as conts
4789 $summary['total']['mode'] = CRM_Contribute_BAO_Contribution
::computeStats('mode', $modeSQL);
4791 $medianSQL = "{$from} {$completedWhere}";
4792 $summary['total']['median'] = CRM_Contribute_BAO_Contribution
::computeStats('median', $medianSQL, 'civicrm_contribution');
4793 $summary['total']['currencyCount'] = count($summary['total']['median']);
4795 if (!empty($summary['total']['amount'])) {
4796 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4797 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4798 $summary['total']['mode'] = implode(', ', $summary['total']['mode']);
4799 $summary['total']['median'] = implode(', ', $summary['total']['median']);
4802 $summary['total']['amount'] = $summary['total']['avg'] = $summary['total']['median'] = 0;
4805 // soft credit summary
4806 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
4807 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
4810 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
4811 GROUP BY civicrm_contribution_soft.id
4814 $dao = CRM_Core_DAO
::executeQuery($query);
4815 $summary['soft_credit']['count'] = 0;
4816 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
4817 while ($dao->fetch()) {
4818 $summary['soft_credit']['count'] +
= $dao->total_count
;
4819 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4820 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4822 if (!empty($summary['soft_credit']['amount'])) {
4823 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
4824 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
4827 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
4832 //@todo - this could be one query using the IF in mysql - eg
4833 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
4834 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
4835 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
4836 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
4837 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
4838 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
4839 // FROM civicrm_contact contact_a
4840 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
4841 // WHERE ( ... where clause....
4842 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
4846 SELECT COUNT( conts.total_amount ) as cancel_count,
4847 SUM( conts.total_amount ) as cancel_amount,
4848 AVG( conts.total_amount ) as cancel_avg,
4849 conts.currency as currency";
4851 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4852 if ($context == 'search') {
4853 $where .= " AND contact_a.is_deleted = 0 ";
4856 $query = "$select FROM (
4857 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
4858 GROUP BY civicrm_contribution.id
4862 $dao = CRM_Core_DAO
::executeQuery($query);
4865 if ($dao->fetch()) {
4866 $summary['cancel']['count'] = $dao->cancel_count
;
4867 $summary['cancel']['amount'] = $dao->cancel_amount
;
4868 $summary['cancel']['avg'] = $dao->cancel_avg
;
4872 $summary['cancel']['count'] = 0;
4873 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4874 while ($dao->fetch()) {
4875 $summary['cancel']['count'] +
= $dao->cancel_count
;
4876 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4877 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4879 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4880 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
4887 * Getter for the qill object.
4891 public function qill() {
4892 return $this->_qill
;
4896 * Default set of return default hier return properties.
4900 public static function &defaultHierReturnProperties() {
4901 if (!isset(self
::$_defaultHierReturnProperties)) {
4902 self
::$_defaultHierReturnProperties = array(
4905 'legal_identifier' => 1,
4906 'external_identifier' => 1,
4907 'contact_type' => 1,
4908 'contact_sub_type' => 1,
4910 'display_name' => 1,
4917 'formal_title' => 1,
4918 'communication_style_id' => 1,
4919 'email_greeting' => 1,
4920 'postal_greeting' => 1,
4924 'preferred_communication_method' => 1,
4925 'do_not_phone' => 1,
4926 'do_not_email' => 1,
4929 'do_not_trade' => 1,
4930 'location' => array(
4932 'location_type' => 1,
4933 'street_address' => 1,
4935 'state_province' => 1,
4937 'postal_code_suffix' => 1,
4940 'phone-Mobile' => 1,
4953 'location_type' => 1,
4954 'street_address' => 1,
4956 'state_province' => 1,
4958 'postal_code_suffix' => 1,
4961 'phone-Mobile' => 1,
4975 return self
::$_defaultHierReturnProperties;
4980 * @param string $tableName
4981 * @param string $fieldName
4982 * @param string $dbFieldName
4983 * @param $fieldTitle
4984 * @param bool $appendTimeStamp
4986 public function dateQueryBuilder(
4987 &$values, $tableName, $fieldName,
4988 $dbFieldName, $fieldTitle,
4989 $appendTimeStamp = TRUE
4991 list($name, $op, $value, $grouping, $wildcard) = $values;
4993 if ($name == "{$fieldName}_low" ||
4994 $name == "{$fieldName}_high"
4996 if (isset($this->_rangeCache
[$fieldName]) ||
!$value) {
4999 $this->_rangeCache
[$fieldName] = 1;
5001 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
5003 if ($name == $fieldName . '_low') {
5005 $firstPhrase = ts('greater than or equal to');
5006 $firstDate = CRM_Utils_Date
::processDate($value);
5008 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5009 if (!empty($secondValues) && $secondValues[2]) {
5011 $secondPhrase = ts('less than or equal to');
5012 $secondValue = $secondValues[2];
5014 if ($appendTimeStamp && strlen($secondValue) == 10) {
5015 $secondValue .= ' 23:59:59';
5017 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5020 elseif ($name == $fieldName . '_high') {
5022 $firstPhrase = ts('less than or equal to');
5024 if ($appendTimeStamp && strlen($value) == 10) {
5025 $value .= ' 23:59:59';
5027 $firstDate = CRM_Utils_Date
::processDate($value);
5029 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5030 if (!empty($secondValues) && $secondValues[2]) {
5032 $secondPhrase = ts('greater than or equal to');
5033 $secondValue = $secondValues[2];
5034 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5038 if (!$appendTimeStamp) {
5039 $firstDate = substr($firstDate, 0, 8);
5041 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5044 if (!$appendTimeStamp) {
5045 $secondDate = substr($secondDate, 0, 8);
5047 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5050 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5052 $this->_where
[$grouping][] = "
5053 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5054 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5056 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5059 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5060 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5064 if ($name == $fieldName) {
5065 //In Get API, for operators other then '=' the $value is in array(op => value) format
5066 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5068 $value = $value[$op];
5071 $date = $format = NULL;
5072 if (strstr($op, 'IN')) {
5074 foreach ($value as &$date) {
5075 $date = CRM_Utils_Date
::processDate($date);
5076 if (!$appendTimeStamp) {
5077 $date = substr($date, 0, 8);
5079 $format[] = CRM_Utils_Date
::customFormat($date);
5081 $date = "('" . implode("','", $value) . "')";
5082 $format = implode(', ', $format);
5084 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5085 $date = CRM_Utils_Date
::processDate($value);
5086 if (!$appendTimeStamp) {
5087 $date = substr($date, 0, 8);
5089 $format = CRM_Utils_Date
::customFormat($date);
5094 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5097 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op";
5100 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5102 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
5103 $this->_qill
[$grouping][] = "$fieldTitle $op $format";
5109 * @param string $tableName
5110 * @param string $fieldName
5111 * @param string $dbFieldName
5112 * @param $fieldTitle
5113 * @param null $options
5115 public function numberRangeBuilder(
5117 $tableName, $fieldName,
5118 $dbFieldName, $fieldTitle,
5121 list($name, $op, $value, $grouping, $wildcard) = $values;
5123 if ($name == "{$fieldName}_low" ||
5124 $name == "{$fieldName}_high"
5126 if (isset($this->_rangeCache
[$fieldName])) {
5129 $this->_rangeCache
[$fieldName] = 1;
5131 $secondOP = $secondPhrase = $secondValue = NULL;
5133 if ($name == "{$fieldName}_low") {
5135 $firstPhrase = ts('greater than');
5137 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5138 if (!empty($secondValues)) {
5140 $secondPhrase = ts('less than');
5141 $secondValue = $secondValues[2];
5146 $firstPhrase = ts('less than');
5148 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5149 if (!empty($secondValues)) {
5151 $secondPhrase = ts('greater than');
5152 $secondValue = $secondValues[2];
5157 $this->_where
[$grouping][] = "
5158 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5159 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5161 $displayValue = $options ?
$options[$value] : $value;
5162 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5164 $this->_qill
[$grouping][]
5165 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5168 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5169 $displayValue = $options ?
$options[$value] : $value;
5170 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5172 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5177 if ($name == $fieldName) {
5181 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5183 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5184 $displayValue = $options ?
$options[$value] : $value;
5185 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5190 * Given the field name, operator, value & its data type
5191 * builds the where Clause for the query
5192 * used for handling 'IS NULL'/'IS NOT NULL' operators
5194 * @param string $field
5198 * @param string $value
5200 * @param string $dataType
5201 * Data type of the field.
5204 * Where clause for the query.
5206 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5208 $clause = "$field $op";
5216 $clause = " (NULLIF($field, '') IS NULL) ";
5219 case 'IS NOT EMPTY':
5220 $clause = " (NULLIF($field, '') IS NOT NULL) ";
5224 if (empty($dataType)) {
5225 $dataType = 'String';
5227 if (is_array($value)) {
5228 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5229 // widely used and consistent across the codebase
5230 // adding this here won't accept the search functions which don't submit an array
5231 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, $value, $dataType)) != FALSE) {
5232 return $queryString;
5235 $value = CRM_Utils_Type
::escape($value, $dataType);
5236 // if we don't have a dataType we should assume
5237 if ($dataType == 'String' ||
$dataType == 'Text') {
5238 $value = "'" . strtolower($value) . "'";
5240 return "$clause $value";
5245 * @param bool $reset
5249 public function openedSearchPanes($reset = FALSE) {
5250 if (!$reset ||
empty($this->_whereTables
)) {
5251 return self
::$_openedPanes;
5254 // pane name to table mapper
5255 $panesMapper = array(
5256 ts('Contributions') => 'civicrm_contribution',
5257 ts('Memberships') => 'civicrm_membership',
5258 ts('Events') => 'civicrm_participant',
5259 ts('Relationships') => 'civicrm_relationship',
5260 ts('Activities') => 'civicrm_activity',
5261 ts('Pledges') => 'civicrm_pledge',
5262 ts('Cases') => 'civicrm_case',
5263 ts('Grants') => 'civicrm_grant',
5264 ts('Address Fields') => 'civicrm_address',
5265 ts('Notes') => 'civicrm_note',
5266 ts('Change Log') => 'civicrm_log',
5267 ts('Mailings') => 'civicrm_mailing_event_queue',
5269 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5271 foreach (array_keys($this->_whereTables
) as $table) {
5272 if ($panName = array_search($table, $panesMapper)) {
5273 self
::$_openedPanes[$panName] = TRUE;
5277 return self
::$_openedPanes;
5283 public function setOperator($operator) {
5284 $validOperators = array('AND', 'OR');
5285 if (!in_array($operator, $validOperators)) {
5288 $this->_operator
= $operator;
5294 public function getOperator() {
5295 return $this->_operator
;
5303 public function filterRelatedContacts(&$from, &$where, &$having) {
5304 static $_rTypeProcessed = NULL;
5305 static $_rTypeFrom = NULL;
5306 static $_rTypeWhere = NULL;
5308 if (!$_rTypeProcessed) {
5309 $_rTypeProcessed = TRUE;
5311 // create temp table with contact ids
5312 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5313 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5314 CRM_Core_DAO
::executeQuery($sql);
5317 REPLACE INTO $tableName ( contact_id )
5323 CRM_Core_DAO
::executeQuery($sql);
5325 $qillMessage = ts('Contacts with a Relationship Type of: ');
5326 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5328 if (is_numeric($this->_displayRelationshipType
)) {
5329 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5331 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5332 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5335 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5336 AND displayRelType.is_active = 1
5340 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5341 if ($dirOne == 'a') {
5342 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5344 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5345 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5349 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5351 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5352 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5356 WHERE displayRelType.relationship_type_id = $relType
5357 AND displayRelType.is_active = 1
5360 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5363 if (!empty($this->_permissionWhereClause
)) {
5364 $_rTypeWhere .= "AND $this->_permissionWhereClause";
5367 if (strpos($from, $_rTypeFrom) === FALSE) {
5368 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5369 // this happens when we have an event_type in the quert (CRM-7969)
5370 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5371 $from .= $_rTypeFrom;
5372 $where = $_rTypeWhere;
5383 public static function caseImportant($op) {
5385 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5389 * @param $returnProperties
5394 public static function componentPresent(&$returnProperties, $prefix) {
5395 foreach ($returnProperties as $name => $dontCare) {
5396 if (substr($name, 0, strlen($prefix)) == $prefix) {
5404 * Builds the necessary structures for all fields that are similar to option value lookups.
5406 * @param string $name
5407 * the name of the field.
5409 * the sql operator, this function should handle ALL SQL operators.
5410 * @param string $value
5411 * depends on the operator and who's calling the query builder.
5412 * @param int $grouping
5413 * the index where to place the where clause.
5414 * @param $selectValues
5415 * The key value pairs for this element. This allows us to use this function for things besides option-value pairs.
5416 * @param array $field
5417 * an array that contains various properties of the field identified by $name.
5418 * @param string $label
5419 * The label for this field element.
5420 * @param string $dataType
5421 * The data type for this element.
5422 * @param bool $useIDsOnly
5425 * adds the where clause and qill to the query object
5427 public function optionValueQuery(
5435 $dataType = 'String',
5439 if (!empty($selectValues) && !is_array($value) && !empty($selectValues[$value])) {
5440 $qill = $selectValues[$value];
5446 $pseudoFields = array(
5453 'communication_style_id',
5456 if (is_numeric($value)) {
5457 $qill = $selectValues[(int ) $value];
5459 elseif ($op == 'IN' ||
$op == 'NOT IN') {
5460 if (is_array($value)) {
5462 $newValues = array();
5463 foreach ($value as $k => $v) {
5464 $intVals[$k] = (int) $k;
5465 $newValues[] = $selectValues[(int) $k];
5468 $value = (in_array($name, $pseudoFields)) ?
$intVals : $newValues;
5469 $qill = implode(', ', $newValues);
5472 elseif (!array_key_exists($value, $selectValues)) {
5473 // its a string, lets get the int value
5474 $value = array_search($value, $selectValues);
5477 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5478 if ($tableName == 'civicrm_contact') {
5479 $wc = "contact_a.$fieldName";
5482 $wc = "$tableName.id";
5486 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5489 if (in_array($name, $pseudoFields)) {
5490 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5491 $wc = "contact_a.{$name}_id";
5493 $dataType = 'Positive';
5494 $value = (!$value) ?
0 : $value;
5497 $this->_qill
[$grouping][] = $label . " $op '$qill'";
5498 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' ||
$op == 'RLIKE')) ?
'=' : $op;
5499 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5503 * Check and explode a user defined numeric string into an array
5504 * this was the protocol used by search builder in the old old days before we had
5505 * super nice js widgets to do the hard work
5507 * @param string $string
5508 * @param string $dataType
5509 * The dataType we should check for the values, default integer.
5511 * @return bool|array
5512 * false if string does not match the pattern
5513 * array of numeric values if string does match the pattern
5515 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5516 $string = trim($string);
5517 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5521 $string = substr($string, 1, -1);
5522 $values = explode(',', $string);
5523 if (empty($values)) {
5527 $returnValues = array();
5528 foreach ($values as $v) {
5529 if ($dataType == 'Integer' && !is_numeric($v)) {
5532 elseif ($dataType == 'String' && !is_string($v)) {
5535 $returnValues[] = trim($v);
5538 if (empty($returnValues)) {
5542 return $returnValues;
5546 * Convert the pseudo constants id's to their names
5548 * @param CRM_Core_DAO $dao
5549 * @param bool $return
5551 * @return array|NULL
5553 public function convertToPseudoNames(&$dao, $return = FALSE) {
5554 if (empty($this->_pseudoConstantsSelect
)) {
5558 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5559 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5563 if (property_exists($dao, $value['idCol'])) {
5564 $val = $dao->$value['idCol'];
5566 if (CRM_Utils_System
::isNull($val)) {
5569 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5571 $idColumn = "{$key}_id";
5572 $dao->$idColumn = $val;
5574 if ($key == 'state_province_name') {
5575 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5578 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5581 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5582 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5584 // FIX ME: we should potentially move this to component Query and write a wrapper function that
5585 // handles pseudoconstant fixes for all component
5586 elseif (in_array($value['pseudoField'], array('participant_status', 'participant_role'))) {
5587 $pseudoOptions = $viewValues = array();
5588 $pseudoOptions = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', $value['idCol']);
5589 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val) as $k => $v) {
5590 $viewValues[] = $pseudoOptions[$v];
5592 $dao->$key = implode(', ', $viewValues);
5595 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5596 $dao->$key = $labels[$val];
5599 // return converted values in array format
5601 if (strpos($key, '-') !== FALSE) {
5602 $keyVal = explode('-', $key);
5603 $current = &$values;
5604 $lastElement = array_pop($keyVal);
5605 foreach ($keyVal as $v) {
5606 if (!array_key_exists($v, $current)) {
5607 $current[$v] = array();
5609 $current = &$current[$v];
5611 $current[$lastElement] = $dao->$key;
5614 $values[$key] = $dao->$key;
5623 * Include pseudo fields LEFT JOIN.
5624 * @param string|array $sort can be a object or string
5626 * @return array|NULL
5628 public function includePseudoFieldsJoin($sort) {
5629 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5632 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5635 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5636 if (!empty($value['table'])) {
5637 $regex = "/({$value['table']}\.|{$name})/";
5638 if (preg_match($regex, $sort)) {
5639 $this->_elemnt
[$value['element']] = 1;
5640 $this->_select
[$value['element']] = $value['select'];
5641 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5642 $present[$value['table']] = $value['join'];
5646 $presentSimpleFrom = $present;
5648 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5649 array_key_exists('civicrm_country', $presentSimpleFrom)
5651 unset($presentSimpleFrom['civicrm_country']);
5653 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5654 array_key_exists('civicrm_country', $present)
5656 unset($present['civicrm_country']);
5659 $presentClause = $presentSimpleFromClause = NULL;
5660 if (!empty($present)) {
5661 $presentClause = implode(' ', $present);
5663 if (!empty($presentSimpleFrom)) {
5664 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5667 $this->_fromClause
= $this->_fromClause
. $presentClause;
5668 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5670 return array($presentClause, $presentSimpleFromClause);
5674 * Build qill for field.
5676 * Qill refers to the query detail visible on the UI.
5680 * @param $fieldValue
5682 * @param array $pseduoExtraParam
5686 public static function buildQillForFieldValue($daoName = NULL, $fieldName, $fieldValue, $op, $pseduoExtraParam = array()) {
5687 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
5689 if ($fieldName == 'activity_type_id') {
5690 $pseduoOptions = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
5692 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
5693 $pseduoOptions = CRM_Event_BAO_Event
::getEvents(0, $fieldValue, TRUE, TRUE, TRUE);
5695 elseif ($fieldName == 'contribution_product_id') {
5696 $pseduoOptions = CRM_Contribute_PseudoConstant
::products();
5699 $pseduoOptions = CRM_Core_PseudoConstant
::get($daoName, $fieldName, $pseduoExtraParam = array());
5702 //API usually have fieldValue format as array(operator => array(values)),
5703 //so we need to separate operator out of fieldValue param
5704 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5705 $op = key($fieldValue);
5706 $fieldValue = $fieldValue[$op];
5709 if (is_array($fieldValue)) {
5710 $qillString = array();
5711 if (!empty($pseduoOptions)) {
5712 foreach ((array) $fieldValue as $val) {
5713 $qillString[] = $pseduoOptions[$val];
5715 $fieldValue = implode(', ', $qillString);
5718 $fieldValue = implode(', ', $fieldValue);
5721 elseif (!empty($pseduoOptions) && array_key_exists($fieldValue, $pseduoOptions)) {
5722 $fieldValue = $pseduoOptions[$fieldValue];
5725 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), $fieldValue);