3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 * This class is a heart of 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
66 static $_defaultReturnProperties = NULL;
69 * the default set of hier return properties
74 static $_defaultHierReturnProperties;
77 * the set of input params
88 * the set of output params
92 public $_returnProperties;
102 * the name of the elements that are in the select clause
103 * used to extract the values
110 * the tables involved in the query
117 * the table involved in the where clause
121 public $_whereTables;
136 public $_whereClause;
139 * additional permission Where Clause
144 public $_permissionWhereClause;
155 * additional permission from clause
160 public $_permissionFromClause;
163 * the from clause for the simple select and alphabetical
168 public $_simpleFromClause;
179 * The english language version of the query
186 * All the fields that could potentially be involved in
194 * The cache to translate the option values into labels
201 * are we in search mode
205 public $_search = TRUE;
208 * should we skip permission checking
212 public $_skipPermission = FALSE;
215 * should we skip adding of delete clause
219 public $_skipDeleteClause = FALSE;
222 * are we in strict mode (use equality over LIKE)
226 public $_strict = FALSE;
229 * What operator to use to group the clauses
233 public $_operator = 'AND';
238 * Should we only search on primary location
242 public $_primaryLocation = TRUE;
245 * are contact ids part of the query
249 public $_includeContactIds = FALSE;
252 * Should we use the smart group cache
256 public $_smartGroupCache = TRUE;
259 * Should we display contacts with a specific relationship type
263 public $_displayRelationshipType = NULL;
266 * reference to the query object for custom values
270 public $_customQuery;
273 * should we enable the distinct clause, used if we are including
274 * more than one group
278 public $_useDistinct = FALSE;
281 * Should we just display one contact record
283 public $_useGroupBy = FALSE;
286 * the relationship type direction
299 static $_activityRole;
302 * Consider the component activity type
303 * during activity search.
308 static $_considerCompActivities;
311 * Consider with contact activities only,
312 * during activity search.
317 static $_withContactActivitiesOnly;
320 * use distinct component clause for component searches
324 public $_distinctComponentClause;
326 public $_rowCountClause;
329 * use groupBy component clause for component searches
333 public $_groupByComponentClause;
336 * Track open panes, useful in advance search
341 public static $_openedPanes = array();
344 * For search builder - which custom fields are location-dependent
347 public $_locationSpecificCustomFields = array();
350 * The tables which have a dependency on location and/or address
355 static $_dependencies = array(
356 'civicrm_state_province' => 1,
357 'civicrm_country' => 1,
358 'civicrm_county' => 1,
359 'civicrm_address' => 1,
360 'civicrm_location_type' => 1,
364 * List of location specific fields
366 static $_locationSpecificFields = array(
371 'supplemental_address_1',
372 'supplemental_address_2',
375 'postal_code_suffix',
388 * Remember if we handle either end of a number or date range
389 * so we can skip the other
391 protected $_rangeCache = array();
393 * Set to true when $this->relationship is run to avoid adding twice
396 protected $_relationshipValuesAdded = FALSE;
399 * Set to the name of the temp table if one has been created
402 static $_relationshipTempTable = NULL;
404 public $_pseudoConstantsSelect = array();
407 * class constructor which also does all the work
409 * @param array $params
410 * @param array $returnProperties
411 * @param array $fields
412 * @param boolean $includeContactIds
413 * @param boolean $strict
414 * @param bool|int $mode - mode the search is operating on
416 * @param bool $skipPermission
417 * @param bool $searchDescendentGroups
418 * @param bool $smartGroupCache
419 * @param null $displayRelationshipType
420 * @param string $operator
422 * @return \CRM_Contact_BAO_Query
425 function __construct(
426 $params = NULL, $returnProperties = NULL, $fields = NULL,
427 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
428 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
429 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
432 $this->_params
= &$params;
433 if ($this->_params
== NULL) {
434 $this->_params
= array();
437 if (empty($returnProperties)) {
438 $this->_returnProperties
= self
::defaultReturnProperties($mode);
441 $this->_returnProperties
= &$returnProperties;
444 $this->_includeContactIds
= $includeContactIds;
445 $this->_strict
= $strict;
446 $this->_mode
= $mode;
447 $this->_skipPermission
= $skipPermission;
448 $this->_smartGroupCache
= $smartGroupCache;
449 $this->_displayRelationshipType
= $displayRelationshipType;
450 $this->setOperator($operator);
453 $this->_fields
= &$fields;
454 $this->_search
= FALSE;
455 $this->_skipPermission
= TRUE;
458 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE);
460 $fields = CRM_Core_Component
::getQueryFields();
461 unset($fields['note']);
462 $this->_fields
= array_merge($this->_fields
, $fields);
464 // add activity fields
465 $fields = CRM_Activity_BAO_Activity
::exportableFields();
466 $this->_fields
= array_merge($this->_fields
, $fields);
468 // add any fields provided by hook implementers
469 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
470 $this->_fields
= array_merge($this->_fields
, $extFields);
473 // basically do all the work once, and then reuse it
478 * function which actually does all the work for the constructor
483 function initialize() {
484 $this->_select
= array();
485 $this->_element
= array();
486 $this->_tables
= array();
487 $this->_whereTables
= array();
488 $this->_where
= array();
489 $this->_qill
= array();
490 $this->_options
= array();
491 $this->_cfIDs
= array();
492 $this->_paramLookup
= array();
493 $this->_having
= array();
495 $this->_customQuery
= NULL;
497 // reset cached static variables - CRM-5803
498 self
::$_activityRole = NULL;
499 self
::$_considerCompActivities = NULL;
500 self
::$_withContactActivitiesOnly = NULL;
502 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
503 $this->_element
['contact_id'] = 1;
504 $this->_tables
['civicrm_contact'] = 1;
506 if (!empty($this->_params
)) {
507 $this->buildParamsLookup();
510 $this->_whereTables
= $this->_tables
;
512 $this->selectClause();
513 $this->_whereClause
= $this->whereClause();
515 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
516 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
518 $this->openedSearchPanes(TRUE);
521 function buildParamsLookup() {
522 // first fix and handle contact deletion nicely
523 // this code is primarily for search builder use case
524 // where different clauses can specify if they want deleted
527 $trashParamExists = FALSE;
528 $paramByGroup = array();
529 foreach ( $this->_params
as $k => $param ) {
530 if (!empty($param[0]) && $param[0] == 'contact_is_deleted' ) {
531 $trashParamExists = TRUE;
533 if (!empty($param[3])) {
534 $paramByGroup[$param[3]][$k] = $param;
538 if ( $trashParamExists ) {
539 $this->_skipDeleteClause
= TRUE;
541 //cycle through group sets and explicitly add trash param if not set
542 foreach ( $paramByGroup as $setID => $set ) {
544 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params
) &&
545 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params
) ) {
546 $this->_params
[] = array(
547 'contact_is_deleted',
557 foreach ($this->_params
as $value) {
558 if (empty($value[0])) {
561 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
563 if (!array_key_exists($cfID, $this->_cfIDs
)) {
564 $this->_cfIDs
[$cfID] = array();
566 $this->_cfIDs
[$cfID][] = $value;
569 if (!array_key_exists($value[0], $this->_paramLookup
)) {
570 $this->_paramLookup
[$value[0]] = array();
572 $this->_paramLookup
[$value[0]][] = $value;
577 * Some composite fields do not appear in the fields array
578 * hack to make them part of the query
583 function addSpecialFields() {
584 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
585 foreach ($special as $name) {
586 if (!empty($this->_returnProperties
[$name])) {
587 $this->_select
[$name] = "contact_a.{$name} as $name";
588 $this->_element
[$name] = 1;
594 * Given a list of conditions in params and a list of desired
595 * return Properties generate the required select and from
596 * clauses. Note that since the where clause introduces new
597 * tables, the initial attempt also retrieves all variables used
603 function selectClause() {
605 $this->addSpecialFields();
607 foreach ($this->_fields
as $name => $field) {
608 // skip component fields
609 // there are done by the alter query below
610 // and need not be done on every field
612 (substr($name, 0, 12) == 'participant_') ||
613 (substr($name, 0, 7) == 'pledge_') ||
614 (substr($name, 0, 5) == 'case_')
619 // redirect to activity select clause
621 (substr($name, 0, 9) == 'activity_') ||
622 ($name == 'parent_id')
624 CRM_Activity_BAO_Query
::select($this);
628 // if this is a hierarchical name, we ignore it
629 $names = explode('-', $name);
630 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
634 // make an exception for special cases, to add the field in select clause
635 $makeException = FALSE;
637 //special handling for groups/tags
638 if (in_array($name, array('groups', 'tags', 'notes'))
639 && isset($this->_returnProperties
[substr($name, 0, -1)])
641 $makeException = TRUE;
644 // since note has 3 different options we need special handling
645 // note / note_subject / note_body
646 if ($name == 'notes') {
647 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
648 if (isset($this->_returnProperties
[$noteField])) {
649 $makeException = TRUE;
655 if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id'))) {
656 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
657 $makeException = TRUE;
661 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
662 if (!empty($this->_paramLookup
[$name]) ||
!empty($this->_returnProperties
[$name]) ||
666 // add to cfIDs array if not present
667 if (!array_key_exists($cfID, $this->_cfIDs
)) {
668 $this->_cfIDs
[$cfID] = array();
671 elseif (isset($field['where'])) {
672 list($tableName, $fieldName) = explode('.', $field['where'], 2);
673 if (isset($tableName)) {
674 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
675 $this->_tables
['civicrm_address'] = 1;
676 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
677 $this->_element
['address_id'] = 1;
680 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
681 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
683 if ($tableName == 'im_provider') {
684 CRM_Core_OptionValue
::select($this);
687 if (in_array($tableName,
688 array('email_greeting', 'postal_greeting', 'addressee'))) {
689 $this->_element
["{$name}_id"] = 1;
690 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
691 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
692 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
693 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
695 if ($tableName == 'email_greeting') {
696 $this->_pseudoConstantsSelect
[$name]['join'] =
697 " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
698 $this->_pseudoConstantsSelect
[$name]['join'] .=
699 " 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 ) ";
701 elseif ($tableName == 'postal_greeting') {
702 $this->_pseudoConstantsSelect
[$name]['join'] =
703 " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
704 $this->_pseudoConstantsSelect
[$name]['join'] .=
705 " 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 ) ";
707 elseif ($tableName == 'addressee') {
708 $this->_pseudoConstantsSelect
[$name]['join'] =
709 " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
710 $this->_pseudoConstantsSelect
[$name]['join'] .=
711 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
713 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
716 $greetField = "{$name}_display";
717 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
718 $this->_element
[$greetField] = 1;
720 $greetField = "{$name}_custom";
721 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
722 $this->_element
[$greetField] = 1;
726 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
727 $this->_tables
[$tableName] = 1;
730 // also get the id of the tableName
731 $tName = substr($tableName, 8);
732 if (in_array($tName, array('country', 'state_province', 'county'))) {
733 if ($tName == 'state_province') {
734 $this->_pseudoConstantsSelect
['state_province_name'] =
735 array('pseudoField' => "{$tName}", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address',
736 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
738 $this->_pseudoConstantsSelect
[$tName] =
739 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id",
740 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
743 $this->_pseudoConstantsSelect
[$name] =
744 array('pseudoField' => "{$tName}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address',
745 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
748 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
749 $this->_element
["{$tName}_id"] = 1;
751 elseif ($tName != 'contact') {
752 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
753 $this->_element
["{$tName}_id"] = 1;
756 //special case for phone
757 if ($name == 'phone') {
758 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
759 $this->_element
['phone_type_id'] = 1;
762 // if IM then select provider_id also
763 // to get "IM Service Provider" in a file to be exported, CRM-3140
765 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
766 $this->_element
['provider_id'] = 1;
769 if ($tName == 'contact') {
770 // special case, when current employer is set for Individual contact
771 if ($fieldName == 'organization_name') {
772 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
774 elseif ($fieldName != 'id') {
775 if ($fieldName == 'prefix_id') {
776 $this->_pseudoConstantsSelect
['individual_prefix'] = array('pseudoField' => 'prefix_id', 'idCol' => "prefix_id", 'bao' => 'CRM_Contact_BAO_Contact');
778 if ($fieldName == 'suffix_id') {
779 $this->_pseudoConstantsSelect
['individual_suffix'] = array('pseudoField' => 'suffix_id', 'idCol' => "suffix_id", 'bao' => 'CRM_Contact_BAO_Contact');
781 if ($fieldName == 'gender_id') {
782 $this->_pseudoConstantsSelect
['gender'] = array('pseudoField' => 'gender_id', 'idCol' => "gender_id", 'bao' => 'CRM_Contact_BAO_Contact');
784 if ($name == 'communication_style_id') {
785 $this->_pseudoConstantsSelect
['communication_style'] = array('pseudoField' => 'communication_style_id', 'idCol' => "communication_style_id", 'bao' => 'CRM_Contact_BAO_Contact');
787 $this->_select
[$name] = "contact_a.{$fieldName} as `$name`";
790 elseif (in_array($tName, array('country', 'county'))) {
791 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
792 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
794 elseif ($tName == 'state_province') {
795 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
796 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
799 $this->_select
[$name] = "{$field['where']} as `$name`";
801 if (!in_array($tName, array('state_province', 'country', 'county'))) {
802 $this->_element
[$name] = 1;
807 elseif ($name === 'tags') {
808 $this->_useGroupBy
= TRUE;
809 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
810 $this->_element
[$name] = 1;
811 $this->_tables
['civicrm_tag'] = 1;
812 $this->_tables
['civicrm_entity_tag'] = 1;
814 elseif ($name === 'groups') {
815 $this->_useGroupBy
= TRUE;
816 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
817 $this->_element
[$name] = 1;
818 $this->_tables
['civicrm_group'] = 1;
820 elseif ($name === 'notes') {
821 // if note field is subject then return subject else body of the note
822 $noteColumn = 'note';
823 if (isset($noteField) && $noteField == 'note_subject') {
824 $noteColumn = 'subject';
827 $this->_useGroupBy
= TRUE;
828 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
829 $this->_element
[$name] = 1;
830 $this->_tables
['civicrm_note'] = 1;
832 elseif ($name === 'current_employer') {
833 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
834 $this->_element
[$name] = 1;
838 if ($cfID && !empty($field['is_search_range'])) {
839 // this is a custom field with range search enabled, so we better check for two/from values
840 if (!empty($this->_paramLookup
[$name . '_from'])) {
841 if (!array_key_exists($cfID, $this->_cfIDs
)) {
842 $this->_cfIDs
[$cfID] = array();
844 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
845 // search in the cdID array for the same grouping
847 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
848 if ($c[3] == $p[3]) {
849 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
854 $p[2] = array('from' => $p[2]);
855 $this->_cfIDs
[$cfID][] = $p;
859 if (!empty($this->_paramLookup
[$name . '_to'])) {
860 if (!array_key_exists($cfID, $this->_cfIDs
)) {
861 $this->_cfIDs
[$cfID] = array();
863 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
864 // search in the cdID array for the same grouping
866 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
867 if ($c[4] == $p[4]) {
868 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
873 $p[2] = array('to' => $p[2]);
874 $this->_cfIDs
[$cfID][] = $p;
881 // add location as hierarchical elements
882 $this->addHierarchicalElements();
884 // add multiple field like website
885 $this->addMultipleElements();
888 CRM_Core_Component
::alterQuery($this, 'select');
890 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
892 if (!empty($this->_cfIDs
)) {
893 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
894 $this->_customQuery
->query();
895 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
896 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
897 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
898 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
899 $this->_options
= $this->_customQuery
->_options
;
904 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
910 function addHierarchicalElements() {
911 if (empty($this->_returnProperties
['location'])) {
914 if (!is_array($this->_returnProperties
['location'])) {
918 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
919 $processed = array();
922 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
923 $addressCustomFieldIds = array();
925 foreach ($this->_returnProperties
['location'] as $name => $elements) {
926 $lCond = self
::getPrimaryCondition($name);
929 $locationTypeId = array_search($name, $locationTypes);
930 if ($locationTypeId === FALSE) {
933 $lCond = "location_type_id = $locationTypeId";
934 $this->_useDistinct
= TRUE;
936 //commented for CRM-3256
937 $this->_useGroupBy
= TRUE;
940 $name = str_replace(' ', '_', $name);
942 $tName = "$name-location_type";
943 $ltName = "`$name-location_type`";
944 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
945 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
946 $this->_element
["{$tName}_id"] = 1;
947 $this->_element
["{$tName}"] = 1;
949 $locationTypeName = $tName;
950 $locationTypeJoin = array();
954 foreach ($elements as $elementFullName => $dontCare) {
956 $elementName = $elementCmpName = $elementFullName;
958 if (substr($elementCmpName, 0, 5) == 'phone') {
959 $elementCmpName = 'phone';
962 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
963 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
964 $addressCustomFieldIds[$cfID][$name] = 1;
967 //add address table only once
968 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
970 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
972 $tName = "$name-address";
973 $aName = "`$name-address`";
974 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
975 $this->_element
["{$tName}_id"] = 1;
976 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
977 $this->_tables
[$tName] = $addressJoin;
978 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
979 $processed[$aName] = 1;
983 $cond = $elementType = '';
984 if (strpos($elementName, '-') !== FALSE) {
985 // this is either phone, email or IM
986 list($elementName, $elementType) = explode('-', $elementName);
989 if (($elementName != 'phone') && ($elementName != 'im')) {
990 $cond = self
::getPrimaryCondition($elementType);
992 // CRM-13011 : If location type is primary, do not restrict search to the phone
993 // type id - we want the primary phone, regardless of what type it is.
994 // Otherwise, restrict to the specified phone type for the given field.
995 if ((!$cond) && ($elementName == 'phone') && $elements['location_type'] != 'Primary') {
996 $cond = "phone_type_id = '$elementType'";
998 elseif ((!$cond) && ($elementName == 'im')) {
999 // IM service provider id, CRM-3140
1000 $cond = "provider_id = '$elementType'";
1002 $elementType = '-' . $elementType;
1005 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
1007 // hack for profile, add location id
1010 // fix for CRM-882( to handle phone types )
1011 !is_numeric($elementType)
1013 if (is_numeric($name)) {
1014 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1017 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1020 elseif (is_numeric($name)) {
1021 //this for phone type to work
1022 if (in_array($elementName, array('phone', 'phone_ext'))) {
1023 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1026 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1030 //this is for phone type to work for profile edit
1031 if (in_array($elementName, array('phone', 'phone_ext'))) {
1032 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1035 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1040 // Check if there is a value, if so also add to where Clause
1042 if ($this->_params
) {
1044 if (isset($locationTypeId)) {
1045 $nm .= "-$locationTypeId";
1047 if (!is_numeric($elementType)) {
1048 $nm .= "$elementType";
1051 foreach ($this->_params
as $id => $values) {
1052 if ((is_array($values) && $values[0] == $nm) ||
1053 (in_array($elementName, array('phone', 'im'))
1054 && (strpos($values[0], $nm) !== FALSE)
1064 if ($field && isset($field['where'])) {
1065 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1066 $pf = substr($tableName, 8);
1067 $tName = $name . '-' . $pf . $elementType;
1068 if (isset($tableName)) {
1069 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1070 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1073 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1076 $this->_element
["{$tName}_id"] = 1;
1077 if (substr($tName, -15) == '-state_province') {
1078 // FIXME: hack to fix CRM-1900
1079 $a = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1083 if (substr_count($a, 'state_province_name') > 0) {
1084 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1085 array('pseudoField' => "{$pf}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1086 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1089 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] =
1090 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id");
1091 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1095 if (substr($elementFullName, 0, 2) == 'im') {
1096 $provider = "{$name}-{$elementFullName}-provider_id";
1097 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1098 $this->_element
[$provider] = 1;
1100 if ($pf == 'country' ||
$pf == 'county') {
1101 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array('pseudoField' => "{$pf}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
1102 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1105 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1109 if (in_array($pf, array('state_province', 'country', 'county'))) {
1110 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1113 $this->_element
["{$name}-{$elementFullName}"] = 1;
1116 if (empty($processed["`$tName`"])) {
1117 $processed["`$tName`"] = 1;
1118 $newName = $tableName . '_' . $index;
1119 switch ($tableName) {
1120 case 'civicrm_phone':
1121 case 'civicrm_email':
1123 case 'civicrm_openid':
1125 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id AND `$tName`.$lCond";
1126 // this special case to add phone type
1128 $phoneTypeCondition = " AND `$tName`.$cond ";
1129 //gross hack to pickup corrupted data also, CRM-7603
1130 if (strpos($cond, 'phone_type_id') !== FALSE) {
1131 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1133 $this->_tables
[$tName] .= $phoneTypeCondition;
1136 //build locationType join
1137 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1140 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1144 case 'civicrm_state_province':
1145 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1146 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1147 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1149 $this->_whereTables
["{$name}-address"] = $addressJoin;
1153 case 'civicrm_country':
1154 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1155 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1156 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1158 $this->_whereTables
["{$name}-address"] = $addressJoin;
1162 case 'civicrm_county':
1163 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1164 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join'] =
1165 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1167 $this->_whereTables
["{$name}-address"] = $addressJoin;
1173 $this->_whereTables
["{$name}-address"] = $addressJoin;
1182 // add location type join
1183 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1184 $this->_tables
[$locationTypeName] = $ltypeJoin;
1186 // table should be present in $this->_whereTables,
1187 // to add its condition in location type join, CRM-3939.
1188 if ($addWhereCount) {
1189 $locClause = array();
1190 foreach ($this->_whereTables
as $tableName => $clause) {
1191 if (!empty($locationTypeJoin[$tableName])) {
1192 $locClause[] = $locationTypeJoin[$tableName];
1196 if (!empty($locClause)) {
1197 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1202 if (!empty($addressCustomFieldIds)) {
1203 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1204 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1205 foreach ($locTypeName as $name => $dnc) {
1206 $this->_locationSpecificCustomFields
[$cfID] = array($name, array_search($name, $locationTypes));
1207 $fieldName = "$name-custom_{$cfID}";
1208 $tName = "$name-address-custom-{$cfID}";
1209 $aName = "`$name-address-custom-{$cfID}`";
1210 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1211 $this->_element
["{$tName}_id"] = 1;
1212 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1213 $this->_element
[$fieldName] = 1;
1214 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1221 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
1227 function addMultipleElements() {
1228 if (empty($this->_returnProperties
['website'])) {
1231 if (!is_array($this->_returnProperties
['website'])) {
1235 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1236 foreach ($elements as $elementFullName => $dontCare) {
1237 $tName = "website-{$key}-{$elementFullName}";
1238 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1239 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1240 $this->_element
["{$tName}_id"] = 1;
1241 $this->_element
["{$tName}"] = 1;
1243 $type = "website-{$key}-website_type_id";
1244 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1245 $this->_element
[$type] = 1;
1246 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1252 * generate the query based on what type of query we need
1254 * @param boolean $count
1255 * @param boolean $sortByChar
1256 * @param boolean $groupContacts
1258 * @return array sql query parts as an array
1261 function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE) {
1263 if (isset($this->_rowCountClause
)) {
1264 $select = "SELECT {$this->_rowCountClause}";
1265 } else if (isset($this->_distinctComponentClause
)) {
1266 // we add distinct to get the right count for components
1267 // for the more complex result set, we use GROUP BY the same id
1269 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1272 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1274 $from = $this->_simpleFromClause
;
1275 if ($this->_useDistinct
) {
1276 $this->_useGroupBy
= TRUE;
1279 elseif ($sortByChar) {
1280 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1281 $from = $this->_simpleFromClause
;
1283 elseif ($groupContacts) {
1284 $select = 'SELECT contact_a.id as id';
1285 if ($this->_useDistinct
) {
1286 $this->_useGroupBy
= TRUE;
1288 $from = $this->_simpleFromClause
;
1291 if (!empty($this->_paramLookup
['group'])) {
1292 // make sure there is only one element
1293 // this is used when we are running under smog and need to know
1294 // how the contact was added (CRM-1203)
1295 if ((count($this->_paramLookup
['group']) == 1) &&
1296 (count($this->_paramLookup
['group'][0][2]) == 1)
1298 $groups = array_keys($this->_paramLookup
['group'][0][2]);
1299 $groupId = $groups[0];
1301 //check if group is saved search
1302 $group = new CRM_Contact_BAO_Group();
1303 $group->id
= $groupId;
1306 if (!isset($group->saved_search_id
)) {
1307 $tbName = "`civicrm_group_contact-{$groupId}`";
1308 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1309 $this->_element
['group_contact_id'] = 1;
1310 $this->_select
['status'] = "$tbName.status as status";
1311 $this->_element
['status'] = 1;
1314 $this->_useGroupBy
= TRUE;
1316 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1317 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1319 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1320 $this->_useDistinct
= FALSE;
1321 $this->_useGroupBy
= TRUE;
1325 $select = "SELECT ";
1326 if (isset($this->_distinctComponentClause
)) {
1327 $select .= "{$this->_distinctComponentClause}, ";
1329 $select .= implode(', ', $this->_select
);
1330 $from = $this->_fromClause
;
1334 if (!empty($this->_whereClause
)) {
1335 $where = "WHERE {$this->_whereClause}";
1339 if (!empty($this->_having
)) {
1340 foreach ($this->_having
as $havingsets) {
1341 foreach ($havingsets as $havingset) {
1342 $havingvalue[] = $havingset;
1345 $having = ' HAVING ' . implode(' AND ', $havingvalue);
1348 // if we are doing a transform, do it here
1349 // use the $from, $where and $having to get the contact ID
1350 if ($this->_displayRelationshipType
) {
1351 $this->filterRelatedContacts($from, $where, $having);
1354 return array($select, $from, $where, $having);
1363 function &getWhereValues($name, $grouping) {
1365 foreach ($this->_params
as $values) {
1366 if ($values[0] == $name && $values[3] == $grouping) {
1379 static function fixDateValues($relative, &$from, &$to) {
1381 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1386 * @param $formValues
1387 * @param int $wildcard
1388 * @param bool $useEquals
1392 static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE) {
1394 if (empty($formValues)) {
1398 foreach ($formValues as $id => $values) {
1399 if ($id == 'privacy') {
1400 if (is_array($formValues['privacy'])) {
1401 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1402 foreach ($formValues['privacy'] as $key => $value) {
1404 $params[] = array($key, $op, $value, 0, 0);
1409 elseif ($id == 'email_on_hold') {
1410 if ($formValues['email_on_hold']['on_hold']) {
1411 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1414 elseif (preg_match('/_date_relative$/', $id) ||
1415 $id == 'event_relative' ||
1416 $id == 'case_from_relative' ||
1417 $id == 'case_to_relative'
1419 if ($id == 'event_relative') {
1420 $fromRange = 'event_start_date_low';
1421 $toRange = 'event_end_date_high';
1423 else if ($id == 'case_from_relative') {
1424 $fromRange = 'case_from_start_date_low';
1425 $toRange = 'case_from_start_date_high';
1427 else if ($id == 'case_to_relative') {
1428 $fromRange = 'case_to_end_date_low';
1429 $toRange = 'case_to_end_date_high';
1432 $dateComponent = explode('_date_relative', $id);
1433 $fromRange = "{$dateComponent[0]}_date_low";
1434 $toRange = "{$dateComponent[0]}_date_high";
1437 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1438 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1443 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals);
1448 $params[] = $values;
1457 * @param int $wildcard
1458 * @param bool $useEquals
1460 * @return array|null
1462 static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE) {
1463 // skip a few search variables
1464 static $skipWhere = NULL;
1465 static $likeNames = NULL;
1468 if (CRM_Utils_System
::isNull($values)) {
1474 'task', 'radio_ts', 'uf_group_id',
1475 'component_mode', 'qfKey', 'operator',
1476 'display_relationship_type',
1480 if (in_array($id, $skipWhere) ||
1481 substr($id, 0, 4) == '_qf_' ||
1482 substr($id, 0, 7) == 'hidden_'
1488 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1491 // email comes in via advanced search
1492 // so use wildcard always
1493 if ($id == 'email') {
1497 if (!$useEquals && in_array($id, $likeNames)) {
1498 $result = array($id, 'LIKE', $values, 0, 1);
1500 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1501 $result = array($id, 'LIKE', $values, 0, 0);
1503 elseif ($id == 'group') {
1504 if (is_array($values)) {
1505 foreach ($values as $groupIds => $val) {
1507 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1508 if (strlen($matches[1]) > 0) {
1509 $values[$matches[1]] = 1;
1510 unset($values[$groupIds]);
1516 $groupIds = explode(',', $values);
1518 foreach ($groupIds as $groupId) {
1519 $values[$groupId] = 1;
1523 $result = array($id, 'IN', $values, 0, 0);
1525 elseif ($id == 'contact_tags' ||
$id == 'tag') {
1526 if (!is_array($values)) {
1527 $tagIds = explode(',', $values);
1529 foreach ($tagIds as $tagId) {
1530 $values[$tagId] = 1;
1533 $result = array($id, 'IN', $values, 0, 0);
1536 $result = array($id, '=', $values, 0, $wildcard);
1545 function whereClauseSingle(&$values) {
1546 // do not process custom fields or prefixed contact ids or component params
1547 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1548 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1549 (substr($values[0], 0, 13) == 'contribution_') ||
1550 (substr($values[0], 0, 6) == 'event_') ||
1551 (substr($values[0], 0, 12) == 'participant_') ||
1552 (substr($values[0], 0, 7) == 'member_') ||
1553 (substr($values[0], 0, 6) == 'grant_') ||
1554 (substr($values[0], 0, 7) == 'pledge_') ||
1555 (substr($values[0], 0, 5) == 'case_') ||
1556 (substr($values[0], 0, 10) == 'financial_') ||
1557 (substr($values[0], 0, 11) == 'membership_')
1562 // skip for hook injected fields / params
1563 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1564 if (array_key_exists($values[0], $extFields)) {
1568 switch ($values[0]) {
1569 case 'deleted_contacts':
1570 $this->deletedContacts($values);
1573 case 'contact_type':
1574 $this->contactType($values);
1577 case 'contact_sub_type':
1578 $this->contactSubType($values);
1582 $this->group($values);
1586 // so we resolve this into a list of groups & proceed as if they had been
1588 list($name, $op, $value, $grouping, $wildcard) = $values;
1589 $values[0] = 'group';
1591 $this->_paramLookup
['group'][0][0] ='group';
1592 $this->_paramLookup
['group'][0][1] = 'IN';
1593 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1594 $this->group($values);
1597 // case tag comes from find contacts
1599 $this->tagSearch($values);
1603 case 'contact_tags':
1604 $this->tag($values);
1609 case 'note_subject':
1610 $this->notes($values);
1614 $this->ufUser($values);
1618 case 'display_name':
1619 $this->sortName($values);
1623 $this->email($values);
1626 case 'phone_numeric':
1627 $this->phone_numeric($values);
1630 case 'phone_phone_type_id':
1631 case 'phone_location_type_id':
1632 $this->phone_option_group($values);
1635 case 'street_address':
1636 $this->street_address($values);
1639 case 'street_number':
1640 $this->street_number($values);
1643 case 'sortByCharacter':
1644 $this->sortByCharacter($values);
1647 case 'location_type':
1648 $this->locationType($values);
1652 $this->county($values);
1655 case 'state_province':
1656 $this->stateProvince($values);
1660 $this->country($values, FALSE);
1664 case 'postal_code_low':
1665 case 'postal_code_high':
1666 $this->postalCode($values);
1669 case 'activity_date':
1670 case 'activity_date_low':
1671 case 'activity_date_high':
1672 case 'activity_role':
1673 case 'activity_status':
1674 case 'followup_parent_id':
1676 case 'activity_subject':
1677 case 'test_activities':
1678 case 'activity_type_id':
1679 case 'activity_type':
1680 case 'activity_survey_id':
1681 case 'activity_tags':
1682 case 'activity_taglist':
1683 case 'activity_test':
1684 case 'activity_campaign_id':
1685 case 'activity_engagement_level':
1687 case 'activity_result':
1688 case 'source_contact':
1689 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1692 case 'birth_date_low':
1693 case 'birth_date_high':
1694 case 'deceased_date_low':
1695 case 'deceased_date_high':
1696 $this->demographics($values);
1699 case 'log_date_low':
1700 case 'log_date_high':
1701 $this->modifiedDates($values);
1705 $this->changeLog($values);
1708 case 'do_not_phone':
1709 case 'do_not_email':
1712 case 'do_not_trade':
1714 $this->privacy($values);
1717 case 'privacy_options':
1718 $this->privacyOptions($values);
1721 case 'privacy_operator':
1722 case 'privacy_toggle':
1723 // these are handled by privacy options
1726 case 'preferred_communication_method':
1727 $this->preferredCommunication($values);
1730 case 'relation_type_id':
1731 case 'relation_start_date_high':
1732 case 'relation_start_date_low':
1733 case 'relation_end_date_high':
1734 case 'relation_end_date_low':
1735 case 'relation_target_name':
1736 case 'relation_status':
1737 case 'relation_date_low':
1738 case 'relation_date_high':
1739 $this->relationship($values);
1740 $this->_relationshipValuesAdded
= TRUE;
1743 case 'task_status_id':
1744 $this->task($values);
1748 // since this case is handled with the above
1751 case 'prox_distance':
1752 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1755 case 'prox_street_address':
1757 case 'prox_postal_code':
1758 case 'prox_state_province_id':
1759 case 'prox_country_id':
1760 // handled by the proximity_distance clause
1764 $this->restWhere($values);
1770 * Given a list of conditions in params generate the required
1776 function whereClause() {
1777 $this->_where
[0] = array();
1778 $this->_qill
[0] = array();
1780 $this->includeContactIds();
1781 if (!empty($this->_params
)) {
1782 foreach (array_keys($this->_params
) as $id) {
1783 if (empty($this->_params
[$id][0])) {
1786 // check for both id and contact_id
1787 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
1789 $this->_params
[$id][1] == 'IS NULL' ||
1790 $this->_params
[$id][1] == 'IS NOT NULL'
1792 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]}";
1794 elseif (is_array($this->_params
[$id][2])) {
1795 $idList = implode("','", $this->_params
[$id][2]);
1796 //why on earth do they put ' in the middle & not on the outside? We have to assume it's
1797 //to support 'something' so lets add them conditionally to support the api (which is a tested flow
1798 // so if you are looking to alter this check api test results
1799 if(strpos(trim($idList), "'") > 0) {
1800 $idList = "'" . $idList . "'";
1803 $this->_where
[0][] = "contact_a.id IN ({$idList})";
1806 $this->_where
[0][] = "contact_a.id {$this->_params[$id][1]} {$this->_params[$id][2]}";
1810 $this->whereClauseSingle($this->_params
[$id]);
1814 CRM_Core_Component
::alterQuery($this, 'where');
1816 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
1819 if ($this->_customQuery
) {
1820 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1821 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1822 if (!empty($this->_customQuery
->_where
)) {
1823 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
1826 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
1830 $andClauses = array();
1833 if (!empty($this->_where
)) {
1834 foreach ($this->_where
as $grouping => $values) {
1835 if ($grouping > 0 && !empty($values)) {
1836 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1841 if (!empty($this->_where
[0])) {
1842 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
1844 if (!empty($clauses)) {
1845 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1848 if ($validClauses > 1) {
1849 $this->_useDistinct
= TRUE;
1853 return implode(' AND ', $andClauses);
1861 function restWhere(&$values) {
1862 $name = CRM_Utils_Array
::value(0, $values);
1863 $op = CRM_Utils_Array
::value(1, $values);
1864 $value = CRM_Utils_Array
::value(2, $values);
1865 $grouping = CRM_Utils_Array
::value(3, $values);
1866 $wildcard = CRM_Utils_Array
::value(4, $values);
1868 if (isset($grouping) && empty($this->_where
[$grouping])) {
1869 $this->_where
[$grouping] = array();
1872 $multipleFields = array('url');
1874 //check if the location type exits for fields
1876 $locType = explode('-', $name);
1878 if (!in_array($locType[0], $multipleFields)) {
1879 //add phone type if exists
1880 if (isset($locType[2]) && $locType[2]) {
1881 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
1885 $field = CRM_Utils_Array
::value($name, $this->_fields
);
1888 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
1897 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
1898 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1900 if (substr($name, 0, 14) === 'state_province') {
1901 if (isset($locType[1]) && is_numeric($locType[1])) {
1903 $aName = "{$locationType[$locType[1]]}-address";
1904 $where = "`$aName`.state_province_id";
1907 $where = "civicrm_address.state_province_id";
1910 $states = CRM_Core_PseudoConstant
::stateProvince();
1911 if (is_numeric($value)) {
1912 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1913 $value = $states[(int ) $value];
1916 $intVal = CRM_Utils_Array
::key($value, $states);
1917 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1920 $this->_qill
[$grouping][] = ts('State') . " $op '$value'";
1923 $this->_qill
[$grouping][] = ts('State') . " ($lType) $op '$value'";
1926 elseif (!empty($field['pseudoconstant'])) {
1927 $this->optionValueQuery(
1928 $name, $op, $value, $grouping,
1929 CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', $field['name']),
1935 if ($name == 'gender_id') {
1936 self
::$_openedPanes[ts('Demographics')] = TRUE;
1939 elseif (substr($name, 0, 7) === 'country') {
1940 if (isset($locType[1]) && is_numeric($locType[1])) {
1942 $aName = "{$locationType[$locType[1]]}-address";
1943 $where = "`$aName`.country_id";
1946 $where = "civicrm_address.country_id";
1949 $countries = CRM_Core_PseudoConstant
::country();
1950 if (is_numeric($value)) {
1951 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1952 $value = $countries[(int ) $value];
1955 $intVal = CRM_Utils_Array
::key($value, $countries);
1956 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1960 $this->_qill
[$grouping][] = ts('Country') . " $op '$value'";
1963 $this->_qill
[$grouping][] = ts('Country') . " ($lType) $op '$value'";
1966 elseif (substr($name, 0, 6) === 'county') {
1967 if (isset($locType[1]) && is_numeric($locType[1])) {
1969 $aName = "{$locationType[$locType[1]]}-address";
1970 $where = "`$aName`.county_id";
1973 $where = "civicrm_address.county_id";
1976 $counties = CRM_Core_PseudoConstant
::county();
1977 if (is_numeric($value)) {
1978 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
1979 $value = $counties[(int ) $value];
1982 $intVal = CRM_Utils_Array
::key($value, $counties);
1983 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
1987 $this->_qill
[$grouping][] = ts('County') . " $op '$value'";
1990 $this->_qill
[$grouping][] = ts('County') . " ($lType) $op '$value'";
1993 elseif ($name === 'world_region') {
1994 $field['where'] = 'civicrm_worldregion.id';
1995 $this->optionValueQuery(
1996 $name, $op, $value, $grouping,
1997 CRM_Core_PseudoConstant
::worldRegion(),
2002 elseif ($name === 'birth_date') {
2003 $date = CRM_Utils_Date
::processDate($value);
2004 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
2007 $date = CRM_Utils_Date
::customFormat($date);
2008 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
2011 $this->_qill
[$grouping][] = "$field[title] $op";
2013 self
::$_openedPanes[ts('Demographics')] = TRUE;
2015 elseif ($name === 'deceased_date') {
2016 $date = CRM_Utils_Date
::processDate($value);
2017 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $date);
2019 $date = CRM_Utils_Date
::customFormat($date);
2020 $this->_qill
[$grouping][] = "$field[title] $op \"$date\"";
2023 $this->_qill
[$grouping][] = "$field[title] $op";
2025 self
::$_openedPanes[ts('Demographics')] = TRUE;
2027 elseif ($name === 'is_deceased') {
2028 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
2029 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2030 self
::$_openedPanes[ts('Demographics')] = TRUE;
2032 elseif ($name === 'contact_id') {
2033 if (is_int($value)) {
2034 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2035 $this->_qill
[$grouping][] = "$field[title] $op $value";
2038 elseif ($name === 'name') {
2039 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2041 $value = "%$value%";
2044 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2045 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2046 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2048 elseif ($name === 'current_employer') {
2049 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2051 $value = "%$value%";
2054 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
2055 $ceWhereClause = self
::buildClause($wc, $op,
2058 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2059 $this->_where
[$grouping][] = $ceWhereClause;
2060 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2062 elseif ($name === 'email_greeting') {
2063 $filterCondition = array('greeting_type' => 'email_greeting');
2064 $this->optionValueQuery(
2065 $name, $op, $value, $grouping,
2066 CRM_Core_PseudoConstant
::greeting($filterCondition),
2068 ts('Email Greeting')
2071 elseif ($name === 'postal_greeting') {
2072 $filterCondition = array('greeting_type' => 'postal_greeting');
2073 $this->optionValueQuery(
2074 $name, $op, $value, $grouping,
2075 CRM_Core_PseudoConstant
::greeting($filterCondition),
2077 ts('Postal Greeting')
2080 elseif ($name === 'addressee') {
2081 $filterCondition = array('greeting_type' => 'addressee');
2082 $this->optionValueQuery(
2083 $name, $op, $value, $grouping,
2084 CRM_Core_PseudoConstant
::greeting($filterCondition),
2089 elseif (substr($name, 0, 4) === 'url-') {
2090 $tName = 'civicrm_website';
2091 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2092 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2094 $value = "%$value%";
2098 $wc = 'civicrm_website.url';
2099 $this->_where
[$grouping][] = $d = self
::buildClause($wc, $op, $value);
2100 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2102 elseif ($name === 'contact_is_deleted') {
2103 $this->_where
[$grouping][] = self
::buildClause("contact_a.is_deleted", $op, $value);
2104 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2107 // sometime the value is an array, need to investigate and fix
2108 if (is_array($value)) {
2109 CRM_Core_Error
::fatal();
2112 if (!empty($field['where'])) {
2114 $value = $strtolower($value);
2117 $value = "%$value%";
2121 if (isset($locType[1]) &&
2122 is_numeric($locType[1])
2126 //get the location name
2127 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2129 $where = "`$tName`.$fldName";
2131 $this->_where
[$grouping][] = self
::buildClause("LOWER($where)", $op, $value);
2132 $this->_whereTables
[$tName] = $this->_tables
[$tName];
2133 $this->_qill
[$grouping][] = "$field[title] $op '$value'";
2136 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2137 if ($tableName == 'civicrm_contact') {
2138 $fieldName = "LOWER(contact_a.{$fieldName})";
2141 if ($op != 'IN' && !is_numeric($value)) {
2142 $fieldName = "LOWER({$field['where']})";
2145 $fieldName = "{$field['where']}";
2150 if (!empty($field['type'])) {
2151 $type = CRM_Utils_Type
::typeToString($field['type']);
2154 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2155 $this->_qill
[$grouping][] = "$field[title] $op $value";
2160 if ($setTables && isset($field['where'])) {
2161 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2162 if (isset($tableName)) {
2163 $this->_tables
[$tableName] = 1;
2164 $this->_whereTables
[$tableName] = 1;
2177 static function getLocationTableName(&$where, &$locType) {
2178 if (isset($locType[1]) && is_numeric($locType[1])) {
2179 list($tbName, $fldName) = explode(".", $where);
2181 //get the location name
2182 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2183 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2184 if (in_array($locType[0], $specialFields)) {
2185 //hack to fix / special handing for phone_ext
2186 if ($locType[0] == 'phone_ext') {
2187 $locType[0] = 'phone';
2189 if (isset($locType[2]) && $locType[2]) {
2190 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2193 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2196 elseif (in_array($locType[0],
2198 'address_name', 'street_address', 'supplemental_address_1', 'supplemental_address_2',
2199 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
2202 //fix for search by profile with address fields.
2203 $tName = "{$locationType[$locType[1]]}-address";
2205 elseif ($locType[0] == 'on_hold') {
2206 $tName = "{$locationType[$locType[1]]}-email";
2209 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2211 $tName = str_replace(' ', '_', $tName);
2212 return array($tName, $fldName);
2214 CRM_Core_Error
::fatal();
2218 * Given a result dao, extract the values and return that array
2220 * @param Object $dao
2222 * @return array values for this query
2224 function store($dao) {
2227 foreach ($this->_element
as $key => $dontCare) {
2228 if (property_exists($dao, $key)) {
2229 if (strpos($key, '-') !== FALSE) {
2230 $values = explode('-', $key);
2231 $lastElement = array_pop($values);
2233 $cnt = count($values);
2235 foreach ($values as $v) {
2236 if (!array_key_exists($v, $current)) {
2237 $current[$v] = array();
2239 //bad hack for im_provider
2240 if ($lastElement == 'provider_id') {
2241 if ($count < $cnt) {
2242 $current = &$current[$v];
2245 $lastElement = "{$v}_{$lastElement}";
2249 $current = &$current[$v];
2254 $current[$lastElement] = $dao->$key;
2257 $value[$key] = $dao->$key;
2265 * getter for tables array
2271 return $this->_tables
;
2277 function whereTables() {
2278 return $this->_whereTables
;
2282 * generate the where clause (used in match contacts and permissions)
2284 * @param array $params
2285 * @param array $fields
2286 * @param array $tables
2287 * @param $whereTables
2288 * @param boolean $strict
2294 static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2295 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2299 $tables = array_merge($query->tables(), $tables);
2300 $whereTables = array_merge($query->whereTables(), $whereTables);
2302 return $query->_whereClause
;
2306 * create the from clause
2308 * @param array $tables tables that need to be included in this from clause
2309 * if null, return mimimal from clause (i.e. civicrm_contact)
2310 * @param array $inner tables that should be inner-joined
2311 * @param array $right tables that should be right-joined
2313 * @param bool $primaryLocation
2316 * @return string the from clause
2320 static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2322 $from = ' FROM civicrm_contact contact_a';
2323 if (empty($tables)) {
2327 if (!empty($tables['civicrm_worldregion'])) {
2328 $tables = array_merge(array('civicrm_country' => 1), $tables);
2331 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2332 CRM_Utils_Array
::value('civicrm_county', $tables)
2333 ) && empty($tables['civicrm_address'])) {
2334 $tables = array_merge(array('civicrm_address' => 1),
2339 // add group_contact table if group table is present
2340 if (!empty($tables['civicrm_group']) && empty($tables['civicrm_group_contact'])) {
2341 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
2344 // add group_contact and group table is subscription history is present
2345 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2346 $tables = array_merge(array(
2347 'civicrm_group' => 1,
2348 'civicrm_group_contact' => 1,
2354 // to handle table dependencies of components
2355 CRM_Core_Component
::tableNames($tables);
2356 // to handle table dependencies of hook injected tables
2357 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2359 //format the table list according to the weight
2360 $info = CRM_Core_TableHierarchy
::info();
2362 foreach ($tables as $key => $value) {
2364 if (strpos($key, '-') !== FALSE) {
2365 $keyArray = explode('-', $key);
2366 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2368 elseif (strpos($key, '_') !== FALSE) {
2369 $keyArray = explode('_', $key);
2370 if (is_numeric(array_pop($keyArray))) {
2371 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2374 $k = CRM_Utils_Array
::value($key, $info, 99);
2378 $k = CRM_Utils_Array
::value($key, $info, 99);
2380 $tempTable[$k . ".$key"] = $key;
2383 $newTables = array();
2384 foreach ($tempTable as $key) {
2385 $newTables[$key] = $tables[$key];
2388 $tables = $newTables;
2390 foreach ($tables as $name => $value) {
2395 if (!empty($inner[$name])) {
2398 elseif (!empty($right[$name])) {
2406 // if there is already a join statement in value, use value itself
2407 if (strpos($value, 'JOIN')) {
2408 $from .= " $value ";
2411 $from .= " $side JOIN $name ON ( $value ) ";
2416 case 'civicrm_address':
2417 if ($primaryLocation) {
2418 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2421 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2425 case 'civicrm_phone':
2426 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2429 case 'civicrm_email':
2430 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2434 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2438 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2439 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2440 $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)";
2443 case 'civicrm_openid':
2444 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2447 case 'civicrm_worldregion':
2448 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2449 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2452 case 'civicrm_location_type':
2453 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2456 case 'civicrm_group':
2457 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2460 case 'civicrm_group_contact':
2461 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2464 case 'civicrm_activity':
2465 case 'civicrm_activity_tag':
2466 case 'activity_type':
2467 case 'activity_status':
2469 case 'civicrm_activity_contact':
2470 case 'source_contact':
2471 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2474 case 'civicrm_entity_tag':
2475 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2476 civicrm_entity_tag.entity_id = contact_a.id ) ";
2479 case 'civicrm_note':
2480 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2481 contact_a.id = civicrm_note.entity_id ) ";
2484 case 'civicrm_subscription_history':
2485 $from .= " $side JOIN civicrm_subscription_history
2486 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2487 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2490 case 'civicrm_relationship':
2491 if (self
::$_relType == 'reciprocal') {
2492 if(self
::$_relationshipTempTable) {
2493 // we have a temptable to join on
2494 $tbl = self
::$_relationshipTempTable;
2495 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2498 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2499 $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)";
2502 elseif (self
::$_relType == 'b') {
2503 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2504 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2507 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2508 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2513 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2514 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2518 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2521 case 'civicrm_grant':
2522 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2525 case 'civicrm_website':
2526 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2530 $from .= CRM_Core_Component
::from($name, $mode, $side);
2531 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2541 * WHERE / QILL clause for deleted_contacts
2547 function deletedContacts($values) {
2548 list($_, $_, $value, $grouping, $_) = $values;
2550 // *prepend* to the relevant grouping as this is quite an important factor
2551 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2556 * where / qill clause for contact_type
2563 function contactType(&$values) {
2564 list($name, $op, $value, $grouping, $wildcard) = $values;
2566 $subTypes = array();
2569 // account for search builder mapping multiple values
2570 if (!is_array($value)) {
2571 $values = self
::parseSearchBuilderString($value, 'String');
2572 if (is_array($values)) {
2573 $value = array_flip($values);
2577 if (is_array($value)) {
2578 foreach ($value as $k => $v) {
2583 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2584 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2587 if (!empty($subType)) {
2588 $subTypes[$subType] = 1;
2590 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2595 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2596 $contactType = $contactTypeANDSubType[0];
2597 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2598 if (!empty($subType)) {
2599 $subTypes[$subType] = 1;
2601 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2605 if (!empty($clause)) {
2606 if ($op == 'IN' ||
$op == 'NOT IN') {
2607 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2611 $type = array_pop($clause);
2612 $this->_where
[$grouping][] = "contact_a.contact_type $op $type";
2615 $this->_qill
[$grouping][] = ts('Contact Type') . ' - ' . implode(' ' . ts('or') . ' ', $quill);
2617 if (!empty($subTypes)) {
2618 $this->includeContactSubTypes($subTypes, $grouping);
2624 * where / qill clause for contact_sub_type
2631 function contactSubType(&$values) {
2632 list($name, $op, $value, $grouping, $wildcard) = $values;
2633 $this->includeContactSubTypes($value, $grouping);
2640 function includeContactSubTypes($value, $grouping) {
2643 $alias = "contact_a.contact_sub_type";
2645 if (is_array($value)) {
2646 foreach ($value as $k => $v) {
2648 $clause[$k] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($k, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2653 $clause[$value] = "($alias like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2656 if (!empty($clause)) {
2657 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2658 $this->_qill
[$grouping][] = ts('Contact Subtype') . ' - ' . implode(' ' . ts('or') . ' ', array_keys($clause));
2663 * where / qill clause for groups
2670 function group(&$values) {
2671 list($name, $op, $value, $grouping, $wildcard) = $values;
2673 if (count($value) > 1) {
2674 $this->_useDistinct
= TRUE;
2677 $groupNames = CRM_Core_PseudoConstant
::group();
2678 $groupIds = implode(',', array_keys($value));
2681 foreach ($value as $id => $dontCare) {
2682 if (array_key_exists($id, $groupNames) && $dontCare) {
2683 $names[] = $groupNames[$id];
2689 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2691 is_array($gcsValues[2])
2693 foreach ($gcsValues[2] as $k => $v) {
2695 if ($k == 'Added') {
2698 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2703 $statii[] = '"Added"';
2708 if (count($value) == 1 &&
2709 count($statii) == 1 &&
2710 $statii[0] == '"Added"'
2712 // check if smart group, if so we can get rid of that one additional
2714 $groupIDs = array_keys($value);
2716 if (!empty($groupIDs[0]) &&
2717 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group',
2727 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2728 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON ( contact_a.id = {$gcTable}.contact_id AND {$gcTable}.group_id $op ( $groupIds ) )";
2731 $qill = ts('Contacts %1', array(1 => $op));
2732 $qill .= ' ' . implode(' ' . ts('or') . ' ', $names);
2734 $groupClause = NULL;
2737 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2738 if (!empty($statii)) {
2739 $groupClause .= " AND {$gcTable}.status IN (" . implode(', ', $statii) . ")";
2740 $qill .= " " . ts('AND') . " " . ts('Group Status') . ' - ' . implode(' ' . ts('or') . ' ', $statii);
2745 $ssClause = $this->savedSearch($values);
2748 $groupClause = "( ( $groupClause ) OR ( $ssClause ) )";
2751 $groupClause = $ssClause;
2756 $this->_where
[$grouping][] = $groupClause;
2757 $this->_qill
[$grouping][] = $qill;
2760 * Function translates selection of group type into a list of groups
2767 function getGroupsFromTypeCriteria($value){
2768 $groupIds = array();
2769 foreach ($value as $groupTypeValue) {
2770 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2771 $groupIds = ($groupIds +
$groupList);
2777 * where / qill clause for smart groups
2781 * @return string|NULL
2784 function savedSearch(&$values) {
2785 list($name, $op, $value, $grouping, $wildcard) = $values;
2786 return $this->addGroupContactCache(array_keys($value));
2790 * @param array $groups
2791 * @param string $tableAlias
2792 * @param string $joinTable
2794 * @return null|string
2796 function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
2797 $config = CRM_Core_Config
::singleton();
2799 // Find all the groups that are part of a saved search.
2800 $groupIDs = implode(',', $groups);
2801 if (empty($groupIDs)) {
2806 SELECT id, cache_date, saved_search_id, children
2808 WHERE id IN ( $groupIDs )
2809 AND ( saved_search_id != 0
2810 OR saved_search_id IS NOT NULL
2811 OR children IS NOT NULL )
2814 $group = CRM_Core_DAO
::executeQuery($sql);
2815 $groupsFiltered = array();
2817 while ($group->fetch()) {
2818 $groupsFiltered[] = $group->id
;
2820 $this->_useDistinct
= TRUE;
2822 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
2823 CRM_Contact_BAO_GroupContactCache
::load($group);
2827 if (count($groupsFiltered)) {
2828 $groupIDsFiltered = implode(',', $groupsFiltered);
2830 if ($tableAlias == NULL) {
2831 $tableAlias = "civicrm_group_contact_cache_{$groupIDsFiltered}";
2834 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache `{$tableAlias}` ON {$joinTable}.id = `{$tableAlias}`.contact_id ";
2836 return "`{$tableAlias}`.group_id IN (" . $groupIDsFiltered . ")";
2843 * where / qill clause for cms users
2850 function ufUser(&$values) {
2851 list($name, $op, $value, $grouping, $wildcard) = $values;
2854 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2856 $this->_qill
[$grouping][] = ts('CMS User');
2858 elseif ($value == 0) {
2859 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2861 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2862 $this->_qill
[$grouping][] = ts('Not a CMS User');
2867 * all tag search specific
2874 function tagSearch(&$values) {
2875 list($name, $op, $value, $grouping, $wildcard) = $values;
2878 $value = "%{$value}%";
2881 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2882 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2884 $etTable = "`civicrm_entity_tag-" . $value . "`";
2885 $tTable = "`civicrm_tag-" . $value . "`";
2887 if ($useAllTagTypes[2]) {
2888 $this->_tables
[$etTable] =
2889 $this->_whereTables
[$etTable] =
2890 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
2891 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
2893 // search tag in cases
2894 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2895 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
2896 $this->_tables
[$etCaseTable] =
2897 $this->_whereTables
[$etCaseTable] =
2898 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2899 LEFT JOIN civicrm_case
2900 ON (civicrm_case_contact.case_id = civicrm_case.id
2901 AND civicrm_case.is_deleted = 0 )
2902 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
2903 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
2904 // search tag in activities
2905 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2906 $tActTable = "`civicrm_act_tag-" . $value . "`";
2907 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2908 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2910 $this->_tables
[$etActTable] =
2911 $this->_whereTables
[$etActTable] =
2912 " LEFT JOIN civicrm_activity_contact
2913 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
2914 LEFT JOIN civicrm_activity
2915 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
2916 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2917 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
2918 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
2920 $this->_where
[$grouping][] = "({$tTable}.name $op '". $value . "' OR {$tCaseTable}.name $op '". $value . "' OR {$tActTable}.name $op '". $value . "')";
2921 $this->_qill
[$grouping][] = ts('Tag %1 %2 ', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
2923 $etTable = "`civicrm_entity_tag-" . $value . "`";
2924 $tTable = "`civicrm_tag-" . $value . "`";
2925 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
2926 {$etTable}.entity_table = 'civicrm_contact' )
2927 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
2929 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
2930 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
2935 * where / qill clause for tag
2942 function tag(&$values) {
2943 list($name, $op, $value, $grouping, $wildcard) = $values;
2945 $tagNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
2946 if (is_array($value)) {
2947 if (count($value) > 1) {
2948 $this->_useDistinct
= TRUE;
2950 foreach ($value as $id => $dontCare) {
2951 $names[] = CRM_Utils_Array
::value($id, $tagNames);
2953 $names = implode(' ' . ts('or') . ' ', $names);
2954 $value = implode(',', array_keys($value));
2957 $names = CRM_Utils_Array
::value($value, $tagNames);
2961 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2962 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2964 $etTable = "`civicrm_entity_tag-" . $value . "`";
2966 if ($useAllTagTypes[2]) {
2967 $this->_tables
[$etTable] =
2968 $this->_whereTables
[$etTable] =
2969 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2971 // search tag in cases
2972 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2973 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2974 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2976 $this->_tables
[$etCaseTable] =
2977 $this->_whereTables
[$etCaseTable] =
2978 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2979 LEFT JOIN civicrm_case
2980 ON (civicrm_case_contact.case_id = civicrm_case.id
2981 AND civicrm_case.is_deleted = 0 )
2982 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
2983 // search tag in activities
2984 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2985 $this->_tables
[$etActTable] =
2986 $this->_whereTables
[$etActTable] =
2987 " LEFT JOIN civicrm_activity_contact
2988 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
2989 LEFT JOIN civicrm_activity
2990 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
2991 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2992 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
2995 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
2996 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
2999 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (". $value . ") OR {$etCaseTable}.tag_id $op (". $value . ") OR {$etActTable}.tag_id $op (". $value . "))";
3001 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
3003 $this->_tables
[$etTable] =
3004 $this->_whereTables
[$etTable] =
3005 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3008 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3009 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3010 $op = str_replace('EMPTY', 'NULL', $op);
3011 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3014 $this->_where
[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
3016 $this->_qill
[$grouping][] = ts('Tagged %1', array( 1 => $op)) . ' ' . $names;
3022 * where/qill clause for notes
3029 function notes(&$values) {
3030 list($name, $op, $value, $grouping, $wildcard) = $values;
3032 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3033 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3034 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3036 $this->_useDistinct
= TRUE;
3038 $this->_tables
['civicrm_note'] =
3039 $this->_whereTables
['civicrm_note'] =
3040 " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3042 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3044 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3045 if ($wildcard ||
$op == 'LIKE') {
3046 if (strpos($value, '%') === FALSE) {
3047 $value = "%$value%";
3051 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3057 if ( $noteOption %
2 == 0 ) {
3058 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3059 $label = ts('Note: Body Only');
3061 if ( $noteOption %
3 == 0 ) {
3062 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3063 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3065 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3066 $this->_qill
[$grouping][] = $label . " $op - '$n'";
3076 function nameNullOrEmptyOp($name, $op, $grouping) {
3080 $this->_where
[$grouping][] = "contact_a.$name $op";
3081 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3085 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3086 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3089 case 'IS NOT EMPTY':
3090 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3091 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3100 * where / qill clause for sort_name
3107 function sortName(&$values) {
3108 list($name, $op, $value, $grouping, $wildcard) = $values;
3110 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3111 if ( $this->nameNullOrEmptyOp( $name, $op, $grouping ) ) {
3116 $name = trim($value);
3122 $config = CRM_Core_Config
::singleton();
3126 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3129 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3130 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3132 if (substr($name, 0, 1) == '"' &&
3133 substr($name, -1, 1) == '"'
3135 //If name is encased in double quotes, the value should be taken to be the string in entirety and the
3136 $value = substr($name, 1, -1);
3137 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
3138 $wc = ($newName == 'sort_name') ?
'LOWER(contact_a.sort_name)' : 'LOWER(contact_a.display_name)';
3139 $sub[] = " ( $wc = '$value' ) ";
3140 if ($config->includeEmailInName
) {
3141 $sub[] = " ( civicrm_email.email = '$value' ) ";
3144 elseif (strpos($name, ',') !== FALSE) {
3145 // if we have a comma in the string, search for the entire string
3146 $value = $strtolower(CRM_Core_DAO
::escapeString($name));
3148 if ($config->includeWildCardInName
) {
3149 $value = "'%$value%'";
3152 $value = "'$value%'";
3157 $value = "'$value'";
3159 if ($newName == 'sort_name') {
3160 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3163 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3165 $sub[] = " ( $wc $op $value )";
3166 if ($config->includeNickNameInName
) {
3167 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3168 $sub[] = " ( $wc $op $value )";
3170 if ($config->includeEmailInName
) {
3171 $sub[] = " ( civicrm_email.email $op $value ) ";
3175 // the string should be treated as a series of keywords to be matched with match ANY OR
3176 // match ALL depending on Civi config settings (see CiviAdmin)
3178 // The Civi configuration setting can be overridden if the string *starts* with the case
3179 // insenstive strings 'AND:' or 'OR:'TO THINK ABOUT: what happens when someone searches
3180 // for the following "AND: 'a string in quotes'"? - probably nothing - it would make the
3181 // AND OR variable reduntant because there is only one search string?
3183 // Check to see if the $subGlue is overridden in the search text
3184 if (strtolower(substr($name, 0, 4)) == 'and:') {
3185 $name = substr($name, 4);
3188 if (strtolower(substr($name, 0, 3)) == 'or:') {
3189 $name = substr($name, 3);
3193 $firstChar = substr($name, 0, 1);
3194 $lastChar = substr($name, -1, 1);
3195 $quotes = array("'", '"');
3196 if ((strlen($name) > 2) && in_array($firstChar, $quotes) &&
3197 in_array($lastChar, $quotes)
3199 $name = substr($name, 1);
3200 $name = substr($name, 0, -1);
3201 $pieces = array($name);
3204 $pieces = explode(' ', $name);
3206 foreach ($pieces as $piece) {
3207 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($piece)));
3208 if (strlen($value)) {
3209 // Added If as a sanitization - without it, when you do an OR search, any string with
3210 // double spaces (i.e. " ") or that has a space after the keyword (e.g. "OR: ") will
3211 // return all contacts because it will include a condition similar to "OR contact
3212 // name LIKE '%'". It might be better to replace this with array_filter.
3213 $fieldsub = array();
3215 if ($config->includeWildCardInName
) {
3216 $value = "'%$value%'";
3219 $value = "'$value%'";
3224 $value = "'$value'";
3226 if ($newName == 'sort_name') {
3227 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3230 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3232 $fieldsub[] = " ( $wc $op $value )";
3233 if ($config->includeNickNameInName
) {
3234 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3235 $fieldsub[] = " ( $wc $op $value )";
3237 if ($config->includeEmailInName
) {
3238 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3240 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3241 // I seperated the glueing in two. The first stage should always be OR because we are searching for matches in *ANY* of these fields
3246 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3248 $this->_where
[$grouping][] = $sub;
3249 if ($config->includeEmailInName
) {
3250 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3251 $this->_qill
[$grouping][] = ts('Name or Email ') . "$op - '$name'";
3254 $this->_qill
[$grouping][] = ts('Name like') . " - '$name'";
3259 * where / qill clause for email
3266 function email(&$values) {
3267 list($name, $op, $value, $grouping, $wildcard) = $values;
3271 $config = CRM_Core_Config
::singleton();
3273 if (substr($n, 0, 1) == '"' &&
3274 substr($n, -1, 1) == '"'
3276 $n = substr($n, 1, -1);
3277 $value = strtolower(CRM_Core_DAO
::escapeString($n));
3278 $value = "'$value'";
3282 $value = strtolower($n);
3284 if (strpos($value, '%') === FALSE) {
3285 $value = "%{$value}%";
3290 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3291 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3294 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3295 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3298 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3302 * where / qill clause for phone number
3309 function phone_numeric(&$values) {
3310 list($name, $op, $value, $grouping, $wildcard) = $values;
3311 // Strip non-numeric characters; allow wildcards
3312 $number = preg_replace('/[^\d%]/', '', $value);
3314 if ( strpos($number, '%') === FALSE ) {
3315 $number = "%$number%";
3318 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3319 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3320 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3325 * where / qill clause for phone type/location
3332 function phone_option_group($values) {
3333 list($name, $op, $value, $grouping, $wildcard) = $values;
3334 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3335 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3336 $optionName = $options[$value];
3337 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3338 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3339 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3343 * where / qill clause for street_address
3350 function street_address(&$values) {
3351 list($name, $op, $value, $grouping, $wildcard) = $values;
3360 $value = strtolower($n);
3361 if (strpos($value, '%') === FALSE) {
3362 // only add wild card if not there
3363 $value = "%{$value}%";
3366 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3367 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3370 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3371 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3374 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3378 * where / qill clause for street_unit
3385 function street_number(&$values) {
3386 list($name, $op, $value, $grouping, $wildcard) = $values;
3394 if (strtolower($n) == 'odd') {
3395 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3396 $this->_qill
[$grouping][] = ts('Street Number is odd');
3398 elseif (strtolower($n) == 'even') {
3399 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3400 $this->_qill
[$grouping][] = ts('Street Number is even');
3403 $value = strtolower($n);
3405 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3406 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3409 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3413 * where / qill clause for sorting by character
3420 function sortByCharacter(&$values) {
3421 list($name, $op, $value, $grouping, $wildcard) = $values;
3423 $name = trim($value);
3424 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3425 $this->_where
[$grouping][] = $cond;
3426 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3430 * where / qill clause for including contact ids
3435 function includeContactIDs() {
3436 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3440 $contactIds = array();
3441 foreach ($this->_params
as $id => $values) {
3442 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3443 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3446 if (!empty($contactIds)) {
3447 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3452 * where / qill clause for postal code
3459 function postalCode(&$values) {
3460 // skip if the fields dont have anything to do with postal_code
3461 if (empty($this->_fields
['postal_code'])) {
3465 list($name, $op, $value, $grouping, $wildcard) = $values;
3467 // Handle numeric postal code range searches properly by casting the column as numeric
3468 if (is_numeric($value)) {
3469 $field = 'ROUND(civicrm_address.postal_code)';
3470 $val = CRM_Utils_Type
::escape($value, 'Integer');
3473 $field = 'civicrm_address.postal_code';
3474 $val = CRM_Utils_Type
::escape($value, 'String');
3477 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3479 if ($name == 'postal_code') {
3480 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3481 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3483 elseif ($name == 'postal_code_low') {
3484 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3485 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3487 elseif ($name == 'postal_code_high') {
3488 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3489 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3494 * where / qill clause for location type
3497 * @param null $status
3502 function locationType(&$values, $status = NULL) {
3503 list($name, $op, $value, $grouping, $wildcard) = $values;
3505 if (is_array($value)) {
3506 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', array_keys($value)) . ')';
3507 $this->_tables
['civicrm_address'] = 1;
3508 $this->_whereTables
['civicrm_address'] = 1;
3510 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3512 foreach (array_keys($value) as $id) {
3513 $names[] = $locationType[$id];
3516 $this->_primaryLocation
= FALSE;
3519 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3522 return implode(' ' . ts('or') . ' ', $names);
3529 * @param bool $fromStateProvince
3533 function country(&$values, $fromStateProvince = TRUE) {
3534 list($name, $op, $value, $grouping, $wildcard) = $values;
3536 if (!$fromStateProvince) {
3537 $stateValues = $this->getWhereValues('state_province', $grouping);
3538 if (!empty($stateValues)) {
3539 // return back to caller if there are state province values
3540 // since that handles this case
3545 $countryClause = $countryQill = NULL;
3551 $this->_tables
['civicrm_address'] = 1;
3552 $this->_whereTables
['civicrm_address'] = 1;
3554 $countries = CRM_Core_PseudoConstant
::country();
3555 if (is_numeric($value)) {
3556 $countryClause = self
::buildClause(
3557 'civicrm_address.country_id',
3562 $countryName = $countries[(int ) $value];
3566 $intValues = self
::parseSearchBuilderString($value);
3567 if ($intValues && ($op == 'IN' ||
$op == 'NOT IN')) {
3568 $countryClause = self
::buildClause(
3569 'civicrm_address.country_id',
3574 $countryNames = array();
3575 foreach ($intValues as $v) {
3576 $countryNames[] = $countries[$v];
3578 $countryName = implode(',', $countryNames);
3581 $countries = CRM_Core_PseudoConstant
::country();
3582 $intVal = CRM_Utils_Array
::key($value, $countries);
3583 $countryClause = self
::buildClause(
3584 'civicrm_address.country_id',
3589 $countryName = $value;
3592 $countryQill = ts('Country') . " {$op} '$countryName'";
3594 if (!$fromStateProvince) {
3595 $this->_where
[$grouping][] = $countryClause;
3596 $this->_qill
[$grouping][] = $countryQill;
3600 if ($fromStateProvince) {
3601 if (!empty($countryClause)) {
3604 " ...AND... " . $countryQill,
3608 return array(NULL, NULL);
3614 * where / qill clause for county (if present)
3617 * @param null $status
3622 function county(&$values, $status = null) {
3623 list($name, $op, $value, $grouping, $wildcard) = $values;
3625 if (! is_array($value)) {
3626 // force the county to be an array
3627 $value = array($value);
3630 // check if the values are ids OR names of the counties
3631 $inputFormat = 'id';
3632 foreach ($value as $v) {
3633 if (!is_numeric($v)) {
3634 $inputFormat = 'name';
3642 else if ($op == '!=') {
3646 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3647 $op = str_replace('EMPTY', 'NULL', $op);
3650 if (in_array( $op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3651 $clause = "civicrm_address.county_id $op";
3653 elseif ($inputFormat == 'id') {
3654 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3656 $county = CRM_Core_PseudoConstant
::county();
3657 foreach ($value as $id) {
3658 $names[] = CRM_Utils_Array
::value($id, $county);
3662 $inputClause = array();
3663 $county = CRM_Core_PseudoConstant
::county();
3664 foreach ($value as $name) {
3665 $name = trim($name);
3666 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3668 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3671 $this->_tables
['civicrm_address'] = 1;
3672 $this->_whereTables
['civicrm_address'] = 1;
3674 $this->_where
[$grouping][] = $clause;
3676 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3678 return implode(' ' . ts('or') . ' ', $names);
3683 * where / qill clause for state/province AND country (if present)
3686 * @param null $status
3691 function stateProvince(&$values, $status = NULL) {
3692 list($name, $op, $value, $grouping, $wildcard) = $values;
3694 // quick escape for IS NULL
3695 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3698 else if (!is_array($value)) {
3699 // force the state to be an array
3700 // check if its in the mapper format!
3701 $values = self
::parseSearchBuilderString($value);
3702 if (is_array($values)) {
3706 $value = array($value);
3710 // check if the values are ids OR names of the states
3711 $inputFormat = 'id';
3713 foreach ($value as $v) {
3714 if (!is_numeric($v)) {
3715 $inputFormat = 'name';
3725 else if ($op == '!=') {
3729 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3730 $op = str_replace('EMPTY', 'NULL', $op);
3732 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3733 $stateClause = "civicrm_address.state_province_id $op";
3735 else if ($inputFormat == 'id') {
3736 if ($op != 'NOT IN') {
3739 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
3741 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3742 foreach ($value as $id) {
3743 $names[] = CRM_Utils_Array
::value($id, $stateProvince);
3747 $inputClause = array();
3748 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3749 foreach ($value as $name) {
3750 $name = trim($name);
3751 $inputClause[] = CRM_Utils_Array
::key($name, $stateProvince);
3753 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
3756 $this->_tables
['civicrm_address'] = 1;
3757 $this->_whereTables
['civicrm_address'] = 1;
3759 $countryValues = $this->getWhereValues('country', $grouping);
3760 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3762 if ($countryClause) {
3763 $clause = "( $stateClause AND $countryClause )";
3766 $clause = $stateClause;
3769 $this->_where
[$grouping][] = $clause;
3771 $this->_qill
[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3774 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
3779 * where / qill clause for change log
3786 function changeLog(&$values) {
3787 list($name, $op, $value, $grouping, $wildcard) = $values;
3789 $targetName = $this->getWhereValues('changed_by', $grouping);
3794 $name = trim($targetName[2]);
3795 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3796 $name = $targetName[4] ?
"%$name%" : $name;
3797 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3798 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3799 $this->_qill
[$grouping][] = ts('Modified by') . ": $name";
3805 function modifiedDates($values) {
3806 $this->_useDistinct
= TRUE;
3808 // CRM-11281, default to added date if not set
3809 $fieldTitle = ts('Added Date');
3810 $fieldName = 'created_date';
3811 foreach (array_keys($this->_params
) as $id) {
3812 if ($this->_params
[$id][0] == 'log_date') {
3813 if ($this->_params
[$id][2] == 2) {
3814 $fieldTitle = ts('Modified Date');
3815 $fieldName = 'modified_date';
3821 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3823 self
::$_openedPanes[ts('Change Log')] = TRUE;
3829 function demographics(&$values) {
3830 list($name, $op, $value, $grouping, $wildcard) = $values;
3832 if (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3834 $this->dateQueryBuilder($values,
3835 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3838 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3840 $this->dateQueryBuilder($values,
3841 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3845 self
::$_openedPanes[ts('Demographics')] = TRUE;
3851 function privacy(&$values) {
3852 list($name, $op, $value, $grouping, $wildcard) = $values;
3853 //fixed for profile search listing CRM-4633
3854 if (strpbrk($value, "[")) {
3855 $value = "'{$value}'";
3857 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3860 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3862 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3863 $title = $field ?
$field['title'] : $name;
3864 $this->_qill
[$grouping][] = "$title $op $value";
3870 function privacyOptions($values) {
3871 list($name, $op, $value, $grouping, $wildcard) = $values;
3873 if (empty($value) ||
!is_array($value)) {
3877 // get the operator and toggle values
3878 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3881 strtolower($opValues[2] == 'AND')
3886 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3888 if ($toggleValues &&
3889 $toggleValues[2] == 2
3896 foreach ($value as $dontCare => $pOption) {
3897 $clauses[] = " ( contact_a.{$pOption} $compareOP 1 ) ";
3898 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3899 $title = $field ?
$field['title'] : $pOption;
3900 $qill[] = " $title $compareOP 1 ";
3903 $this->_where
[$grouping][] = '( ' . implode($operator, $clauses) . ' )';
3904 $this->_qill
[$grouping][] = implode($operator, $qill);
3910 function preferredCommunication(&$values) {
3911 list($name, $op, $value, $grouping, $wildcard) = $values;
3914 if (in_array($op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3917 elseif (!is_array($value)) {
3919 $value = trim($value, ' ()');
3920 if (strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
3921 $v = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
3924 $v = explode(",", $value);
3927 foreach ($v as $item) {
3934 foreach ($value as $key => $checked) {
3941 $commPref = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
3943 $sqlValue = array();
3944 $showValue = array();
3945 $sql = "contact_a.preferred_communication_method";
3946 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3947 $sqlValue[] = "{$sql} {$op}";
3950 foreach ($pref as $val) {
3951 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $val . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' ) ";
3952 $showValue[] = $commPref[$val];
3955 $this->_where
[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
3956 $this->_qill
[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
3960 * where / qill clause for relationship
3967 function relationship(&$values) {
3968 list($name, $op, $value, $grouping, $wildcard) = $values;
3969 if($this->_relationshipValuesAdded
){
3972 // also get values array for relation_target_name
3973 // for relatinship search we always do wildcard
3974 $targetName = $this->getWhereValues('relation_target_name', $grouping);
3975 $relStatus = $this->getWhereValues('relation_status', $grouping);
3976 $relPermission = $this->getWhereValues('relation_permission', $grouping);
3977 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
3979 $nameClause = $name = NULL;
3981 $name = trim($targetName[2]);
3982 if (substr($name, 0, 1) == '"' &&
3983 substr($name, -1, 1) == '"'
3985 $name = substr($name, 1, -1);
3986 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3987 $nameClause = "= '$name'";
3990 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3991 $nameClause = "LIKE '%{$name}%'";
3995 $rel = explode('_', $value);
3997 self
::$_relType = $rel[1];
3998 $params = array('id' => $rel[0]);
3999 $rTypeValues = array();
4000 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
4001 if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
4002 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4003 //@todo unless we are dealing with a target group
4004 self
::$_relType = 'reciprocal';
4006 // if we are creating a temp table we build our own where for the relationship table
4007 $relationshipTempTable = NULL;
4008 if(self
::$_relType == 'reciprocal' && empty($targetGroup)) {
4010 self
::$_relationshipTempTable =
4011 $relationshipTempTable =
4012 CRM_Core_DAO
::createTempTableName( 'civicrm_rel');
4014 $where[$grouping][] = " sort_name $nameClause ";
4018 $where = &$this->_where
;
4020 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4025 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
4026 $relTypeOrg = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
4027 $relTypeHou = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Household');
4028 $allRelationshipType = array();
4029 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
4030 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
4032 if ($nameClause ||
!$targetGroup) {
4033 $this->_qill
[$grouping][] = "$allRelationshipType[$value] $name";
4037 //check to see if the target contact is in specified group
4039 //add contacts from static groups
4040 $this->_tables
['civicrm_relationship_group_contact'] =
4041 $this->_whereTables
['civicrm_relationship_group_contact'] =
4042 " 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'";
4044 "( civicrm_relationship_group_contact.group_id IN (" .
4045 implode(",", $targetGroup[2]) . ") ) ";
4047 //add contacts from saved searches
4048 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
4050 //set the group where clause
4052 $groupWhere[] = "( " . $ssWhere . " )";
4054 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4056 //Get the names of the target groups for the qill
4057 $groupNames = CRM_Core_PseudoConstant
::group();
4058 $qillNames = array();
4059 foreach ($targetGroup[2] as $groupId) {
4060 if (array_key_exists($groupId, $groupNames)) {
4061 $qillNames[] = $groupNames[$groupId];
4064 $this->_qill
[$grouping][] = "$allRelationshipType[$value] ( " . implode(", ", $qillNames) . " )";
4067 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4068 $today = date('Ymd');
4069 //check for active, inactive and all relation status
4070 if ($relStatus[2] == 0) {
4071 $where[$grouping][] = "(
4072 civicrm_relationship.is_active = 1 AND
4073 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4074 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4076 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4078 elseif ($relStatus[2] == 1) {
4079 $where[$grouping][] = "(
4080 civicrm_relationship.is_active = 0 OR
4081 civicrm_relationship.end_date < {$today} OR
4082 civicrm_relationship.start_date > {$today}
4084 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4087 //check for permissioned, non-permissioned and all permissioned relations
4088 if ($relPermission[2] == 1) {
4089 $this->_where
[$grouping][] = "(
4090 civicrm_relationship.is_permission_a_b = 1
4092 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4093 } elseif ($relPermission[2] == 2) {
4094 //non-allowed permission relationship.
4095 $this->_where
[$grouping][] = "(
4096 civicrm_relationship.is_permission_a_b = 0
4098 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4101 $this->addRelationshipDateClauses($grouping, $where);
4102 if(!empty($rType) && isset($rType->id
)){
4103 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
4105 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4106 $this->_useDistinct
= TRUE;
4107 $this->_relationshipValuesAdded
= TRUE;
4108 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4110 // @todo creating a temp table could be expanded to group filter
4111 // as even creating a temp table of all relationships is much much more efficient than
4112 // an OR in the join
4113 if($relationshipTempTable) {
4114 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4116 CREATE TEMPORARY TABLE {$relationshipTempTable}
4117 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4118 FROM civicrm_relationship
4119 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4122 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4123 FROM civicrm_relationship
4124 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4127 CRM_Core_DAO
::executeQuery($sql);
4132 * Add start & end date criteria in
4133 * @param string $grouping
4134 * @param array $where = array to add where clauses to, in case you are generating a temp table
4135 * not the main query.
4137 function addRelationshipDateClauses($grouping, &$where){
4138 $dateValues = array();
4144 foreach ($dateTypes as $dateField){
4145 $dateValueLow = $this->getWhereValues('relation_'. $dateField .'_low', $grouping);
4146 $dateValueHigh= $this->getWhereValues('relation_'. $dateField .'_high', $grouping);
4147 if(!empty($dateValueLow)){
4148 $date = date('Ymd', strtotime($dateValueLow[2]));
4149 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4150 $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);
4152 if(!empty($dateValueHigh)){
4153 $date = date('Ymd', strtotime($dateValueHigh[2]));
4154 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4155 $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);
4161 * default set of return properties
4165 * @return array derault return properties
4168 static function &defaultReturnProperties($mode = 1) {
4169 if (!isset(self
::$_defaultReturnProperties)) {
4170 self
::$_defaultReturnProperties = array();
4173 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4174 // add activity return properties
4175 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4176 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4179 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4182 if (empty(self
::$_defaultReturnProperties[$mode])) {
4183 self
::$_defaultReturnProperties[$mode] = array(
4186 'legal_identifier' => 1,
4187 'external_identifier' => 1,
4188 'contact_type' => 1,
4189 'contact_sub_type' => 1,
4191 'display_name' => 1,
4192 'preferred_mail_format' => 1,
4199 'formal_title' => 1,
4200 'communication_style_id' => 1,
4203 'street_address' => 1,
4204 'supplemental_address_1' => 1,
4205 'supplemental_address_2' => 1,
4208 'postal_code_suffix' => 1,
4209 'state_province' => 1,
4211 'world_region' => 1,
4218 'household_name' => 1,
4219 'organization_name' => 1,
4220 'deceased_date' => 1,
4225 'current_employer' => 1,
4226 // FIXME: should we use defaultHierReturnProperties() for the below?
4227 'do_not_email' => 1,
4230 'do_not_phone' => 1,
4231 'do_not_trade' => 1,
4233 'contact_is_deleted' => 1,
4234 'preferred_communication_method' => 1,
4235 'preferred_language' => 1,
4239 return self
::$_defaultReturnProperties[$mode];
4243 * get primary condition for a sql clause
4247 * @return string|NULL
4250 static function getPrimaryCondition($value) {
4251 if (is_numeric($value)) {
4252 $value = (int ) $value;
4253 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4259 * wrapper for a simple search query
4261 * @param array $params
4262 * @param array $returnProperties
4263 * @param bool $count
4268 static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4269 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4270 list($select, $from, $where, $having) = $query->query();
4272 return "$select $from $where $having";
4276 * These are stub comments as this function needs more explanation - particularly in terms of how it
4277 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4279 * This function was originally written as a wrapper for the api query but is called from multiple places
4280 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4281 * but it is unclear as to whehter that is historical or there is a reason
4282 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4284 * @param array $params
4285 * @param array $returnProperties
4286 * @param null $fields
4287 * @param string $sort
4288 * @param int $offset
4289 * @param int $row_count
4290 * @param bool $smartGroupCache
4291 * @param bool $count return count obnly
4292 * @param bool $skipPermissions Should permissions be ignored or should the logged in user's permissions be applied
4294 * @params bool $smartGroupCache ?? update smart group cache?
4299 static function apiQuery(
4301 $returnProperties = NULL,
4306 $smartGroupCache = TRUE,
4308 $skipPermissions = TRUE
4311 $query = new CRM_Contact_BAO_Query(
4312 $params, $returnProperties,
4313 NULL, TRUE, FALSE, 1,
4315 TRUE, $smartGroupCache
4318 //this should add a check for view deleted if permissions are enabled
4319 if ($skipPermissions){
4320 $query->_skipDeleteClause
= TRUE;
4322 $query->generatePermissionClause(FALSE, $count);
4324 // note : this modifies _fromClause and _simpleFromClause
4325 $query->includePseudoFieldsJoin($sort);
4327 list($select, $from, $where, $having) = $query->query($count);
4329 $options = $query->_options
;
4330 if(!empty($query->_permissionWhereClause
)){
4331 if (empty($where)) {
4332 $where = "WHERE $query->_permissionWhereClause";
4335 $where = "$where AND $query->_permissionWhereClause";
4339 $sql = "$select $from $where $having";
4342 if ($query->_useGroupBy
) {
4343 $sql .= ' GROUP BY contact_a.id';
4345 if (!empty($sort)) {
4346 $sort = CRM_Utils_Type
::escape($sort, 'String');
4347 $sql .= " ORDER BY $sort ";
4349 if ($row_count > 0 && $offset >= 0) {
4350 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4351 $rowCount = CRM_Utils_Type
::escape($row_count, 'Int');
4352 $sql .= " LIMIT $offset, $row_count ";
4355 $dao = CRM_Core_DAO
::executeQuery($sql);
4358 while ($dao->fetch()) {
4360 $noRows = $dao->rowCount
;
4362 return array($noRows,NULL);
4364 $val = $query->store($dao);
4365 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4367 if (!empty($convertedVals)) {
4368 $val = array_replace_recursive($val, $convertedVals);
4370 $values[$dao->contact_id
] = $val;
4373 return array($values, $options);
4377 * create and query the db for an contact search
4379 * @param int $offset the offset for the query
4380 * @param int $rowCount the number of rows to return
4381 * @param string $sort the order by string
4382 * @param boolean $count is this a count only query ?
4383 * @param boolean $includeContactIds should we include contact ids?
4384 * @param boolean $sortByChar if true returns the distinct array of first characters for search results
4385 * @param boolean $groupContacts if true, return only the contact ids
4386 * @param boolean $returnQuery should we return the query as a string
4387 * @param string $additionalWhereClause if the caller wants to further restrict the search (used for components)
4388 * @param null $sortOrder
4389 * @param string $additionalFromClause should be clause with proper joins, effective to reduce where clause load.
4391 * @param bool $skipOrderAndLimit
4393 * @return CRM_Contact_DAO_Contact
4396 function searchQuery(
4397 $offset = 0, $rowCount = 0, $sort = NULL,
4398 $count = FALSE, $includeContactIds = FALSE,
4399 $sortByChar = FALSE, $groupContacts = FALSE,
4400 $returnQuery = FALSE,
4401 $additionalWhereClause = NULL, $sortOrder = NULL,
4402 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4405 if ($includeContactIds) {
4406 $this->_includeContactIds
= TRUE;
4407 $this->_whereClause
= $this->whereClause();
4410 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4412 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4413 // and that contact happens to be deleted, set $onlyDeleted to true
4414 foreach ($this->_params
as $values) {
4415 $name = CRM_Utils_Array
::value(0, $values);
4416 $op = CRM_Utils_Array
::value(1, $values);
4417 $value = CRM_Utils_Array
::value(2, $values);
4418 if ($name == 'contact_id' and $op == '=') {
4419 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4420 $onlyDeleted = TRUE;
4425 $this->generatePermissionClause($onlyDeleted, $count);
4427 // building the query string
4430 if (isset($this->_groupByComponentClause
)) {
4431 $groupBy = $this->_groupByComponentClause
;
4433 elseif ($this->_useGroupBy
) {
4434 $groupBy = ' GROUP BY contact_a.id';
4437 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4438 $groupBy = 'GROUP BY civicrm_activity.id ';
4441 $order = $orderBy = $limit = '';
4443 $config = CRM_Core_Config
::singleton();
4444 if ($config->includeOrderByClause ||
4445 isset($this->_distinctComponentClause
)
4448 if (is_string($sort)) {
4452 $orderBy = trim($sort->orderBy());
4454 if (!empty($orderBy)) {
4455 // this is special case while searching for
4456 // changelog CRM-1718
4457 if (preg_match('/sort_name/i', $orderBy)) {
4458 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4461 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
4462 $order = " ORDER BY $orderBy";
4465 $sortOrder = CRM_Utils_Type
::escape($sortOrder, 'String');
4466 $order .= " $sortOrder";
4469 // always add contact_a.id to the ORDER clause
4470 // so the order is deterministic
4471 if (strpos('contact_a.id', $order) === FALSE) {
4472 $order .= ", contact_a.id";
4476 elseif ($sortByChar) {
4477 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4480 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4484 // hack for order clause
4486 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4487 $fieldOrder = explode(' ', $fieldStr);
4488 $field = $fieldOrder[0];
4494 $this->_whereTables
["civicrm_address"] = 1;
4495 $order = str_replace($field, "civicrm_address.{$field}", $order);
4499 case 'state_province':
4500 $this->_whereTables
["civicrm_{$field}"] = 1;
4501 $order = str_replace($field, "civicrm_{$field}.name", $order);
4505 $this->_whereTables
["civicrm_email"] = 1;
4506 $order = str_replace($field, "civicrm_email.{$field}", $order);
4510 //CRM-12565 add "`" around $field if it is a pseudo constant
4511 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
4512 if (!empty($value['element']) && $value['element'] == $field) {
4513 $order = str_replace($field, "`{$field}`", $order);
4517 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4518 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4522 if ($rowCount > 0 && $offset >= 0) {
4523 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4524 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4525 $limit = " LIMIT $offset, $rowCount ";
4529 // note : this modifies _fromClause and _simpleFromClause
4530 $this->includePseudoFieldsJoin($sort);
4532 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts);
4534 if(!empty($this->_permissionWhereClause
)){
4535 if (empty($where)) {
4536 $where = "WHERE $this->_permissionWhereClause";
4539 $where = "$where AND $this->_permissionWhereClause";
4543 if ($additionalWhereClause) {
4544 $where = $where . ' AND ' . $additionalWhereClause;
4547 //additional from clause should be w/ proper joins.
4548 if ($additionalFromClause) {
4549 $from .= "\n" . $additionalFromClause;
4552 // if we are doing a transform, do it here
4553 // use the $from, $where and $having to get the contact ID
4554 if ($this->_displayRelationshipType
) {
4555 $this->filterRelatedContacts($from, $where, $having);
4558 if ($skipOrderAndLimit) {
4559 $query = "$select $from $where $having $groupBy";
4562 $query = "$select $from $where $having $groupBy $order $limit";
4569 return CRM_Core_DAO
::singleValueQuery($query);
4572 $dao = CRM_Core_DAO
::executeQuery($query);
4573 if ($groupContacts) {
4575 while ($dao->fetch()) {
4578 return implode(',', $ids);
4585 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4587 * @param string $cacheKey
4588 * @param int $offset
4589 * @param int $rowCount
4590 * @param bool $includeContactIds
4591 * @return CRM_Core_DAO
4593 function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4594 $this->_includeContactIds
= $includeContactIds;
4595 list($select, $from, $where) = $this->query();
4596 $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);
4597 $order = " ORDER BY pnc.id";
4598 $groupBy = " GROUP BY contact_a.id";
4599 $limit = " LIMIT $offset, $rowCount";
4600 $query = "$select $from $where $groupBy $order $limit";
4602 return CRM_Core_DAO
::executeQuery($query);
4606 * Populate $this->_permissionWhereClause with permission related clause and update other
4607 * query related properties.
4609 * Function calls ACL permission class and hooks to filter the query appropriately
4611 * Note that these 2 params were in the code when extracted from another function
4612 * and a second round extraction would be to make them properties of the class
4614 * @param bool $onlyDeleted Only get deleted contacts
4615 * @param bool $count Return Count only
4619 function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4620 if (!$this->_skipPermission
) {
4621 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4622 CRM_Core_Permission
::VIEW
,
4624 $this->_whereTables
,
4627 $this->_skipDeleteClause
4630 // regenerate fromClause since permission might have added tables
4631 if ($this->_permissionWhereClause
) {
4632 //fix for row count in qill (in contribute/membership find)
4634 $this->_useDistinct
= TRUE;
4636 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4637 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4641 // add delete clause if needed even if we are skipping permission
4643 if (!$this->_skipDeleteClause
) {
4644 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4645 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4649 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4658 function setSkipPermission($val) {
4659 $this->_skipPermission
= $val;
4663 * @param null $context
4667 function &summaryContribution($context = NULL) {
4668 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4672 SELECT COUNT( conts.total_amount ) as total_count,
4673 SUM( conts.total_amount ) as total_amount,
4674 AVG( conts.total_amount ) as total_avg,
4675 conts.currency as currency";
4676 if($this->_permissionWhereClause
) {
4677 $where .= " AND " . $this->_permissionWhereClause
;
4679 if ($context == 'search') {
4680 $where .= " AND contact_a.is_deleted = 0 ";
4683 // make sure contribution is completed - CRM-4989
4684 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4688 $summary['total'] = array();
4689 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4691 $query = "$select FROM (
4692 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $completedWhere
4693 GROUP BY civicrm_contribution.id
4697 $dao = CRM_Core_DAO
::executeQuery($query);
4699 $summary['total']['count'] = 0;
4700 $summary['total']['amount'] = $summary['total']['avg'] = array();
4701 while ($dao->fetch()) {
4702 $summary['total']['count'] +
= $dao->total_count
;
4703 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4704 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4706 if (!empty($summary['total']['amount'])) {
4707 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4708 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4711 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4714 // soft credit summary
4715 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
4716 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
4719 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
4720 GROUP BY civicrm_contribution_soft.id
4723 $dao = CRM_Core_DAO
::executeQuery($query);
4724 $summary['soft_credit']['count'] = 0;
4725 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
4726 while ($dao->fetch()) {
4727 $summary['soft_credit']['count'] +
= $dao->total_count
;
4728 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4729 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4731 if (!empty($summary['soft_credit']['amount'])) {
4732 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
4733 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
4736 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
4741 //@todo - this could be one query using the IF in mysql - eg
4742 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
4743 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
4744 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
4745 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
4746 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
4747 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
4748 // FROM civicrm_contact contact_a
4749 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
4750 // WHERE ( ... where clause....
4751 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
4755 SELECT COUNT( conts.total_amount ) as cancel_count,
4756 SUM( conts.total_amount ) as cancel_amount,
4757 AVG( conts.total_amount ) as cancel_avg,
4758 conts.currency as currency";
4760 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4761 if ($context == 'search') {
4762 $where .= " AND contact_a.is_deleted = 0 ";
4765 $query = "$select FROM (
4766 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
4767 GROUP BY civicrm_contribution.id
4771 $dao = CRM_Core_DAO
::executeQuery($query);
4774 if ($dao->fetch()) {
4775 $summary['cancel']['count'] = $dao->cancel_count
;
4776 $summary['cancel']['amount'] = $dao->cancel_amount
;
4777 $summary['cancel']['avg'] = $dao->cancel_avg
;
4781 $summary['cancel']['count'] = 0;
4782 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4783 while ($dao->fetch()) {
4784 $summary['cancel']['count'] +
= $dao->cancel_count
;
4785 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4786 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4788 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4789 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
4796 * getter for the qill object
4802 return $this->_qill
;
4806 * default set of return default hier return properties
4811 static function &defaultHierReturnProperties() {
4812 if (!isset(self
::$_defaultHierReturnProperties)) {
4813 self
::$_defaultHierReturnProperties = array(
4816 'legal_identifier' => 1,
4817 'external_identifier' => 1,
4818 'contact_type' => 1,
4819 'contact_sub_type' => 1,
4821 'display_name' => 1,
4828 'formal_title' => 1,
4829 'communication_style_id' => 1,
4830 'email_greeting' => 1,
4831 'postal_greeting' => 1,
4835 'preferred_communication_method' => 1,
4836 'do_not_phone' => 1,
4837 'do_not_email' => 1,
4840 'do_not_trade' => 1,
4843 '1' => array('location_type' => 1,
4844 'street_address' => 1,
4846 'state_province' => 1,
4848 'postal_code_suffix' => 1,
4851 'phone-Mobile' => 1,
4864 'location_type' => 1,
4865 'street_address' => 1,
4867 'state_province' => 1,
4869 'postal_code_suffix' => 1,
4872 'phone-Mobile' => 1,
4886 return self
::$_defaultHierReturnProperties;
4893 * @param $dbFieldName
4894 * @param $fieldTitle
4895 * @param bool $appendTimeStamp
4897 function dateQueryBuilder(
4898 &$values, $tableName, $fieldName,
4899 $dbFieldName, $fieldTitle,
4900 $appendTimeStamp = TRUE
4902 list($name, $op, $value, $grouping, $wildcard) = $values;
4908 if ($name == "{$fieldName}_low" ||
4909 $name == "{$fieldName}_high"
4911 if (isset($this->_rangeCache
[$fieldName])) {
4914 $this->_rangeCache
[$fieldName] = 1;
4916 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4918 if ($name == $fieldName . '_low') {
4920 $firstPhrase = ts('greater than or equal to');
4921 $firstDate = CRM_Utils_Date
::processDate($value);
4923 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4924 if (!empty($secondValues) && $secondValues[2]) {
4926 $secondPhrase = ts('less than or equal to');
4927 $secondValue = $secondValues[2];
4929 if ($appendTimeStamp && strlen($secondValue) == 10) {
4930 $secondValue .= ' 23:59:59';
4932 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4935 elseif ($name == $fieldName . '_high') {
4937 $firstPhrase = ts('less than or equal to');
4939 if ($appendTimeStamp && strlen($value) == 10) {
4940 $value .= ' 23:59:59';
4942 $firstDate = CRM_Utils_Date
::processDate($value);
4944 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4945 if (!empty($secondValues) && $secondValues[2]) {
4947 $secondPhrase = ts('greater than or equal to');
4948 $secondValue = $secondValues[2];
4949 $secondDate = CRM_Utils_Date
::processDate($secondValue);
4953 if (!$appendTimeStamp) {
4954 $firstDate = substr($firstDate, 0, 8);
4956 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
4959 if (!$appendTimeStamp) {
4960 $secondDate = substr($secondDate, 0, 8);
4962 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
4965 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4967 $this->_where
[$grouping][] = "
4968 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
4969 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
4971 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
4974 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
4975 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
4979 if ($name == $fieldName) {
4983 $date = CRM_Utils_Date
::processDate($value);
4985 if (!$appendTimeStamp) {
4986 $date = substr($date, 0, 8);
4989 $format = CRM_Utils_Date
::customFormat($date);
4992 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'";
4995 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op";
4997 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
4998 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$format\"";
5006 * @param $dbFieldName
5007 * @param $fieldTitle
5008 * @param null $options
5010 function numberRangeBuilder(&$values,
5011 $tableName, $fieldName,
5012 $dbFieldName, $fieldTitle,
5015 list($name, $op, $value, $grouping, $wildcard) = $values;
5017 if ($name == "{$fieldName}_low" ||
5018 $name == "{$fieldName}_high"
5020 if (isset($this->_rangeCache
[$fieldName])) {
5023 $this->_rangeCache
[$fieldName] = 1;
5025 $secondOP = $secondPhrase = $secondValue = NULL;
5027 if ($name == "{$fieldName}_low") {
5029 $firstPhrase = ts('greater than');
5031 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5032 if (!empty($secondValues)) {
5034 $secondPhrase = ts('less than');
5035 $secondValue = $secondValues[2];
5040 $firstPhrase = ts('less than');
5042 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5043 if (!empty($secondValues)) {
5045 $secondPhrase = ts('greater than');
5046 $secondValue = $secondValues[2];
5051 $this->_where
[$grouping][] = "
5052 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5053 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5055 $displayValue = $options ?
$options[$value] : $value;
5056 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5058 $this->_qill
[$grouping][] =
5059 "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5062 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5063 $displayValue = $options ?
$options[$value] : $value;
5064 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5066 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5071 if ($name == $fieldName) {
5075 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5077 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5078 $displayValue = $options ?
$options[$value] : $value;
5079 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5086 * Given the field name, operator, value & its data type
5087 * builds the where Clause for the query
5088 * used for handling 'IS NULL'/'IS NOT NULL' operators
5090 * @param string $field fieldname
5091 * @param string $op operator
5092 * @param string $value value
5093 * @param string $dataType data type of the field
5095 * @return string where clause for the query
5098 static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5100 $clause = "$field $op";
5108 $clause = " ( $field IS NULL OR $field = '' ) ";
5111 case 'IS NOT EMPTY':
5112 $clause = " ( $field IS NOT NULL AND $field <> '' ) ";
5117 if (isset($dataType)) {
5118 if (is_array($value)) {
5122 $value = CRM_Utils_Type
::escape($value, "String");
5123 $values = explode(',', CRM_Utils_Array
::value(0, explode(')', CRM_Utils_Array
::value(1, explode('(', $value)))));
5125 // supporting multiple values in IN clause
5127 foreach ($values as $v) {
5129 $val[] = "'" . CRM_Utils_Type
::escape($v, $dataType) . "'";
5131 $value = "(" . implode($val, ",") . ")";
5133 return "$clause $value";
5136 if (empty($dataType)) {
5137 $dataType = 'String';
5140 $value = CRM_Utils_Type
::escape($value, $dataType);
5141 // if we dont have a dataType we should assume
5142 if ($dataType == 'String' ||
$dataType == 'Text') {
5143 $value = "'" . strtolower($value) . "'";
5145 return "$clause $value";
5150 * @param bool $reset
5154 function openedSearchPanes($reset = FALSE) {
5155 if (!$reset ||
empty($this->_whereTables
)) {
5156 return self
::$_openedPanes;
5159 // pane name to table mapper
5160 $panesMapper = array(
5161 ts('Contributions') => 'civicrm_contribution',
5162 ts('Memberships') => 'civicrm_membership',
5163 ts('Events') => 'civicrm_participant',
5164 ts('Relationships') => 'civicrm_relationship',
5165 ts('Activities') => 'civicrm_activity',
5166 ts('Pledges') => 'civicrm_pledge',
5167 ts('Cases') => 'civicrm_case',
5168 ts('Grants') => 'civicrm_grant',
5169 ts('Address Fields') => 'civicrm_address',
5170 ts('Notes') => 'civicrm_note',
5171 ts('Change Log') => 'civicrm_log',
5172 ts('Mailings') => 'civicrm_mailing_event_queue',
5174 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5176 foreach (array_keys($this->_whereTables
) as $table) {
5177 if ($panName = array_search($table, $panesMapper)) {
5178 self
::$_openedPanes[$panName] = TRUE;
5182 return self
::$_openedPanes;
5188 function setOperator($operator) {
5189 $validOperators = array('AND', 'OR');
5190 if (!in_array($operator, $validOperators)) {
5193 $this->_operator
= $operator;
5199 function getOperator() {
5200 return $this->_operator
;
5208 function filterRelatedContacts(&$from, &$where, &$having) {
5209 static $_rTypeProcessed = NULL;
5210 static $_rTypeFrom = NULL;
5211 static $_rTypeWhere = NULL;
5213 if (!$_rTypeProcessed) {
5214 $_rTypeProcessed = TRUE;
5216 // create temp table with contact ids
5217 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5218 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5219 CRM_Core_DAO
::executeQuery($sql);
5222 REPLACE INTO $tableName ( contact_id )
5228 CRM_Core_DAO
::executeQuery($sql);
5230 $qillMessage = ts('Contacts with a Relationship Type of: ');
5231 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5233 if (is_numeric($this->_displayRelationshipType
)) {
5234 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5236 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5237 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5240 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5241 AND displayRelType.is_active = 1
5245 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5246 if ($dirOne == 'a') {
5247 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5249 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5250 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5254 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5256 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5257 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5261 WHERE displayRelType.relationship_type_id = $relType
5262 AND displayRelType.is_active = 1
5265 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5268 if (strpos($from, $_rTypeFrom) === FALSE) {
5269 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5270 // this happens when we have an event_type in the quert (CRM-7969)
5271 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5272 $from .= $_rTypeFrom;
5273 $where = $_rTypeWhere;
5284 static function caseImportant( $op ) {
5286 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5290 * @param $returnProperties
5295 static function componentPresent( &$returnProperties, $prefix ) {
5296 foreach ($returnProperties as $name => $dontCare ) {
5297 if (substr($name, 0, strlen($prefix)) == $prefix) {
5305 * Builds the necessary structures for all fields that are similar to option value lookups
5307 * @param $name string the name of the field
5308 * @param $op string the sql operator, this function should handle ALL SQL operators
5309 * @param $value string|integer|array depends on the operator and who's calling the query builder
5310 * @param $grouping int the index where to place the where clause
5311 * @param $selectValues
5312 * @param $field array an array that contains various properties of the field identified by $name
5313 * @param $label string The label for this field element
5314 * @param $dataType string The data type for this element
5316 * @param bool $useIDsOnly
5318 * @internal param array $selectValue the key value pairs for this element. This allows us to use this function for things besides option-value pairs
5319 * @return void adds the where clause and qill to the query object
5321 function optionValueQuery(
5329 $dataType = 'String',
5333 if (!empty($selectValues)) {
5334 $qill = $selectValues[$value];
5340 $pseudoFields = array('email_greeting', 'postal_greeting', 'addressee', 'gender_id', 'prefix_id', 'suffix_id', 'communication_style_id');
5342 if (is_numeric($value)) {
5343 $qill = $selectValues[(int ) $value];
5345 elseif ($op == 'IN' ||
$op == 'NOT IN') {
5346 $values = self
::parseSearchBuilderString($value);
5347 if (is_array($values)) {
5349 $newValues = array();
5350 foreach ($values as $v) {
5351 $intVals[] = (int) $v;
5352 $newValues[] = $selectValues[(int ) $v];
5355 $value = (in_array($name, $pseudoFields)) ?
$intVals : $newValues;
5356 $qill = implode(', ', $newValues);
5359 elseif (!array_key_exists($value, $selectValues)) {
5360 // its a string, lets get the int value
5361 $value = array_search($value, $selectValues);
5364 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5365 if ($tableName == 'civicrm_contact') {
5366 $wc = "contact_a.$fieldName";
5370 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5373 if (in_array($name, $pseudoFields)) {
5374 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5375 $wc = "contact_a.{$name}_id";
5377 $dataType = 'Positive';
5378 $value = (!$value) ?
0 : $value;
5381 $this->_qill
[$grouping][] = $label . " $op '$qill'";
5382 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' ||
$op == 'RLIKE')) ?
'=' : $op;
5383 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5387 * function to check and explode a user defined numeric string into an array
5388 * this was the protocol used by search builder in the old old days before we had
5389 * super nice js widgets to do the hard work
5391 * @param string $string
5392 * @param string $dataType the dataType we should check for the values, default integer
5394 * @return bool|array if string does not match the patter
5395 * array of numeric values if string does match the pattern
5398 static function parseSearchBuilderString($string, $dataType = 'Integer') {
5399 $string = trim($string);
5400 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5404 $string = substr($string, 1, -1);
5405 $values = explode(',', $string);
5406 if (empty($values)) {
5410 $returnValues = array();
5411 foreach ($values as $v) {
5412 if ($dataType == 'Integer' && ! is_numeric($v)) {
5415 else if ($dataType == 'String' && ! is_string($v)) {
5418 $returnValues[] = trim($v);
5421 if (empty($returnValues)) {
5425 return $returnValues;
5429 * convert the pseudo constants id's to their names
5431 * @param CRM_Core_DAO dao
5432 * @param bool $return
5436 function convertToPseudoNames(&$dao, $return = FALSE) {
5437 if (empty($this->_pseudoConstantsSelect
)) {
5441 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5442 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5446 if (property_exists($dao, $value['idCol'])) {
5447 $val = $dao->$value['idCol'];
5449 if (CRM_Utils_System
::isNull($val)) {
5452 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5454 $idColumn = "{$key}_id";
5455 $dao->$idColumn = $val;
5456 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5458 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5459 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5461 // FIX ME: we should potentially move this to component Query and write a wrapper function that
5462 // handles pseudoconstant fixes for all component
5463 elseif ($value['pseudoField'] == 'participant_role') {
5464 $viewRoles = array();
5465 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val) as $k => $v) {
5466 $viewRoles[] = CRM_Event_PseudoConstant
::participantRole($v);
5468 $dao->$key = implode(', ', $viewRoles);
5471 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5472 $dao->$key = $labels[$val];
5475 // return converted values in array format
5477 if (strpos($key, '-') !== FALSE) {
5478 $keyVal = explode('-', $key);
5479 $current = &$values;
5480 $lastElement = array_pop($keyVal);
5481 foreach ($keyVal as $v) {
5482 if (!array_key_exists($v, $current)) {
5483 $current[$v] = array();
5485 $current = &$current[$v];
5487 $current[$lastElement] = $dao->$key;
5490 $values[$key] = $dao->$key;
5499 * include pseudo fields LEFT JOIN
5500 * @param string|array $sort can be a object or string
5504 function includePseudoFieldsJoin($sort) {
5505 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5508 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5511 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5512 if (!empty($value['table'])) {
5513 $regex = "/({$value['table']}\.|{$name})/";
5514 if (preg_match($regex, $sort)) {
5515 $this->_elemnt
[$value['element']] = 1;
5516 $this->_select
[$value['element']] = $value['select'];
5517 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5518 $present[$value['table']] = $value['join'];
5522 $presentSimpleFrom = $present;
5524 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5525 array_key_exists('civicrm_country', $presentSimpleFrom)) {
5526 unset($presentSimpleFrom['civicrm_country']);
5528 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5529 array_key_exists('civicrm_country', $present)) {
5530 unset($present['civicrm_country']);
5533 $presentClause = $presentSimpleFromClause = NULL;
5534 if (!empty($present)) {
5535 $presentClause = implode(' ', $present);
5537 if (!empty($presentSimpleFrom)) {
5538 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5541 $this->_fromClause
= $this->_fromClause
. $presentClause;
5542 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5544 return array($presentClause, $presentSimpleFromClause);