3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
35 * This is the heart of the search query building mechanism.
37 class CRM_Contact_BAO_Query
{
40 * The various search modes.
50 MODE_PLEDGEBANK
= 256,
59 * The default set of return properties.
63 static $_defaultReturnProperties = NULL;
66 * The default set of hier return properties.
70 static $_defaultHierReturnProperties;
73 * The set of input params.
85 * The set of output params
89 public $_returnProperties;
99 * The name of the elements that are in the select clause
100 * used to extract the values
107 * The tables involved in the query
114 * The table involved in the where clause
118 public $_whereTables;
132 public $_whereClause;
135 * Additional permission Where Clause
139 public $_permissionWhereClause;
149 * Additional permission from clause
153 public $_permissionFromClause;
156 * The from clause for the simple select and alphabetical
161 public $_simpleFromClause;
171 * The english language version of the query
178 * All the fields that could potentially be involved in
186 * The cache to translate the option values into labels.
193 * Are we in search mode.
197 public $_search = TRUE;
200 * Should we skip permission checking.
204 public $_skipPermission = FALSE;
207 * Should we skip adding of delete clause.
211 public $_skipDeleteClause = FALSE;
214 * Are we in strict mode (use equality over LIKE)
218 public $_strict = FALSE;
221 * What operator to use to group the clauses.
225 public $_operator = 'AND';
230 * Should we only search on primary location.
234 public $_primaryLocation = TRUE;
237 * Are contact ids part of the query.
241 public $_includeContactIds = FALSE;
244 * Should we use the smart group cache.
248 public $_smartGroupCache = TRUE;
251 * Should we display contacts with a specific relationship type.
255 public $_displayRelationshipType = NULL;
258 * Reference to the query object for custom values.
262 public $_customQuery;
265 * Should we enable the distinct clause, used if we are including
266 * more than one group
270 public $_useDistinct = FALSE;
273 * Should we just display one contact record
275 public $_useGroupBy = FALSE;
278 * The relationship type direction
289 static $_activityRole;
292 * Consider the component activity type
293 * during activity search.
297 static $_considerCompActivities;
300 * Consider with contact activities only,
301 * during activity search.
305 static $_withContactActivitiesOnly;
308 * Use distinct component clause for component searches
312 public $_distinctComponentClause;
314 public $_rowCountClause;
317 * Use groupBy component clause for component searches
321 public $_groupByComponentClause;
324 * Track open panes, useful in advance search
328 public static $_openedPanes = array();
331 * For search builder - which custom fields are location-dependent
334 public $_locationSpecificCustomFields = array();
337 * The tables which have a dependency on location and/or address
341 static $_dependencies = array(
342 'civicrm_state_province' => 1,
343 'civicrm_country' => 1,
344 'civicrm_county' => 1,
345 'civicrm_address' => 1,
346 'civicrm_location_type' => 1,
350 * List of location specific fields.
352 static $_locationSpecificFields = array(
357 'supplemental_address_1',
358 'supplemental_address_2',
361 'postal_code_suffix',
374 * Remember if we handle either end of a number or date range
375 * so we can skip the other
377 protected $_rangeCache = array();
379 * Set to true when $this->relationship is run to avoid adding twice
382 protected $_relationshipValuesAdded = FALSE;
385 * Set to the name of the temp table if one has been created
388 static $_relationshipTempTable = NULL;
390 public $_pseudoConstantsSelect = array();
393 * Class constructor which also does all the work.
395 * @param array $params
396 * @param array $returnProperties
397 * @param array $fields
398 * @param bool $includeContactIds
399 * @param bool $strict
400 * @param bool|int $mode - mode the search is operating on
402 * @param bool $skipPermission
403 * @param bool $searchDescendentGroups
404 * @param bool $smartGroupCache
405 * @param null $displayRelationshipType
406 * @param string $operator
408 * @return \CRM_Contact_BAO_Query
410 public function __construct(
411 $params = NULL, $returnProperties = NULL, $fields = NULL,
412 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
413 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
414 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
417 $this->_params
= &$params;
418 if ($this->_params
== NULL) {
419 $this->_params
= array();
422 if (empty($returnProperties)) {
423 $this->_returnProperties
= self
::defaultReturnProperties($mode);
426 $this->_returnProperties
= &$returnProperties;
429 $this->_includeContactIds
= $includeContactIds;
430 $this->_strict
= $strict;
431 $this->_mode
= $mode;
432 $this->_skipPermission
= $skipPermission;
433 $this->_smartGroupCache
= $smartGroupCache;
434 $this->_displayRelationshipType
= $displayRelationshipType;
435 $this->setOperator($operator);
438 $this->_fields
= &$fields;
439 $this->_search
= FALSE;
440 $this->_skipPermission
= TRUE;
443 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE);
445 $fields = CRM_Core_Component
::getQueryFields();
446 unset($fields['note']);
447 $this->_fields
= array_merge($this->_fields
, $fields);
449 // add activity fields
450 $fields = CRM_Activity_BAO_Activity
::exportableFields();
451 $this->_fields
= array_merge($this->_fields
, $fields);
453 // add any fields provided by hook implementers
454 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
455 $this->_fields
= array_merge($this->_fields
, $extFields);
458 // basically do all the work once, and then reuse it
463 * Function which actually does all the work for the constructor.
465 public function initialize() {
466 $this->_select
= array();
467 $this->_element
= array();
468 $this->_tables
= array();
469 $this->_whereTables
= array();
470 $this->_where
= array();
471 $this->_qill
= array();
472 $this->_options
= array();
473 $this->_cfIDs
= array();
474 $this->_paramLookup
= array();
475 $this->_having
= array();
477 $this->_customQuery
= NULL;
479 // reset cached static variables - CRM-5803
480 self
::$_activityRole = NULL;
481 self
::$_considerCompActivities = NULL;
482 self
::$_withContactActivitiesOnly = NULL;
484 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
485 $this->_element
['contact_id'] = 1;
486 $this->_tables
['civicrm_contact'] = 1;
488 if (!empty($this->_params
)) {
489 $this->buildParamsLookup();
492 $this->_whereTables
= $this->_tables
;
494 $this->selectClause();
495 $this->_whereClause
= $this->whereClause();
497 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
498 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
500 $this->openedSearchPanes(TRUE);
504 * Function for same purpose as convertFormValues.
506 * Like convert form values this function exists to pre-Process parameters from the form.
508 * It is unclear why they are different functions & likely relates to advances search
509 * versus search builder.
511 * The direction we are going is having the form convert values to a standardised format &
512 * moving away from wierd & wonderful where clause switches.
514 * Fix and handle contact deletion nicely.
516 * this code is primarily for search builder use case where different clauses can specify if they want deleted.
520 public function buildParamsLookup() {
521 $trashParamExists = FALSE;
522 $paramByGroup = array();
523 foreach ($this->_params
as $k => $param) {
524 if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
525 $trashParamExists = TRUE;
527 if (!empty($param[3])) {
528 $paramByGroup[$param[3]][$k] = $param;
532 if ($trashParamExists) {
533 $this->_skipDeleteClause
= TRUE;
535 //cycle through group sets and explicitly add trash param if not set
536 foreach ($paramByGroup as $setID => $set) {
538 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params
) &&
539 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params
)
541 $this->_params
[] = array(
542 'contact_is_deleted',
552 foreach ($this->_params
as $value) {
553 if (empty($value[0])) {
556 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
558 if (!array_key_exists($cfID, $this->_cfIDs
)) {
559 $this->_cfIDs
[$cfID] = array();
561 // Set wildcard value based on "and/or" selection
562 foreach ($this->_params
as $key => $param) {
563 if ($param[0] == $value[0] . '_operator') {
564 $value[4] = $param[2] == 'or';
568 $this->_cfIDs
[$cfID][] = $value;
571 if (!array_key_exists($value[0], $this->_paramLookup
)) {
572 $this->_paramLookup
[$value[0]] = array();
574 $this->_paramLookup
[$value[0]][] = $value;
579 * Some composite fields do not appear in the fields array hack to make them part of the query.
581 public function addSpecialFields() {
582 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
583 foreach ($special as $name) {
584 if (!empty($this->_returnProperties
[$name])) {
585 $this->_select
[$name] = "contact_a.{$name} as $name";
586 $this->_element
[$name] = 1;
592 * Given a list of conditions in params and a list of desired
593 * return Properties generate the required select and from
594 * clauses. Note that since the where clause introduces new
595 * tables, the initial attempt also retrieves all variables used
598 public function selectClause() {
600 $this->addSpecialFields();
602 foreach ($this->_fields
as $name => $field) {
603 // skip component fields
604 // there are done by the alter query below
605 // and need not be done on every field
607 (substr($name, 0, 12) == 'participant_') ||
608 (substr($name, 0, 7) == 'pledge_') ||
609 (substr($name, 0, 5) == 'case_') ||
610 (substr($name, 0, 13) == 'contribution_' &&
611 (strpos($name, 'source') !== FALSE && strpos($name, 'recur') !== FALSE)) ||
612 (substr($name, 0, 8) == 'payment_')
617 // redirect to activity select clause
619 (substr($name, 0, 9) == 'activity_') ||
620 ($name == 'parent_id')
622 CRM_Activity_BAO_Query
::select($this);
626 // if this is a hierarchical name, we ignore it
627 $names = explode('-', $name);
628 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
632 // make an exception for special cases, to add the field in select clause
633 $makeException = FALSE;
635 //special handling for groups/tags
636 if (in_array($name, array('groups', 'tags', 'notes'))
637 && isset($this->_returnProperties
[substr($name, 0, -1)])
639 $makeException = TRUE;
642 // since note has 3 different options we need special handling
643 // note / note_subject / note_body
644 if ($name == 'notes') {
645 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
646 if (isset($this->_returnProperties
[$noteField])) {
647 $makeException = TRUE;
653 if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id', 'communication_style_id'))) {
654 if (CRM_Utils_Array
::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties
)) {
655 $makeException = TRUE;
659 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
660 if (!empty($this->_paramLookup
[$name]) ||
!empty($this->_returnProperties
[$name]) ||
664 // add to cfIDs array if not present
665 if (!array_key_exists($cfID, $this->_cfIDs
)) {
666 $this->_cfIDs
[$cfID] = array();
669 elseif (isset($field['where'])) {
670 list($tableName, $fieldName) = explode('.', $field['where'], 2);
671 if (isset($tableName)) {
672 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
673 $this->_tables
['civicrm_address'] = 1;
674 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
675 $this->_element
['address_id'] = 1;
678 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
679 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
681 if ($tableName == 'im_provider') {
682 CRM_Core_OptionValue
::select($this);
685 if (in_array($tableName,
686 array('email_greeting', 'postal_greeting', 'addressee'))) {
687 $this->_element
["{$name}_id"] = 1;
688 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
689 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
690 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
691 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
693 if ($tableName == 'email_greeting') {
694 $this->_pseudoConstantsSelect
[$name]['join']
695 = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
696 $this->_pseudoConstantsSelect
[$name]['join'] .=
697 " 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 ) ";
699 elseif ($tableName == 'postal_greeting') {
700 $this->_pseudoConstantsSelect
[$name]['join']
701 = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
702 $this->_pseudoConstantsSelect
[$name]['join'] .=
703 " 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 ) ";
705 elseif ($tableName == 'addressee') {
706 $this->_pseudoConstantsSelect
[$name]['join']
707 = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
708 $this->_pseudoConstantsSelect
[$name]['join'] .=
709 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
711 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
714 $greetField = "{$name}_display";
715 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
716 $this->_element
[$greetField] = 1;
718 $greetField = "{$name}_custom";
719 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
720 $this->_element
[$greetField] = 1;
724 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
725 $this->_tables
[$tableName] = 1;
728 // also get the id of the tableName
729 $tName = substr($tableName, 8);
730 if (in_array($tName, array('country', 'state_province', 'county'))) {
731 if ($tName == 'state_province') {
732 $this->_pseudoConstantsSelect
['state_province_name'] = array(
733 'pseudoField' => "{$tName}",
734 'idCol' => "{$tName}_id",
735 'bao' => 'CRM_Core_BAO_Address',
736 'table' => "civicrm_{$tName}",
737 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
740 $this->_pseudoConstantsSelect
[$tName] = array(
741 'pseudoField' => 'state_province_abbreviation',
742 'idCol' => "{$tName}_id",
743 'table' => "civicrm_{$tName}",
744 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
748 $this->_pseudoConstantsSelect
[$name] = array(
749 'pseudoField' => "{$tName}_id",
750 'idCol' => "{$tName}_id",
751 'bao' => 'CRM_Core_BAO_Address',
752 'table' => "civicrm_{$tName}",
753 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
757 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
758 $this->_element
["{$tName}_id"] = 1;
760 elseif ($tName != 'contact') {
761 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
762 $this->_element
["{$tName}_id"] = 1;
765 //special case for phone
766 if ($name == 'phone') {
767 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
768 $this->_element
['phone_type_id'] = 1;
771 // if IM then select provider_id also
772 // to get "IM Service Provider" in a file to be exported, CRM-3140
774 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
775 $this->_element
['provider_id'] = 1;
778 if ($tName == 'contact') {
779 // special case, when current employer is set for Individual contact
780 if ($fieldName == 'organization_name') {
781 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
783 elseif ($fieldName != 'id') {
784 if ($fieldName == 'prefix_id') {
785 $this->_pseudoConstantsSelect
['individual_prefix'] = array(
786 'pseudoField' => 'prefix_id',
787 'idCol' => "prefix_id",
788 'bao' => 'CRM_Contact_BAO_Contact',
791 if ($fieldName == 'suffix_id') {
792 $this->_pseudoConstantsSelect
['individual_suffix'] = array(
793 'pseudoField' => 'suffix_id',
794 'idCol' => "suffix_id",
795 'bao' => 'CRM_Contact_BAO_Contact',
798 if ($fieldName == 'gender_id') {
799 $this->_pseudoConstantsSelect
['gender'] = array(
800 'pseudoField' => 'gender_id',
801 'idCol' => "gender_id",
802 'bao' => 'CRM_Contact_BAO_Contact',
805 if ($name == 'communication_style_id') {
806 $this->_pseudoConstantsSelect
['communication_style'] = array(
807 'pseudoField' => 'communication_style_id',
808 'idCol' => "communication_style_id",
809 'bao' => 'CRM_Contact_BAO_Contact',
812 $this->_select
[$name] = "contact_a.{$fieldName} as `$name`";
815 elseif (in_array($tName, array('country', 'county'))) {
816 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
817 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
819 elseif ($tName == 'state_province') {
820 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
821 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
824 $this->_select
[$name] = "{$field['where']} as `$name`";
826 if (!in_array($tName, array('state_province', 'country', 'county'))) {
827 $this->_element
[$name] = 1;
832 elseif ($name === 'tags') {
833 $this->_useGroupBy
= TRUE;
834 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
835 $this->_element
[$name] = 1;
836 $this->_tables
['civicrm_tag'] = 1;
837 $this->_tables
['civicrm_entity_tag'] = 1;
839 elseif ($name === 'groups') {
840 $this->_useGroupBy
= TRUE;
841 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
842 $this->_element
[$name] = 1;
843 $this->_tables
['civicrm_group'] = 1;
845 elseif ($name === 'notes') {
846 // if note field is subject then return subject else body of the note
847 $noteColumn = 'note';
848 if (isset($noteField) && $noteField == 'note_subject') {
849 $noteColumn = 'subject';
852 $this->_useGroupBy
= TRUE;
853 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
854 $this->_element
[$name] = 1;
855 $this->_tables
['civicrm_note'] = 1;
857 elseif ($name === 'current_employer') {
858 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
859 $this->_element
[$name] = 1;
863 if ($cfID && !empty($field['is_search_range'])) {
864 // this is a custom field with range search enabled, so we better check for two/from values
865 if (!empty($this->_paramLookup
[$name . '_from'])) {
866 if (!array_key_exists($cfID, $this->_cfIDs
)) {
867 $this->_cfIDs
[$cfID] = array();
869 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
870 // search in the cdID array for the same grouping
872 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
873 if ($c[3] == $p[3]) {
874 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
879 $p[2] = array('from' => $p[2]);
880 $this->_cfIDs
[$cfID][] = $p;
884 if (!empty($this->_paramLookup
[$name . '_to'])) {
885 if (!array_key_exists($cfID, $this->_cfIDs
)) {
886 $this->_cfIDs
[$cfID] = array();
888 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
889 // search in the cdID array for the same grouping
891 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
892 if ($c[4] == $p[4]) {
893 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
898 $p[2] = array('to' => $p[2]);
899 $this->_cfIDs
[$cfID][] = $p;
906 // add location as hierarchical elements
907 $this->addHierarchicalElements();
909 // add multiple field like website
910 $this->addMultipleElements();
913 CRM_Core_Component
::alterQuery($this, 'select');
915 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
917 if (!empty($this->_cfIDs
)) {
918 // @todo This function is the select function but instead of running 'select' it
919 // is running the whole query.
920 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
921 $this->_customQuery
->query();
922 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
923 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
924 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
925 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
926 $this->_options
= $this->_customQuery
->_options
;
931 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
933 public function addHierarchicalElements() {
934 if (empty($this->_returnProperties
['location'])) {
937 if (!is_array($this->_returnProperties
['location'])) {
941 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
942 $processed = array();
945 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
946 $addressCustomFieldIds = array();
948 foreach ($this->_returnProperties
['location'] as $name => $elements) {
949 $lCond = self
::getPrimaryCondition($name);
952 $locationTypeId = array_search($name, $locationTypes);
953 if ($locationTypeId === FALSE) {
956 $lCond = "location_type_id = $locationTypeId";
957 $this->_useDistinct
= TRUE;
959 //commented for CRM-3256
960 $this->_useGroupBy
= TRUE;
963 $name = str_replace(' ', '_', $name);
965 $tName = "$name-location_type";
966 $ltName = "`$name-location_type`";
967 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
968 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
969 $this->_element
["{$tName}_id"] = 1;
970 $this->_element
["{$tName}"] = 1;
972 $locationTypeName = $tName;
973 $locationTypeJoin = array();
977 foreach ($elements as $elementFullName => $dontCare) {
979 $elementName = $elementCmpName = $elementFullName;
981 if (substr($elementCmpName, 0, 5) == 'phone') {
982 $elementCmpName = 'phone';
985 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
986 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
987 $addressCustomFieldIds[$cfID][$name] = 1;
990 //add address table only once
991 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
993 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
995 $tName = "$name-address";
996 $aName = "`$name-address`";
997 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
998 $this->_element
["{$tName}_id"] = 1;
999 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
1000 $this->_tables
[$tName] = $addressJoin;
1001 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1002 $processed[$aName] = 1;
1006 $cond = $elementType = '';
1007 if (strpos($elementName, '-') !== FALSE) {
1008 // this is either phone, email or IM
1009 list($elementName, $elementType) = explode('-', $elementName);
1011 if (($elementName != 'phone') && ($elementName != 'im')) {
1012 $cond = self
::getPrimaryCondition($elementType);
1014 // CRM-13011 : If location type is primary, do not restrict search to the phone
1015 // type id - we want the primary phone, regardless of what type it is.
1016 // Otherwise, restrict to the specified phone type for the given field.
1017 if ((!$cond) && ($elementName == 'phone')) {
1018 $cond = "phone_type_id = '$elementType'";
1020 elseif ((!$cond) && ($elementName == 'im')) {
1021 // IM service provider id, CRM-3140
1022 $cond = "provider_id = '$elementType'";
1024 $elementType = '-' . $elementType;
1027 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
1029 // hack for profile, add location id
1032 // fix for CRM-882( to handle phone types )
1033 !is_numeric($elementType)
1035 if (is_numeric($name)) {
1036 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1039 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1042 elseif (is_numeric($name)) {
1043 //this for phone type to work
1044 if (in_array($elementName, array('phone', 'phone_ext'))) {
1045 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1048 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1052 //this is for phone type to work for profile edit
1053 if (in_array($elementName, array('phone', 'phone_ext'))) {
1054 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1057 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1062 // Check if there is a value, if so also add to where Clause
1064 if ($this->_params
) {
1066 if (isset($locationTypeId)) {
1067 $nm .= "-$locationTypeId";
1069 if (!is_numeric($elementType)) {
1070 $nm .= "$elementType";
1073 foreach ($this->_params
as $id => $values) {
1074 if ((is_array($values) && $values[0] == $nm) ||
1075 (in_array($elementName, array('phone', 'im'))
1076 && (strpos($values[0], $nm) !== FALSE)
1086 if ($field && isset($field['where'])) {
1087 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1088 $pf = substr($tableName, 8);
1089 $tName = $name . '-' . $pf . $elementType;
1090 if (isset($tableName)) {
1091 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1092 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1095 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1098 $this->_element
["{$tName}_id"] = 1;
1099 if (substr($tName, -15) == '-state_province') {
1100 // FIXME: hack to fix CRM-1900
1101 $a = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1105 if (substr_count($a, 'state_province_name') > 0) {
1106 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1107 'pseudoField' => "{$pf}_id",
1108 'idCol' => "{$tName}_id",
1109 'bao' => 'CRM_Core_BAO_Address',
1111 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1114 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1115 'pseudoField' => 'state_province_abbreviation',
1116 'idCol' => "{$tName}_id",
1118 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1122 if (substr($elementFullName, 0, 2) == 'im') {
1123 $provider = "{$name}-{$elementFullName}-provider_id";
1124 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1125 $this->_element
[$provider] = 1;
1127 if ($pf == 'country' ||
$pf == 'county') {
1128 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1129 'pseudoField' => "{$pf}_id",
1130 'idCol' => "{$tName}_id",
1131 'bao' => 'CRM_Core_BAO_Address',
1133 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1136 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1140 if (in_array($pf, array('state_province', 'country', 'county'))) {
1141 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1144 $this->_element
["{$name}-{$elementFullName}"] = 1;
1147 if (empty($processed["`$tName`"])) {
1148 $processed["`$tName`"] = 1;
1149 $newName = $tableName . '_' . $index;
1150 switch ($tableName) {
1151 case 'civicrm_phone':
1152 case 'civicrm_email':
1154 case 'civicrm_openid':
1156 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1157 if ($tableName != 'civicrm_phone') {
1158 $this->_tables
[$tName] .= " AND `$tName`.$lCond";
1160 elseif (is_numeric($name)) {
1161 $this->_select
[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1164 // this special case to add phone type
1166 $phoneTypeCondition = " AND `$tName`.$cond ";
1167 //gross hack to pickup corrupted data also, CRM-7603
1168 if (strpos($cond, 'phone_type_id') !== FALSE) {
1169 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1170 if (!empty($lCond)) {
1171 $phoneTypeCondition .= " AND ( `$tName`.$lCond ) ";
1174 $this->_tables
[$tName] .= $phoneTypeCondition;
1177 //build locationType join
1178 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1181 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1185 case 'civicrm_state_province':
1186 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1187 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1188 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1190 $this->_whereTables
["{$name}-address"] = $addressJoin;
1194 case 'civicrm_country':
1195 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1196 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1197 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1199 $this->_whereTables
["{$name}-address"] = $addressJoin;
1203 case 'civicrm_county':
1204 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1205 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1206 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1208 $this->_whereTables
["{$name}-address"] = $addressJoin;
1214 $this->_whereTables
["{$name}-address"] = $addressJoin;
1223 // add location type join
1224 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1225 $this->_tables
[$locationTypeName] = $ltypeJoin;
1227 // table should be present in $this->_whereTables,
1228 // to add its condition in location type join, CRM-3939.
1229 if ($addWhereCount) {
1230 $locClause = array();
1231 foreach ($this->_whereTables
as $tableName => $clause) {
1232 if (!empty($locationTypeJoin[$tableName])) {
1233 $locClause[] = $locationTypeJoin[$tableName];
1237 if (!empty($locClause)) {
1238 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1243 if (!empty($addressCustomFieldIds)) {
1244 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1245 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1246 foreach ($locTypeName as $name => $dnc) {
1247 $this->_locationSpecificCustomFields
[$cfID] = array($name, array_search($name, $locationTypes));
1248 $fieldName = "$name-custom_{$cfID}";
1249 $tName = "$name-address-custom-{$cfID}";
1250 $aName = "`$name-address-custom-{$cfID}`";
1251 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1252 $this->_element
["{$tName}_id"] = 1;
1253 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1254 $this->_element
[$fieldName] = 1;
1255 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1262 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1264 public function addMultipleElements() {
1265 if (empty($this->_returnProperties
['website'])) {
1268 if (!is_array($this->_returnProperties
['website'])) {
1272 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1273 foreach ($elements as $elementFullName => $dontCare) {
1274 $tName = "website-{$key}-{$elementFullName}";
1275 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1276 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1277 $this->_element
["{$tName}_id"] = 1;
1278 $this->_element
["{$tName}"] = 1;
1280 $type = "website-{$key}-website_type_id";
1281 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1282 $this->_element
[$type] = 1;
1283 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1289 * Generate the query based on what type of query we need.
1291 * @param bool $count
1292 * @param bool $sortByChar
1293 * @param bool $groupContacts
1294 * @param bool $onlyDeleted
1297 * sql query parts as an array
1299 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1300 // build permission clause
1301 $this->generatePermissionClause($onlyDeleted, $count);
1304 if (isset($this->_rowCountClause
)) {
1305 $select = "SELECT {$this->_rowCountClause}";
1307 elseif (isset($this->_distinctComponentClause
)) {
1308 // we add distinct to get the right count for components
1309 // for the more complex result set, we use GROUP BY the same id
1311 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1314 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1316 $from = $this->_simpleFromClause
;
1317 if ($this->_useDistinct
) {
1318 $this->_useGroupBy
= TRUE;
1321 elseif ($sortByChar) {
1322 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1323 $from = $this->_simpleFromClause
;
1325 elseif ($groupContacts) {
1326 $select = 'SELECT contact_a.id as id';
1327 if ($this->_useDistinct
) {
1328 $this->_useGroupBy
= TRUE;
1330 $from = $this->_simpleFromClause
;
1333 if (!empty($this->_paramLookup
['group'])) {
1334 // make sure there is only one element
1335 // this is used when we are running under smog and need to know
1336 // how the contact was added (CRM-1203)
1337 if ((count($this->_paramLookup
['group']) == 1) &&
1338 (count($this->_paramLookup
['group'][0][2]) == 1)
1340 $groups = array_keys($this->_paramLookup
['group'][0][2]);
1341 $groupId = $groups[0];
1343 //check if group is saved search
1344 $group = new CRM_Contact_BAO_Group();
1345 $group->id
= $groupId;
1348 if (!isset($group->saved_search_id
)) {
1349 $tbName = "`civicrm_group_contact-{$groupId}`";
1350 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1351 $this->_element
['group_contact_id'] = 1;
1352 $this->_select
['status'] = "$tbName.status as status";
1353 $this->_element
['status'] = 1;
1356 $this->_useGroupBy
= TRUE;
1358 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1359 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1361 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1362 $this->_useDistinct
= FALSE;
1363 $this->_useGroupBy
= TRUE;
1367 $select = "SELECT ";
1368 if (isset($this->_distinctComponentClause
)) {
1369 $select .= "{$this->_distinctComponentClause}, ";
1371 $select .= implode(', ', $this->_select
);
1372 $from = $this->_fromClause
;
1376 if (!empty($this->_whereClause
)) {
1377 $where = "WHERE {$this->_whereClause}";
1380 if (!empty($this->_permissionWhereClause
) && empty($this->_displayRelationshipType
)) {
1381 if (empty($where)) {
1382 $where = "WHERE $this->_permissionWhereClause";
1385 $where = "$where AND $this->_permissionWhereClause";
1390 if (!empty($this->_having
)) {
1391 foreach ($this->_having
as $havingSets) {
1392 foreach ($havingSets as $havingSet) {
1393 $havingValue[] = $havingSet;
1396 $having = ' HAVING ' . implode(' AND ', $havingValue);
1399 // if we are doing a transform, do it here
1400 // use the $from, $where and $having to get the contact ID
1401 if ($this->_displayRelationshipType
) {
1402 $this->filterRelatedContacts($from, $where, $having);
1405 return array($select, $from, $where, $having);
1409 * Get where values from the parameters.
1411 * @param string $name
1412 * @param mixed $grouping
1416 public function getWhereValues($name, $grouping) {
1418 foreach ($this->_params
as $values) {
1419 if ($values[0] == $name && $values[3] == $grouping) {
1430 * @param bool $relative
1431 * @param string $from
1434 public static function fixDateValues($relative, &$from, &$to) {
1436 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1441 * Convert values from form-appropriate to query-object appropriate.
1443 * The query object is increasingly supporting the sql-filter syntax which is the most flexible syntax.
1444 * So, ideally we would convert all fields to look like
1447 * // Set the operator for legacy reasons, but it is ignored
1449 * // array in sql filter syntax
1450 * 2 => array('BETWEEN' => array(1,60),
1455 * There are some examples of the syntax in
1456 * https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples/Relationship
1458 * More notes at CRM_Core_DAO::createSQLFilter
1460 * and a list of supported operators in CRM_Core_DAO
1462 * @param array $formValues
1463 * @param int $wildcard
1464 * @param bool $useEquals
1466 * @param string $apiEntity
1470 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1472 if (empty($formValues)) {
1476 foreach ($formValues as $id => $values) {
1478 if (self
::isAlreadyProcessedForQueryFormat($values)) {
1479 $params[] = $values;
1483 self
::legacyConvertFormValues($id, $values);
1485 if ($id == 'privacy') {
1486 if (is_array($formValues['privacy'])) {
1487 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1488 foreach ($formValues['privacy'] as $key => $value) {
1490 $params[] = array($key, $op, $value, 0, 0);
1495 elseif ($id == 'email_on_hold') {
1496 if ($formValues['email_on_hold']['on_hold']) {
1497 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1500 elseif (substr($id, 0, 7) == 'custom_'
1502 substr($id, -9, 9) == '_relative'
1503 ||
substr($id, -5, 5) == '_from'
1504 ||
substr($id, -3, 3) == '_to'
1507 self
::convertCustomRelativeFields($formValues, $params, $values, $id);
1509 elseif (!empty($values) && !is_array($values) && self
::isCustomDateField($id)) {
1510 $params[] = array($id, '=', CRM_Utils_Date
::processDate($values), 0, $wildcard);
1512 elseif (preg_match('/_date_relative$/', $id) ||
1513 $id == 'event_relative' ||
1514 $id == 'case_from_relative' ||
1515 $id == 'case_to_relative'
1517 if ($id == 'event_relative') {
1518 $fromRange = 'event_start_date_low';
1519 $toRange = 'event_end_date_high';
1521 elseif ($id == 'case_from_relative') {
1522 $fromRange = 'case_from_start_date_low';
1523 $toRange = 'case_from_start_date_high';
1525 elseif ($id == 'case_to_relative') {
1526 $fromRange = 'case_to_end_date_low';
1527 $toRange = 'case_to_end_date_high';
1530 $dateComponent = explode('_date_relative', $id);
1531 $fromRange = "{$dateComponent[0]}_date_low";
1532 $toRange = "{$dateComponent[0]}_date_high";
1535 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1536 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1541 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
1546 $params[] = $values;
1553 * Function to support legacy format for groups and tags.
1556 * @param array|int $values
1559 public static function legacyConvertFormValues($id, &$values) {
1560 $legacyElements = array(
1563 'membership_type_id',
1564 'membership_status_id',
1566 if (in_array($id, $legacyElements) && is_array($values)) {
1567 // prior to 4.6, formValues for some attributes (e.g. group, tag) are stored in array(id1 => 1, id2 => 1),
1568 // as per the recent Search fixes $values need to be in standard array(id1, id2) format
1569 $values = CRM_Utils_Array
::convertCheckboxFormatToArray($values);
1575 * @param array $values
1576 * @param int $wildcard
1577 * @param bool $useEquals
1579 * @param string $apiEntity
1581 * @return array|null
1583 public static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1584 // skip a few search variables
1585 static $skipWhere = NULL;
1586 static $likeNames = NULL;
1588 // Change camelCase EntityName to lowercase with underscores
1589 $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity);
1591 if (CRM_Utils_System
::isNull($values)) {
1603 'display_relationship_type',
1607 if (in_array($id, $skipWhere) ||
1608 substr($id, 0, 4) == '_qf_' ||
1609 substr($id, 0, 7) == 'hidden_'
1615 (substr($id, 0, strlen($apiEntity)) != $apiEntity) &&
1616 (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_')
1618 $id = $apiEntity . '_' . $id;
1622 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1625 // email comes in via advanced search
1626 // so use wildcard always
1627 if ($id == 'email') {
1631 if (!$useEquals && in_array($id, $likeNames)) {
1632 $result = array($id, 'LIKE', $values, 0, 1);
1634 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1635 $result = array($id, 'LIKE', $values, 0, 0);
1637 elseif ($id == 'group') {
1638 if (is_array($values)) {
1639 foreach ($values as $groupIds => $val) {
1641 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1642 if (strlen($matches[1]) > 0) {
1643 $values[$matches[1]] = 1;
1644 unset($values[$groupIds]);
1650 $groupIds = explode(',', $values);
1652 foreach ($groupIds as $groupId) {
1653 $values[$groupId] = 1;
1657 $result = array($id, 'IN', $values, 0, 0);
1659 elseif ($id == 'contact_tags' ||
$id == 'tag') {
1660 if (!is_array($values)) {
1661 $tagIds = explode(',', $values);
1663 foreach ($tagIds as $tagId) {
1664 $values[$tagId] = 1;
1667 $result = array($id, 'IN', $values, 0, 0);
1669 elseif ($id == 'contact_type' ||
1670 (!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO
::acceptedSQLOperators(), TRUE))
1672 $result = array($id, 'IN', $values, 0, $wildcard);
1675 $result = array($id, '=', $values, 0, $wildcard);
1682 * Get the where clause for a single field.
1684 * @param array $values
1686 public function whereClauseSingle(&$values) {
1687 // do not process custom fields or prefixed contact ids or component params
1688 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1689 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1690 (substr($values[0], 0, 13) == 'contribution_') ||
1691 (substr($values[0], 0, 6) == 'event_') ||
1692 (substr($values[0], 0, 12) == 'participant_') ||
1693 (substr($values[0], 0, 7) == 'member_') ||
1694 (substr($values[0], 0, 6) == 'grant_') ||
1695 (substr($values[0], 0, 7) == 'pledge_') ||
1696 (substr($values[0], 0, 5) == 'case_') ||
1697 (substr($values[0], 0, 10) == 'financial_') ||
1698 (substr($values[0], 0, 8) == 'payment_') ||
1699 (substr($values[0], 0, 11) == 'membership_')
1704 // skip for hook injected fields / params
1705 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1706 if (array_key_exists($values[0], $extFields)) {
1710 switch ($values[0]) {
1711 case 'deleted_contacts':
1712 $this->deletedContacts($values);
1715 case 'contact_type':
1716 $this->contactType($values);
1719 case 'contact_sub_type':
1720 $this->contactSubType($values);
1724 $this->group($values);
1728 // so we resolve this into a list of groups & proceed as if they had been
1730 list($name, $op, $value, $grouping, $wildcard) = $values;
1731 $values[0] = 'group';
1733 $this->_paramLookup
['group'][0][0] = 'group';
1734 $this->_paramLookup
['group'][0][1] = 'IN';
1735 $this->_paramLookup
['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1736 $this->group($values);
1739 // case tag comes from find contacts
1741 $this->tagSearch($values);
1745 case 'contact_tags':
1746 $this->tag($values);
1751 case 'note_subject':
1752 $this->notes($values);
1756 $this->ufUser($values);
1760 case 'display_name':
1761 $this->sortName($values);
1765 case 'postal_greeting':
1766 case 'email_greeting':
1767 $this->greetings($values);
1771 $this->email($values);
1774 case 'phone_numeric':
1775 $this->phone_numeric($values);
1778 case 'phone_phone_type_id':
1779 case 'phone_location_type_id':
1780 $this->phone_option_group($values);
1783 case 'street_address':
1784 $this->street_address($values);
1787 case 'street_number':
1788 $this->street_number($values);
1791 case 'sortByCharacter':
1792 $this->sortByCharacter($values);
1795 case 'location_type':
1796 $this->locationType($values);
1800 $this->county($values);
1803 case 'state_province':
1804 case 'state_province_id':
1805 case 'state_province_name':
1806 $this->stateProvince($values);
1811 $this->country($values, FALSE);
1815 case 'postal_code_low':
1816 case 'postal_code_high':
1817 $this->postalCode($values);
1820 case 'activity_date':
1821 case 'activity_date_low':
1822 case 'activity_date_high':
1823 case 'activity_role':
1824 case 'activity_status_id':
1825 case 'activity_status':
1826 case 'followup_parent_id':
1828 case 'source_contact_id':
1829 case 'activity_subject':
1830 case 'test_activities':
1831 case 'activity_type_id':
1832 case 'activity_type':
1833 case 'activity_survey_id':
1834 case 'activity_tags':
1835 case 'activity_taglist':
1836 case 'activity_test':
1837 case 'activity_campaign_id':
1838 case 'activity_engagement_level':
1840 case 'activity_result':
1841 case 'source_contact':
1842 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1845 case 'birth_date_low':
1846 case 'birth_date_high':
1847 case 'deceased_date_low':
1848 case 'deceased_date_high':
1849 $this->demographics($values);
1852 case 'log_date_low':
1853 case 'log_date_high':
1854 $this->modifiedDates($values);
1858 $this->changeLog($values);
1861 case 'do_not_phone':
1862 case 'do_not_email':
1865 case 'do_not_trade':
1867 $this->privacy($values);
1870 case 'privacy_options':
1871 $this->privacyOptions($values);
1874 case 'privacy_operator':
1875 case 'privacy_toggle':
1876 // these are handled by privacy options
1879 case 'preferred_communication_method':
1880 $this->preferredCommunication($values);
1883 case 'relation_type_id':
1884 case 'relation_start_date_high':
1885 case 'relation_start_date_low':
1886 case 'relation_end_date_high':
1887 case 'relation_end_date_low':
1888 case 'relation_target_name':
1889 case 'relation_status':
1890 case 'relation_date_low':
1891 case 'relation_date_high':
1892 $this->relationship($values);
1893 $this->_relationshipValuesAdded
= TRUE;
1896 case 'task_status_id':
1897 $this->task($values);
1901 // since this case is handled with the above
1904 case 'prox_distance':
1905 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1908 case 'prox_street_address':
1910 case 'prox_postal_code':
1911 case 'prox_state_province_id':
1912 case 'prox_country_id':
1913 // handled by the proximity_distance clause
1917 $this->restWhere($values);
1923 * Given a list of conditions in params generate the required where clause.
1927 public function whereClause() {
1928 $this->_where
[0] = array();
1929 $this->_qill
[0] = array();
1931 $this->includeContactIds();
1932 if (!empty($this->_params
)) {
1933 foreach (array_keys($this->_params
) as $id) {
1934 if (empty($this->_params
[$id][0])) {
1937 // check for both id and contact_id
1938 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
1939 $this->_where
[0][] = self
::buildClause("contact_a.id", $this->_params
[$id][1], $this->_params
[$id][2]);
1942 $this->whereClauseSingle($this->_params
[$id]);
1946 CRM_Core_Component
::alterQuery($this, 'where');
1948 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
1951 if ($this->_customQuery
) {
1952 // Added following if condition to avoid the wrong value display for 'my account' / any UF info.
1953 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1954 if (!empty($this->_customQuery
->_where
)) {
1955 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
1958 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
1962 $andClauses = array();
1965 if (!empty($this->_where
)) {
1966 foreach ($this->_where
as $grouping => $values) {
1967 if ($grouping > 0 && !empty($values)) {
1968 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1973 if (!empty($this->_where
[0])) {
1974 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
1976 if (!empty($clauses)) {
1977 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1980 if ($validClauses > 1) {
1981 $this->_useDistinct
= TRUE;
1985 return implode(' AND ', $andClauses);
1989 * Generate where clause for any parameters not already handled.
1991 * @param array $values
1995 public function restWhere(&$values) {
1996 $name = CRM_Utils_Array
::value(0, $values);
1997 $op = CRM_Utils_Array
::value(1, $values);
1998 $value = CRM_Utils_Array
::value(2, $values);
1999 $grouping = CRM_Utils_Array
::value(3, $values);
2000 $wildcard = CRM_Utils_Array
::value(4, $values);
2002 if (isset($grouping) && empty($this->_where
[$grouping])) {
2003 $this->_where
[$grouping] = array();
2006 $multipleFields = array('url');
2008 //check if the location type exists for fields
2010 $locType = explode('-', $name);
2012 if (!in_array($locType[0], $multipleFields)) {
2013 //add phone type if exists
2014 if (isset($locType[2]) && $locType[2]) {
2015 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
2019 $field = CRM_Utils_Array
::value($name, $this->_fields
);
2022 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
2031 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2032 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2034 if (substr($name, 0, 14) === 'state_province') {
2035 if (isset($locType[1]) && is_numeric($locType[1])) {
2037 $aName = "{$locationType[$locType[1]]}-address";
2038 $where = "`$aName`.state_province_id";
2041 $where = "civicrm_address.state_province_id";
2044 $states = CRM_Core_PseudoConstant
::stateProvince();
2045 if (is_numeric($value)) {
2046 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2047 $value = $states[(int ) $value];
2050 $intVal = CRM_Utils_Array
::key($value, $states);
2051 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
2054 $this->_qill
[$grouping][] = ts('State') . " $op '$value'";
2057 $this->_qill
[$grouping][] = ts('State') . " ($lType) $op '$value'";
2060 elseif (!empty($field['pseudoconstant'])) {
2061 $this->optionValueQuery(
2062 $name, $op, $value, $grouping,
2063 CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', $field['name']),
2069 if ($name == 'gender_id') {
2070 self
::$_openedPanes[ts('Demographics')] = TRUE;
2073 elseif (substr($name, 0, 7) === 'country') {
2074 if (isset($locType[1]) && is_numeric($locType[1])) {
2076 $aName = "{$locationType[$locType[1]]}-address";
2077 $where = "`$aName`.country_id";
2080 $where = "civicrm_address.country_id";
2083 $countries = CRM_Core_PseudoConstant
::country();
2084 if (is_numeric($value)) {
2085 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2086 $value = $countries[(int ) $value];
2089 $intVal = CRM_Utils_Array
::key($value, $countries);
2090 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
2094 $this->_qill
[$grouping][] = ts('Country') . " $op '$value'";
2097 $this->_qill
[$grouping][] = ts('Country') . " ($lType) $op '$value'";
2100 elseif (substr($name, 0, 6) === 'county') {
2101 if (isset($locType[1]) && is_numeric($locType[1])) {
2103 $aName = "{$locationType[$locType[1]]}-address";
2104 $where = "`$aName`.county_id";
2107 $where = "civicrm_address.county_id";
2110 $counties = CRM_Core_PseudoConstant
::county();
2111 if (is_numeric($value)) {
2112 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2113 $value = $counties[(int ) $value];
2116 $intVal = CRM_Utils_Array
::key($value, $counties);
2117 $this->_where
[$grouping][] = self
::buildClause($where, $op, $intVal, 'Positive');
2121 $this->_qill
[$grouping][] = ts('County') . " $op '$value'";
2124 $this->_qill
[$grouping][] = ts('County') . " ($lType) $op '$value'";
2127 elseif ($name === 'world_region') {
2128 $field['where'] = 'civicrm_worldregion.id';
2129 $this->optionValueQuery(
2130 $name, $op, $value, $grouping,
2131 CRM_Core_PseudoConstant
::worldRegion(),
2138 elseif ($name === 'is_deceased') {
2139 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
2140 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2141 self
::$_openedPanes[ts('Demographics')] = TRUE;
2143 elseif ($name === 'created_date' ||
$name === 'modified_date' ||
$name === 'deceased_date' ||
$name === 'birth_date') {
2144 $appendDateTime = TRUE;
2145 if ($name === 'deceased_date' ||
$name === 'birth_date') {
2146 $appendDateTime = FALSE;
2147 self
::$_openedPanes[ts('Demographics')] = TRUE;
2149 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2151 elseif ($name === 'contact_id') {
2152 if (is_int($value)) {
2153 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2154 $this->_qill
[$grouping][] = "$field[title] $op $value";
2157 elseif ($name === 'name') {
2158 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2160 $value = "%$value%";
2163 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
2164 $this->_where
[$grouping][] = self
::buildClause($wc, $op, "'$value'");
2165 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2167 elseif ($name === 'current_employer') {
2168 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2170 $value = "%$value%";
2173 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.organization_name)" : "contact_a.organization_name";
2174 $ceWhereClause = self
::buildClause($wc, $op,
2177 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2178 $this->_where
[$grouping][] = $ceWhereClause;
2179 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2181 elseif ($name === 'email_greeting') {
2182 $filterCondition = array('greeting_type' => 'email_greeting');
2183 $this->optionValueQuery(
2184 $name, $op, $value, $grouping,
2185 CRM_Core_PseudoConstant
::greeting($filterCondition),
2187 ts('Email Greeting')
2190 elseif ($name === 'postal_greeting') {
2191 $filterCondition = array('greeting_type' => 'postal_greeting');
2192 $this->optionValueQuery(
2193 $name, $op, $value, $grouping,
2194 CRM_Core_PseudoConstant
::greeting($filterCondition),
2196 ts('Postal Greeting')
2199 elseif ($name === 'addressee') {
2200 $filterCondition = array('greeting_type' => 'addressee');
2201 $this->optionValueQuery(
2202 $name, $op, $value, $grouping,
2203 CRM_Core_PseudoConstant
::greeting($filterCondition),
2208 elseif (substr($name, 0, 4) === 'url-') {
2209 $tName = 'civicrm_website';
2210 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2211 $value = $strtolower(CRM_Core_DAO
::escapeString($value));
2213 $value = "%$value%";
2217 $wc = 'civicrm_website.url';
2218 $this->_where
[$grouping][] = $d = self
::buildClause($wc, $op, $value);
2219 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2221 elseif ($name === 'contact_is_deleted') {
2222 $this->_where
[$grouping][] = self
::buildClause("contact_a.is_deleted", $op, $value);
2223 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2225 elseif (!empty($field['where'])) {
2227 if (!empty($field['type'])) {
2228 $type = CRM_Utils_Type
::typeToString($field['type']);
2231 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2233 if (isset($locType[1]) &&
2234 is_numeric($locType[1])
2238 //get the location name
2239 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2241 $fieldName = "LOWER(`$tName`.$fldName)";
2243 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2244 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2248 if ($tableName == 'civicrm_contact') {
2249 $fieldName = "LOWER(contact_a.{$fieldName})";
2252 if ($op != 'IN' && !is_numeric($value)) {
2253 $fieldName = "LOWER({$field['where']})";
2256 $fieldName = "{$field['where']}";
2261 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2262 $this->_qill
[$grouping][] = "$field[title] $qillop '$qillVal'";
2264 if (is_array($value)) {
2265 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2266 // for api style operators for functions that hit this point without worrying about regression
2267 // (the previous comments indicated the condition for hitting this point were unknown
2268 // per CRM-14743 we are adding modified_date & created_date operator support
2269 $operations = array_keys($value);
2270 foreach ($operations as $operator) {
2271 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2272 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2273 //so this condition will satisfy the search for now
2274 if (strpos($op, 'IN') !== FALSE) {
2275 $value = array($op => $value);
2277 // we don't know when this might happen
2279 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $operator)));
2283 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($fieldName, $value, $type);
2287 $value = $strtolower($value);
2290 $value = "%$value%";
2294 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2298 if ($setTables && isset($field['where'])) {
2299 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2300 if (isset($tableName)) {
2301 $this->_tables
[$tableName] = 1;
2302 $this->_whereTables
[$tableName] = 1;
2315 public static function getLocationTableName(&$where, &$locType) {
2316 if (isset($locType[1]) && is_numeric($locType[1])) {
2317 list($tbName, $fldName) = explode(".", $where);
2319 //get the location name
2320 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
2321 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2322 if (in_array($locType[0], $specialFields)) {
2323 //hack to fix / special handing for phone_ext
2324 if ($locType[0] == 'phone_ext') {
2325 $locType[0] = 'phone';
2327 if (isset($locType[2]) && $locType[2]) {
2328 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2331 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2334 elseif (in_array($locType[0],
2338 'supplemental_address_1',
2339 'supplemental_address_2',
2342 'postal_code_suffix',
2347 //fix for search by profile with address fields.
2348 $tName = "{$locationType[$locType[1]]}-address";
2350 elseif ($locType[0] == 'on_hold') {
2351 $tName = "{$locationType[$locType[1]]}-email";
2354 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2356 $tName = str_replace(' ', '_', $tName);
2357 return array($tName, $fldName);
2359 CRM_Core_Error
::fatal();
2363 * Given a result dao, extract the values and return that array
2365 * @param CRM_Core_DAO $dao
2368 * values for this query
2370 public function store($dao) {
2373 foreach ($this->_element
as $key => $dontCare) {
2374 if (property_exists($dao, $key)) {
2375 if (strpos($key, '-') !== FALSE) {
2376 $values = explode('-', $key);
2377 $lastElement = array_pop($values);
2379 $cnt = count($values);
2381 foreach ($values as $v) {
2382 if (!array_key_exists($v, $current)) {
2383 $current[$v] = array();
2385 //bad hack for im_provider
2386 if ($lastElement == 'provider_id') {
2387 if ($count < $cnt) {
2388 $current = &$current[$v];
2391 $lastElement = "{$v}_{$lastElement}";
2395 $current = &$current[$v];
2400 $current[$lastElement] = $dao->$key;
2403 $value[$key] = $dao->$key;
2411 * Getter for tables array.
2415 public function tables() {
2416 return $this->_tables
;
2420 * Where tables is sometimes used to create the from clause, but, not reliably, set this AND set tables
2421 * It's unclear the intent - there is a 'simpleFrom' clause which takes whereTables into account & a fromClause which doesn't
2422 * logic may have eroded
2425 public function whereTables() {
2426 return $this->_whereTables
;
2430 * Generate the where clause (used in match contacts and permissions)
2432 * @param array $params
2433 * @param array $fields
2434 * @param array $tables
2435 * @param $whereTables
2436 * @param bool $strict
2440 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2441 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2445 $tables = array_merge($query->tables(), $tables);
2446 $whereTables = array_merge($query->whereTables(), $whereTables);
2448 return $query->_whereClause
;
2452 * Create the from clause.
2454 * @param array $tables
2455 * Tables that need to be included in this from clause.
2456 * if null, return mimimal from clause (i.e. civicrm_contact)
2457 * @param array $inner
2458 * Tables that should be inner-joined.
2459 * @param array $right
2460 * Tables that should be right-joined.
2462 * @param bool $primaryLocation
2468 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2470 $from = ' FROM civicrm_contact contact_a';
2471 if (empty($tables)) {
2475 if (!empty($tables['civicrm_worldregion'])) {
2476 $tables = array_merge(array('civicrm_country' => 1), $tables);
2479 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2480 CRM_Utils_Array
::value('civicrm_county', $tables)
2481 ) && empty($tables['civicrm_address'])
2483 $tables = array_merge(array('civicrm_address' => 1),
2488 // add group_contact and group_contact_cache table if group table is present
2489 if (!empty($tables['civicrm_group'])) {
2490 if (empty($tables['civicrm_group_contact'])) {
2491 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added' ";
2493 if (empty($tables['civicrm_group_contact_cache'])) {
2494 $tables['civicrm_group_contact_cache'] = " LEFT JOIN civicrm_group_contact_cache ON civicrm_group_contact_cache.contact_id = contact_a.id ";
2498 // add group_contact and group table is subscription history is present
2499 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2500 $tables = array_merge(array(
2501 'civicrm_group' => 1,
2502 'civicrm_group_contact' => 1,
2508 // to handle table dependencies of components
2509 CRM_Core_Component
::tableNames($tables);
2510 // to handle table dependencies of hook injected tables
2511 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2513 //format the table list according to the weight
2514 $info = CRM_Core_TableHierarchy
::info();
2516 foreach ($tables as $key => $value) {
2518 if (strpos($key, '-') !== FALSE) {
2519 $keyArray = explode('-', $key);
2520 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2522 elseif (strpos($key, '_') !== FALSE) {
2523 $keyArray = explode('_', $key);
2524 if (is_numeric(array_pop($keyArray))) {
2525 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2528 $k = CRM_Utils_Array
::value($key, $info, 99);
2532 $k = CRM_Utils_Array
::value($key, $info, 99);
2534 $tempTable[$k . ".$key"] = $key;
2537 $newTables = array();
2538 foreach ($tempTable as $key) {
2539 $newTables[$key] = $tables[$key];
2542 $tables = $newTables;
2544 foreach ($tables as $name => $value) {
2549 if (!empty($inner[$name])) {
2552 elseif (!empty($right[$name])) {
2560 // if there is already a join statement in value, use value itself
2561 if (strpos($value, 'JOIN')) {
2562 $from .= " $value ";
2565 $from .= " $side JOIN $name ON ( $value ) ";
2570 case 'civicrm_address':
2571 if ($primaryLocation) {
2572 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2575 //CRM-14263 further handling of address joins further down...
2576 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2580 case 'civicrm_phone':
2581 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2584 case 'civicrm_email':
2585 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2589 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2593 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2594 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2595 $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)";
2598 case 'civicrm_openid':
2599 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2602 case 'civicrm_worldregion':
2603 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2604 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2607 case 'civicrm_location_type':
2608 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2611 case 'civicrm_group':
2612 $from .= " $side JOIN civicrm_group ON (civicrm_group.id = civicrm_group_contact.group_id OR civicrm_group.id = civicrm_group_contact_cache.group_id) ";
2615 case 'civicrm_group_contact':
2616 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2619 case 'civicrm_group_contact_cache':
2620 $from .= " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
2623 case 'civicrm_activity':
2624 case 'civicrm_activity_tag':
2625 case 'activity_type':
2626 case 'activity_status':
2628 case 'civicrm_activity_contact':
2629 case 'source_contact':
2630 $from .= CRM_Activity_BAO_Query
::from($name, $mode, $side);
2633 case 'civicrm_entity_tag':
2634 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2635 civicrm_entity_tag.entity_id = contact_a.id ) ";
2638 case 'civicrm_note':
2639 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2640 contact_a.id = civicrm_note.entity_id ) ";
2643 case 'civicrm_subscription_history':
2644 $from .= " $side JOIN civicrm_subscription_history
2645 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2646 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2649 case 'civicrm_relationship':
2650 if (self
::$_relType == 'reciprocal') {
2651 if (self
::$_relationshipTempTable) {
2652 // we have a temptable to join on
2653 $tbl = self
::$_relationshipTempTable;
2654 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2657 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2658 $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)";
2661 elseif (self
::$_relType == 'b') {
2662 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2663 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2666 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2667 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2672 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2673 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2677 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2680 case 'civicrm_grant':
2681 $from .= CRM_Grant_BAO_Query
::from($name, $mode, $side);
2684 case 'civicrm_website':
2685 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2689 $locationTypeName = '';
2690 if (strpos($name, '-address') != 0) {
2691 $locationTypeName = 'address';
2693 elseif (strpos($name, '-phone') != 0) {
2694 $locationTypeName = 'phone';
2696 elseif (strpos($name, '-email') != 0) {
2697 $locationTypeName = 'email';
2699 if ($locationTypeName) {
2700 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2701 $parts = explode('-', $name);
2702 $locationID = array_search($parts[0], CRM_Core_BAO_Address
::buildOptions('location_type_id', 'get', array('name' => $parts[0])));
2703 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2706 $from .= CRM_Core_Component
::from($name, $mode, $side);
2708 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2717 * WHERE / QILL clause for deleted_contacts
2719 * @param array $values
2721 public function deletedContacts($values) {
2722 list($_, $_, $value, $grouping, $_) = $values;
2724 // *prepend* to the relevant grouping as this is quite an important factor
2725 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2730 * Where / qill clause for contact_type
2734 public function contactType(&$values) {
2735 list($name, $op, $value, $grouping, $wildcard) = $values;
2737 $subTypes = array();
2740 // account for search builder mapping multiple values
2741 if (!is_array($value)) {
2742 $values = self
::parseSearchBuilderString($value, 'String');
2743 if (is_array($values)) {
2744 $value = array_flip($values);
2748 if (is_array($value)) {
2749 foreach ($value as $k => $v) {
2754 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2755 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2758 if (!empty($subType)) {
2759 $subTypes[$subType] = 1;
2761 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2766 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2767 $contactType = $contactTypeANDSubType[0];
2768 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2769 if (!empty($subType)) {
2770 $subTypes[$subType] = 1;
2772 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2776 if (!empty($clause)) {
2778 if ($op == 'IN' ||
$op == 'NOT IN') {
2779 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2782 $type = array_pop($clause);
2783 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2786 $this->_qill
[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2788 if (!empty($subTypes)) {
2789 $this->includeContactSubTypes($subTypes, $grouping);
2795 * Where / qill clause for contact_sub_type
2799 public function contactSubType(&$values) {
2800 list($name, $op, $value, $grouping, $wildcard) = $values;
2801 $this->includeContactSubTypes($value, $grouping, $op);
2809 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2812 $alias = "contact_a.contact_sub_type";
2813 $qillOperators = array('NOT LIKE' => ts('Not Like')) + CRM_Core_SelectValues
::getSearchBuilderOperators();
2815 $op = str_replace('IN', 'LIKE', $op);
2816 $op = str_replace('=', 'LIKE', $op);
2817 $op = str_replace('!', 'NOT ', $op);
2819 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2820 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
2822 elseif (is_array($value)) {
2823 foreach ($value as $k => $v) {
2825 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($k, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2830 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2833 if (!empty($clause)) {
2834 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2836 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', array(1 => $qillOperators[$op])) . implode(' ' . ts('or') . ' ', array_keys($clause));
2840 * Where / qill clause for groups
2844 public function group(&$values) {
2845 list($name, $op, $value, $grouping, $wildcard) = $values;
2847 // Replace pseudo operators from search builder
2848 $op = str_replace('EMPTY', 'NULL', $op);
2850 if (count($value) > 1) {
2851 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
2852 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $op)));
2854 $this->_useDistinct
= TRUE;
2860 $isNotOp = ($op == 'NOT IN' ||
$op == '!=');
2863 if (strpos($op, 'IN') === FALSE) {
2864 $value = key($value);
2867 $value = array_keys($value);
2872 $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
2874 is_array($gcsValues[2])
2876 foreach ($gcsValues[2] as $k => $v) {
2878 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2883 $statii[] = '"Added"';
2887 if (!is_array($value) &&
2888 count($statii) == 1 &&
2889 $statii[0] == '"Added"' &&
2892 if (!empty($value) && CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $value, 'saved_search_id')) {
2897 $ssClause = $this->addGroupContactCache($value, NULL, "contact_a", $op);
2898 $isSmart = (!$ssClause) ?
FALSE : $isSmart;
2899 $groupClause = NULL;
2902 $groupIds = implode(',', (array) $value);
2903 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2904 $joinClause = array("contact_a.id = {$gcTable}.contact_id");
2906 $joinClause[] = "{$gcTable}.status IN (" . implode(', ', $statii) . ")";
2908 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
2909 $groupClause = "{$gcTable}.group_id $op $groupIds";
2910 if (strpos($op, 'IN') !== FALSE) {
2911 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2916 $and = ($op == 'IS NULL') ?
'AND' : 'OR';
2918 $groupClause = "( ( $groupClause ) $and ( $ssClause ) )";
2921 $groupClause = $ssClause;
2925 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
2926 $this->_qill
[$grouping][] = ts("Group(s) %1 %2", array(1 => $qillop, 2 => $qillVal));
2927 if (strpos($op, 'NULL') === FALSE) {
2928 $this->_qill
[$grouping][] = ts("Group Status %1", array(1 => implode(' ' . ts('or') . ' ', $statii)));
2931 $this->_where
[$grouping][] = $groupClause;
2936 * Function translates selection of group type into a list of groups.
2941 public function getGroupsFromTypeCriteria($value) {
2942 $groupIds = array();
2943 foreach ((array) $value as $groupTypeValue) {
2944 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
2945 $groupIds = ($groupIds +
$groupList);
2951 * @param array $groups
2952 * @param string $tableAlias
2953 * @param string $joinTable
2956 * @return null|string
2958 public function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a", $op) {
2959 $isNullOp = (strpos($op, 'NULL') !== FALSE);
2960 $groupsIds = $groups;
2961 if (!$isNullOp && !$groups) {
2964 elseif (strpos($op, 'IN') !== FALSE) {
2965 $groups = array($op => $groups);
2967 elseif (is_array($groups) && count($groups)) {
2968 $groups = array('IN' => $groups);
2971 // Find all the groups that are part of a saved search.
2972 $smartGroupClause = self
::buildClause("id", $op, $groups, 'Int');
2974 SELECT id, cache_date, saved_search_id, children
2976 WHERE $smartGroupClause
2977 AND ( saved_search_id != 0
2978 OR saved_search_id IS NOT NULL
2979 OR children IS NOT NULL )
2982 $group = CRM_Core_DAO
::executeQuery($sql);
2984 while ($group->fetch()) {
2985 $this->_useDistinct
= TRUE;
2986 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
2987 CRM_Contact_BAO_GroupContactCache
::load($group);
2992 $tableAlias = "`civicrm_group_contact_cache_";
2993 $tableAlias .= ($isNullOp) ?
"a`" : implode(',', (array) $groupsIds) . "`";
2996 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.id = {$tableAlias}.contact_id ";
2997 return self
::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
3001 * Where / qill clause for cms users
3005 public function ufUser(&$values) {
3006 list($name, $op, $value, $grouping, $wildcard) = $values;
3009 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3011 $this->_qill
[$grouping][] = ts('CMS User');
3013 elseif ($value == 0) {
3014 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3016 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3017 $this->_qill
[$grouping][] = ts('Not a CMS User');
3022 * All tag search specific.
3024 * @param array $values
3026 public function tagSearch(&$values) {
3027 list($name, $op, $value, $grouping, $wildcard) = $values;
3030 $value = "%{$value}%";
3032 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3033 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3035 $etTable = "`civicrm_entity_tag-" . $value . "`";
3036 $tTable = "`civicrm_tag-" . $value . "`";
3038 if ($useAllTagTypes[2]) {
3039 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3040 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3041 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3043 // search tag in cases
3044 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3045 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
3046 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3047 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3048 LEFT JOIN civicrm_case
3049 ON (civicrm_case_contact.case_id = civicrm_case.id
3050 AND civicrm_case.is_deleted = 0 )
3051 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3052 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3053 // search tag in activities
3054 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3055 $tActTable = "`civicrm_act_tag-" . $value . "`";
3056 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3057 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3059 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3060 = " LEFT JOIN civicrm_activity_contact
3061 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3062 LEFT JOIN civicrm_activity
3063 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3064 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3065 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3066 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3068 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $value . "' OR {$tCaseTable}.name $op '" . $value . "' OR {$tActTable}.name $op '" . $value . "')";
3069 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
3072 $etTable = "`civicrm_entity_tag-" . $value . "`";
3073 $tTable = "`civicrm_tag-" . $value . "`";
3074 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3075 {$etTable}.entity_table = 'civicrm_contact' )
3076 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3078 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3079 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
3084 * Where / qill clause for tag
3086 * @param array $values
3088 public function tag(&$values) {
3089 list($name, $op, $value, $grouping, $wildcard) = $values;
3091 $tagNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
3092 if (is_array($value)) {
3093 if (count($value) > 1) {
3094 $this->_useDistinct
= TRUE;
3096 foreach ($value as $id => $dontCare) {
3097 $names[] = CRM_Utils_Array
::value($id, $tagNames);
3099 $names = implode(' ' . ts('or') . ' ', $names);
3100 $value = implode(',', array_keys($value));
3103 $names = CRM_Utils_Array
::value($value, $tagNames);
3106 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3107 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3109 $etTable = "`civicrm_entity_tag-" . $value . "`";
3111 if ($useAllTagTypes[2]) {
3112 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3113 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3115 // search tag in cases
3116 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3117 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3118 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3120 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3121 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3122 LEFT JOIN civicrm_case
3123 ON (civicrm_case_contact.case_id = civicrm_case.id
3124 AND civicrm_case.is_deleted = 0 )
3125 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3126 // search tag in activities
3127 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3128 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3129 = " LEFT JOIN civicrm_activity_contact
3130 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3131 LEFT JOIN civicrm_activity
3132 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3133 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3134 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3137 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3138 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3141 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3143 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
3146 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3147 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3150 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3151 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3152 $op = str_replace('EMPTY', 'NULL', $op);
3153 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3156 $this->_where
[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
3158 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $names;
3164 * Where/qill clause for notes
3166 * @param array $values
3168 public function notes(&$values) {
3169 list($name, $op, $value, $grouping, $wildcard) = $values;
3171 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3172 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3173 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3175 $this->_useDistinct
= TRUE;
3177 $this->_tables
['civicrm_note'] = $this->_whereTables
['civicrm_note']
3178 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3180 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3182 $value = $strtolower(CRM_Core_DAO
::escapeString($n));
3183 if ($wildcard ||
$op == 'LIKE') {
3184 if (strpos($value, '%') === FALSE) {
3185 $value = "%$value%";
3189 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3195 if ($noteOption %
2 == 0) {
3196 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3197 $label = ts('Note: Body Only');
3199 if ($noteOption %
3 == 0) {
3200 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3201 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3203 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3204 $this->_qill
[$grouping][] = $label . " $op - '$n'";
3208 * @param string $name
3214 public function nameNullOrEmptyOp($name, $op, $grouping) {
3218 $this->_where
[$grouping][] = "contact_a.$name $op";
3219 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3223 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3224 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3227 case 'IS NOT EMPTY':
3228 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3229 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3238 * Where / qill clause for sort_name
3240 * @param array $values
3242 public function sortName(&$values) {
3243 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3245 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3246 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3250 $input = $value = trim($value);
3252 if (!strlen($value)) {
3256 $config = CRM_Core_Config
::singleton();
3260 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3263 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
3265 $firstChar = substr($value, 0, 1);
3266 $lastChar = substr($value, -1, 1);
3267 $quotes = array("'", '"');
3268 // If string is quoted, strip quotes and otherwise don't alter it
3269 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3270 $value = trim($value, implode('', $quotes));
3272 // Replace spaces with wildcards for a LIKE operation
3273 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3274 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3275 $value = str_replace(' ', '%', $value);
3277 $value = $strtolower(CRM_Core_DAO
::escapeString(trim($value)));
3278 if (strlen($value)) {
3279 $fieldsub = array();
3280 if ($wildcard && $op == 'LIKE') {
3281 if ($config->includeWildCardInName
) {
3282 $value = "'%$value%'";
3285 $value = "'$value%'";
3290 $value = "'$value'";
3292 if ($fieldName == 'sort_name') {
3293 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3296 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.display_name)" : "contact_a.display_name";
3298 $fieldsub[] = " ( $wc $op $value )";
3299 if ($config->includeNickNameInName
) {
3300 $wc = self
::caseImportant($op) ?
"LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3301 $fieldsub[] = " ( $wc $op $value )";
3303 if ($config->includeEmailInName
) {
3304 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3306 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3309 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3311 $this->_where
[$grouping][] = $sub;
3312 if ($config->includeEmailInName
) {
3313 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3314 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3317 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3322 * Where/qill clause for greeting fields.
3324 * @param array $values
3326 public function greetings(&$values) {
3327 list($name, $op, $value, $grouping, $wildcard) = $values;
3328 $name .= '_display';
3330 $this->_qill
[$grouping][] = ts('Greeting %1 %2', array(1 => $op, 2 => $value));
3331 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", 'LIKE', "$value", 'String');
3335 * Where / qill clause for email
3341 public function email(&$values) {
3342 list($name, $op, $value, $grouping, $wildcard) = $values;
3346 $config = CRM_Core_Config
::singleton();
3348 if (substr($n, 0, 1) == '"' &&
3349 substr($n, -1, 1) == '"'
3351 $n = substr($n, 1, -1);
3352 $value = strtolower(CRM_Core_DAO
::escapeString($n));
3353 $value = "'$value'";
3357 $value = strtolower($n);
3359 if (strpos($value, '%') === FALSE) {
3360 $value = "%{$value}%";
3365 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3366 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3369 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3370 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3373 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3377 * Where / qill clause for phone number
3379 * @param array $values
3381 public function phone_numeric(&$values) {
3382 list($name, $op, $value, $grouping, $wildcard) = $values;
3383 // Strip non-numeric characters; allow wildcards
3384 $number = preg_replace('/[^\d%]/', '', $value);
3386 if (strpos($number, '%') === FALSE) {
3387 $number = "%$number%";
3390 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3391 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3392 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3397 * Where / qill clause for phone type/location
3399 * @param array $values
3401 public function phone_option_group($values) {
3402 list($name, $op, $value, $grouping, $wildcard) = $values;
3403 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3404 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3405 $optionName = $options[$value];
3406 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3407 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3408 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3412 * Where / qill clause for street_address.
3414 * @param array $values
3416 public function street_address(&$values) {
3417 list($name, $op, $value, $grouping, $wildcard) = $values;
3426 $value = strtolower($n);
3427 if (strpos($value, '%') === FALSE) {
3428 // only add wild card if not there
3429 $value = "%{$value}%";
3432 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3433 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3436 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3437 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3440 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3444 * Where / qill clause for street_unit.
3446 * @param array $values
3448 public function street_number(&$values) {
3449 list($name, $op, $value, $grouping, $wildcard) = $values;
3457 if (strtolower($n) == 'odd') {
3458 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3459 $this->_qill
[$grouping][] = ts('Street Number is odd');
3461 elseif (strtolower($n) == 'even') {
3462 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3463 $this->_qill
[$grouping][] = ts('Street Number is even');
3466 $value = strtolower($n);
3468 $this->_where
[$grouping][] = self
::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3469 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3472 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3476 * Where / qill clause for sorting by character.
3478 * @param array $values
3480 public function sortByCharacter(&$values) {
3481 list($name, $op, $value, $grouping, $wildcard) = $values;
3483 $name = trim($value);
3484 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO
::escapeWildCardString($name)) . "%'";
3485 $this->_where
[$grouping][] = $cond;
3486 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3490 * Where / qill clause for including contact ids.
3492 public function includeContactIDs() {
3493 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3497 $contactIds = array();
3498 foreach ($this->_params
as $id => $values) {
3499 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3500 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3503 CRM_Utils_Type
::validateAll($contactIds, 'Positive');
3504 if (!empty($contactIds)) {
3505 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3510 * Where / qill clause for postal code.
3512 * @param array $values
3514 public function postalCode(&$values) {
3515 // skip if the fields dont have anything to do with postal_code
3516 if (empty($this->_fields
['postal_code'])) {
3520 list($name, $op, $value, $grouping, $wildcard) = $values;
3522 // Handle numeric postal code range searches properly by casting the column as numeric
3523 if (is_numeric($value)) {
3524 $field = 'ROUND(civicrm_address.postal_code)';
3525 $val = CRM_Utils_Type
::escape($value, 'Integer');
3528 $field = 'civicrm_address.postal_code';
3529 // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string.
3530 if (!is_array($value)) {
3531 $val = CRM_Utils_Type
::escape($value, 'String');
3534 // Do we need to escape values here? I would expect buildClause does.
3539 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3541 if ($name == 'postal_code') {
3542 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3543 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3545 elseif ($name == 'postal_code_low') {
3546 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3547 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3549 elseif ($name == 'postal_code_high') {
3550 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3551 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3556 * Where / qill clause for location type.
3558 * @param array $values
3559 * @param null $status
3563 public function locationType(&$values, $status = NULL) {
3564 list($name, $op, $value, $grouping, $wildcard) = $values;
3566 if (is_array($value)) {
3567 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3568 $this->_tables
['civicrm_address'] = 1;
3569 $this->_whereTables
['civicrm_address'] = 1;
3571 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3573 foreach ($value as $id) {
3574 $names[] = $locationType[$id];
3577 $this->_primaryLocation
= FALSE;
3580 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3583 return implode(' ' . ts('or') . ' ', $names);
3590 * @param bool $fromStateProvince
3592 * @return array|NULL
3594 public function country(&$values, $fromStateProvince = TRUE) {
3595 list($name, $op, $value, $grouping, $wildcard) = $values;
3597 if (!$fromStateProvince) {
3598 $stateValues = $this->getWhereValues('state_province', $grouping);
3599 if (!empty($stateValues)) {
3600 // return back to caller if there are state province values
3601 // since that handles this case
3606 $countryClause = $countryQill = NULL;
3607 if ($values && !empty($value)) {
3608 $this->_tables
['civicrm_address'] = 1;
3609 $this->_whereTables
['civicrm_address'] = 1;
3611 $countryClause = self
::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
3612 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, 'country_id', $value, $op);
3613 $countryQill = ts("%1 %2 %3", array(1 => 'Country', 2 => $qillop, 3 => $qillVal));
3615 if (!$fromStateProvince) {
3616 $this->_where
[$grouping][] = $countryClause;
3617 $this->_qill
[$grouping][] = $countryQill;
3621 if ($fromStateProvince) {
3622 if (!empty($countryClause)) {
3625 " ...AND... " . $countryQill,
3629 return array(NULL, NULL);
3635 * Where / qill clause for county (if present).
3637 * @param array $values
3638 * @param null $status
3642 public function county(&$values, $status = NULL) {
3643 list($name, $op, $value, $grouping, $wildcard) = $values;
3645 if (!is_array($value)) {
3646 // force the county to be an array
3647 $value = array($value);
3650 // check if the values are ids OR names of the counties
3651 $inputFormat = 'id';
3652 foreach ($value as $v) {
3653 if (!is_numeric($v)) {
3654 $inputFormat = 'name';
3662 elseif ($op == '!=') {
3666 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3667 $op = str_replace('EMPTY', 'NULL', $op);
3670 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3671 $clause = "civicrm_address.county_id $op";
3673 elseif ($inputFormat == 'id') {
3674 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3676 $county = CRM_Core_PseudoConstant
::county();
3677 foreach ($value as $id) {
3678 $names[] = CRM_Utils_Array
::value($id, $county);
3682 $inputClause = array();
3683 $county = CRM_Core_PseudoConstant
::county();
3684 foreach ($value as $name) {
3685 $name = trim($name);
3686 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3688 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3691 $this->_tables
['civicrm_address'] = 1;
3692 $this->_whereTables
['civicrm_address'] = 1;
3694 $this->_where
[$grouping][] = $clause;
3696 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3699 return implode(' ' . ts('or') . ' ', $names);
3704 * Where / qill clause for state/province AND country (if present).
3706 * @param array $values
3707 * @param null $status
3711 public function stateProvince(&$values, $status = NULL) {
3712 list($name, $op, $value, $grouping, $wildcard) = $values;
3714 // quick escape for IS NULL
3715 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3718 elseif (!is_array($value)) {
3719 // force the state to be an array
3720 // check if its in the mapper format!
3721 $values = self
::parseSearchBuilderString($value);
3722 if (is_array($values)) {
3726 $value = array($value);
3730 // check if the values are ids OR names of the states
3731 $inputFormat = 'id';
3733 foreach ($value as $v) {
3734 if (!is_numeric($v)) {
3735 $inputFormat = 'name';
3745 elseif ($op == '!=') {
3749 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3750 $op = str_replace('EMPTY', 'NULL', $op);
3752 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3753 $stateClause = "civicrm_address.state_province_id $op";
3755 elseif ($inputFormat == 'id') {
3756 if ($op != 'NOT IN') {
3759 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
3761 foreach ($value as $id) {
3762 $names[] = CRM_Core_PseudoConstant
::stateProvince($id, FALSE);
3766 $inputClause = array();
3767 $stateProvince = CRM_Core_PseudoConstant
::stateProvince();
3768 foreach ($value as $name) {
3769 $name = trim($name);
3770 $inputClause[] = CRM_Utils_Array
::key($name, $stateProvince);
3772 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
3775 $this->_tables
['civicrm_address'] = 1;
3776 $this->_whereTables
['civicrm_address'] = 1;
3778 $countryValues = $this->getWhereValues('country', $grouping);
3779 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3781 if ($countryClause) {
3782 $clause = "( $stateClause AND $countryClause )";
3785 $clause = $stateClause;
3788 $this->_where
[$grouping][] = $clause;
3790 $this->_qill
[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3793 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
3798 * Where / qill clause for change log.
3800 * @param array $values
3802 public function changeLog(&$values) {
3803 list($name, $op, $value, $grouping, $wildcard) = $values;
3805 $targetName = $this->getWhereValues('changed_by', $grouping);
3810 $name = trim($targetName[2]);
3811 $name = strtolower(CRM_Core_DAO
::escapeString($name));
3812 $name = $targetName[4] ?
"%$name%" : $name;
3813 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3814 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3815 $this->_qill
[$grouping][] = ts('Modified By') . " $name";
3821 public function modifiedDates($values) {
3822 $this->_useDistinct
= TRUE;
3824 // CRM-11281, default to added date if not set
3825 $fieldTitle = ts('Added Date');
3826 $fieldName = 'created_date';
3827 foreach (array_keys($this->_params
) as $id) {
3828 if ($this->_params
[$id][0] == 'log_date') {
3829 if ($this->_params
[$id][2] == 2) {
3830 $fieldTitle = ts('Modified Date');
3831 $fieldName = 'modified_date';
3836 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3838 self
::$_openedPanes[ts('Change Log')] = TRUE;
3844 public function demographics(&$values) {
3845 list($name, $op, $value, $grouping, $wildcard) = $values;
3847 if (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3849 $this->dateQueryBuilder($values,
3850 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3853 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3855 $this->dateQueryBuilder($values,
3856 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3860 self
::$_openedPanes[ts('Demographics')] = TRUE;
3866 public function privacy(&$values) {
3867 list($name, $op, $value, $grouping, $wildcard) = $values;
3868 //fixed for profile search listing CRM-4633
3869 if (strpbrk($value, "[")) {
3870 $value = "'{$value}'";
3872 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3875 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3877 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3878 $title = $field ?
$field['title'] : $name;
3879 $this->_qill
[$grouping][] = "$title $op $value";
3885 public function privacyOptions($values) {
3886 list($name, $op, $value, $grouping, $wildcard) = $values;
3888 if (empty($value) ||
!is_array($value)) {
3892 // get the operator and toggle values
3893 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3896 strtolower($opValues[2] == 'AND')
3901 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3903 if ($toggleValues &&
3904 $toggleValues[2] == 2
3911 foreach ($value as $dontCare => $pOption) {
3912 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
3913 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
3914 $title = $field ?
$field['title'] : $pOption;
3915 $qill[] = " $title = 1 ";
3918 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
3919 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
3925 public function preferredCommunication(&$values) {
3926 list($name, $op, $value, $grouping, $wildcard) = $values;
3929 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3932 elseif (!is_array($value)) {
3934 $value = trim($value, ' ()');
3935 if (strpos($value, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
3936 $v = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
3939 $v = explode(",", $value);
3942 foreach ($v as $item) {
3949 foreach ($value as $key => $checked) {
3956 $commPref = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
3958 $sqlValue = array();
3959 $showValue = array();
3960 $sql = "contact_a.preferred_communication_method";
3961 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3962 $sqlValue[] = "{$sql} {$op}";
3965 foreach ($pref as $val) {
3966 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. $val . CRM_Core_DAO
::VALUE_SEPARATOR
. "%' ) ";
3967 $showValue[] = $commPref[$val];
3970 $this->_where
[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
3971 $this->_qill
[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
3975 * Where / qill clause for relationship.
3977 * @param array $values
3979 public function relationship(&$values) {
3980 list($name, $op, $value, $grouping, $wildcard) = $values;
3981 if ($this->_relationshipValuesAdded
) {
3984 // also get values array for relation_target_name
3985 // for relationship search we always do wildcard
3986 $relationType = $this->getWhereValues('relation_type_id', $grouping);
3987 $targetName = $this->getWhereValues('relation_target_name', $grouping);
3988 $relStatus = $this->getWhereValues('relation_status', $grouping);
3989 $relPermission = $this->getWhereValues('relation_permission', $grouping);
3990 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
3992 $nameClause = $name = NULL;
3994 $name = trim($targetName[2]);
3995 if (substr($name, 0, 1) == '"' &&
3996 substr($name, -1, 1) == '"'
3998 $name = substr($name, 1, -1);
3999 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4000 $nameClause = "= '$name'";
4003 $name = strtolower(CRM_Core_DAO
::escapeString($name));
4004 $nameClause = "LIKE '%{$name}%'";
4008 $rTypeValues = array();
4009 if (!empty($relationType)) {
4010 $rel = explode('_', $relationType[2]);
4011 self
::$_relType = $rel[1];
4012 $params = array('id' => $rel[0]);
4013 $rType = CRM_Contact_BAO_RelationshipType
::retrieve($params, $rTypeValues);
4015 if (!empty($rTypeValues) && $rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
4016 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4017 //@todo unless we are dealing with a target group
4018 self
::$_relType = 'reciprocal';
4020 // if we are creating a temp table we build our own where for the relationship table
4021 $relationshipTempTable = NULL;
4022 if (self
::$_relType == 'reciprocal' && empty($targetGroup)) {
4024 self
::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO
::createTempTableName('civicrm_rel');
4026 $where[$grouping][] = " sort_name $nameClause ";
4030 $where = &$this->_where
;
4032 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4036 $relTypeInd = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
4037 $relTypeOrg = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
4038 $relTypeHou = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, 'Household');
4039 $allRelationshipType = array();
4040 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
4041 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
4043 if ($nameClause ||
!$targetGroup) {
4044 if (!empty($relationType)) {
4045 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " $name";
4048 $this->_qill
[$grouping][] = $name;
4052 //check to see if the target contact is in specified group
4054 //add contacts from static groups
4055 $this->_tables
['civicrm_relationship_group_contact'] = $this->_whereTables
['civicrm_relationship_group_contact']
4056 = " 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'";
4057 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4058 implode(",", $targetGroup[2]) . ") ) ";
4060 //add contacts from saved searches
4061 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b", $op);
4063 //set the group where clause
4065 $groupWhere[] = "( " . $ssWhere . " )";
4067 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4069 //Get the names of the target groups for the qill
4070 $groupNames = CRM_Core_PseudoConstant
::group();
4071 $qillNames = array();
4072 foreach ($targetGroup[2] as $groupId) {
4073 if (array_key_exists($groupId, $groupNames)) {
4074 $qillNames[] = $groupNames[$groupId];
4077 if (!empty($relationType)) {
4078 $this->_qill
[$grouping][] = $allRelationshipType[$relationType[2]] . " ( " . implode(", ", $qillNames) . " )";
4081 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4085 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4086 $today = date('Ymd');
4087 //check for active, inactive and all relation status
4088 if ($relStatus[2] == 0) {
4089 $where[$grouping][] = "(
4090 civicrm_relationship.is_active = 1 AND
4091 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4092 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4094 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4096 elseif ($relStatus[2] == 1) {
4097 $where[$grouping][] = "(
4098 civicrm_relationship.is_active = 0 OR
4099 civicrm_relationship.end_date < {$today} OR
4100 civicrm_relationship.start_date > {$today}
4102 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4106 if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
)) {
4109 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4111 //check for permissioned, non-permissioned and all permissioned relations
4112 if ($relPermission[2] == 1) {
4113 $where[$grouping][] = "(
4114 civicrm_relationship.is_permission_a_b = 1
4116 $this->_qill
[$grouping][] = ts('Relationship - Permissioned');
4118 elseif ($relPermission[2] == 2) {
4119 //non-allowed permission relationship.
4120 $where[$grouping][] = "(
4121 civicrm_relationship.is_permission_a_b = 0
4123 $this->_qill
[$grouping][] = ts('Relationship - Non-permissioned');
4126 $this->addRelationshipDateClauses($grouping, $where);
4127 if (!empty($relationType) && !empty($rType) && isset($rType->id
)) {
4128 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id
;
4130 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4131 $this->_useDistinct
= TRUE;
4132 $this->_relationshipValuesAdded
= TRUE;
4133 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4135 // @todo creating a temp table could be expanded to group filter
4136 // as even creating a temp table of all relationships is much much more efficient than
4137 // an OR in the join
4138 if ($relationshipTempTable) {
4140 if (!empty($where[$grouping])) {
4141 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4142 $whereClause = str_replace('contact_b', 'c', $whereClause);
4145 CREATE TEMPORARY TABLE {$relationshipTempTable}
4146 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4147 FROM civicrm_relationship
4148 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4151 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4152 FROM civicrm_relationship
4153 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4156 CRM_Core_DAO
::executeQuery($sql);
4162 * Add start & end date criteria in
4163 * @param string $grouping
4164 * @param array $where
4165 * = array to add where clauses to, in case you are generating a temp table.
4166 * not the main query.
4168 public function addRelationshipDateClauses($grouping, &$where) {
4169 $dateValues = array();
4175 foreach ($dateTypes as $dateField) {
4176 $dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping);
4177 $dateValueHigh = $this->getWhereValues('relation_' . $dateField . '_high', $grouping);
4178 if (!empty($dateValueLow)) {
4179 $date = date('Ymd', strtotime($dateValueLow[2]));
4180 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4181 $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);
4183 if (!empty($dateValueHigh)) {
4184 $date = date('Ymd', strtotime($dateValueHigh[2]));
4185 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4186 $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);
4192 * Default set of return properties.
4197 * derault return properties
4199 public static function &defaultReturnProperties($mode = 1) {
4200 if (!isset(self
::$_defaultReturnProperties)) {
4201 self
::$_defaultReturnProperties = array();
4204 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4205 // add activity return properties
4206 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4207 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4210 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4213 if (empty(self
::$_defaultReturnProperties[$mode])) {
4214 self
::$_defaultReturnProperties[$mode] = array(
4217 'legal_identifier' => 1,
4218 'external_identifier' => 1,
4219 'contact_type' => 1,
4220 'contact_sub_type' => 1,
4222 'display_name' => 1,
4223 'preferred_mail_format' => 1,
4230 'formal_title' => 1,
4231 'communication_style_id' => 1,
4234 'street_address' => 1,
4235 'supplemental_address_1' => 1,
4236 'supplemental_address_2' => 1,
4239 'postal_code_suffix' => 1,
4240 'state_province' => 1,
4242 'world_region' => 1,
4249 'household_name' => 1,
4250 'organization_name' => 1,
4251 'deceased_date' => 1,
4256 'current_employer' => 1,
4257 // FIXME: should we use defaultHierReturnProperties() for the below?
4258 'do_not_email' => 1,
4261 'do_not_phone' => 1,
4262 'do_not_trade' => 1,
4264 'contact_is_deleted' => 1,
4265 'preferred_communication_method' => 1,
4266 'preferred_language' => 1,
4270 return self
::$_defaultReturnProperties[$mode];
4274 * Get primary condition for a sql clause.
4278 * @return string|NULL
4280 public static function getPrimaryCondition($value) {
4281 if (is_numeric($value)) {
4282 $value = (int ) $value;
4283 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4289 * Wrapper for a simple search query.
4291 * @param array $params
4292 * @param array $returnProperties
4293 * @param bool $count
4297 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4298 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4299 list($select, $from, $where, $having) = $query->query();
4301 return "$select $from $where $having";
4305 * These are stub comments as this function needs more explanation - particularly in terms of how it
4306 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4308 * This function was originally written as a wrapper for the api query but is called from multiple places
4309 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4310 * but it is unclear as to whehter that is historical or there is a reason
4311 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4313 * @param array $params
4314 * @param array $returnProperties
4315 * @param null $fields
4316 * @param string $sort
4317 * @param int $offset
4318 * @param int $row_count
4319 * @param bool $smartGroupCache
4320 * ?? update smart group cache?.
4321 * @param bool $count
4322 * Return count obnly.
4323 * @param bool $skipPermissions
4324 * Should permissions be ignored or should the logged in user's permissions be applied.
4329 public static function apiQuery(
4331 $returnProperties = NULL,
4336 $smartGroupCache = TRUE,
4338 $skipPermissions = TRUE
4341 $query = new CRM_Contact_BAO_Query(
4342 $params, $returnProperties,
4343 NULL, TRUE, FALSE, 1,
4345 TRUE, $smartGroupCache
4348 //this should add a check for view deleted if permissions are enabled
4349 if ($skipPermissions) {
4350 $query->_skipDeleteClause
= TRUE;
4352 $query->generatePermissionClause(FALSE, $count);
4354 // note : this modifies _fromClause and _simpleFromClause
4355 $query->includePseudoFieldsJoin($sort);
4357 list($select, $from, $where, $having) = $query->query($count);
4359 $options = $query->_options
;
4360 if (!empty($query->_permissionWhereClause
)) {
4361 if (empty($where)) {
4362 $where = "WHERE $query->_permissionWhereClause";
4365 $where = "$where AND $query->_permissionWhereClause";
4369 $sql = "$select $from $where $having";
4372 if ($query->_useGroupBy
) {
4373 $sql .= ' GROUP BY contact_a.id';
4375 if (!empty($sort)) {
4376 $sort = CRM_Utils_Type
::escape($sort, 'String');
4377 $sql .= " ORDER BY $sort ";
4379 if ($row_count > 0 && $offset >= 0) {
4380 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4381 $rowCount = CRM_Utils_Type
::escape($row_count, 'Int');
4382 $sql .= " LIMIT $offset, $row_count ";
4385 $dao = CRM_Core_DAO
::executeQuery($sql);
4388 while ($dao->fetch()) {
4390 $noRows = $dao->rowCount
;
4392 return array($noRows, NULL);
4394 $val = $query->store($dao);
4395 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4397 if (!empty($convertedVals)) {
4398 $val = array_replace_recursive($val, $convertedVals);
4400 $values[$dao->contact_id
] = $val;
4403 return array($values, $options);
4407 * Get the actual custom field name by stripping off the appended string.
4409 * The string could be _relative, _from, or _to
4411 * @todo use metadata rather than convention to do this.
4413 * @param string $parameterName
4414 * The name of the parameter submitted to the form.
4421 public static function getCustomFieldName($parameterName) {
4422 if (substr($parameterName, -5, 5) == '_from') {
4423 return substr($parameterName, 0, strpos($parameterName, '_from'));
4425 if (substr($parameterName, -9, 9) == '_relative') {
4426 return substr($parameterName, 0, strpos($parameterName, '_relative'));
4428 if (substr($parameterName, -3, 3) == '_to') {
4429 return substr($parameterName, 0, strpos($parameterName, '_to'));
4434 * Convert submitted values for relative custom fields to query object format.
4436 * The query will support the sqlOperator format so convert to that format.
4438 * @param array $formValues
4440 * @param array $params
4441 * Converted parameters for the query object.
4442 * @param string $values
4444 * @param string $fieldName
4445 * Submitted field name. (Matches form field not DB field.)
4447 protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) {
4448 if (empty($values)) {
4449 // e.g we might have relative set & from & to empty. The form flow is a bit funky &
4450 // this function gets called again after they fields have been converted which can get ugly.
4453 $customFieldName = self
::getCustomFieldName($fieldName);
4455 if (substr($fieldName, -9, 9) == '_relative') {
4456 list($from, $to) = CRM_Utils_Date
::getFromTo($values, NULL, NULL);
4459 if ($fieldName == $customFieldName . '_to' && CRM_Utils_Array
::value($customFieldName . '_from', $formValues)) {
4460 // Both to & from are set. We only need to acton one, choosing from.
4464 $from = CRM_Utils_Array
::value($customFieldName . '_from', $formValues, NULL);
4465 $to = CRM_Utils_Array
::value($customFieldName . '_to', $formValues, NULL);
4467 if (self
::isCustomDateField($customFieldName)) {
4468 list($from, $to) = CRM_Utils_Date
::getFromTo(NULL, $from, $to);
4474 $relativeFunction = array('BETWEEN' => array($from, $to));
4477 $relativeFunction = array('>=' => $from);
4481 $relativeFunction = array('<=' => $to);
4493 * Are we dealing with custom field of type date.
4499 public static function isCustomDateField($fieldName) {
4500 if (($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($fieldName)) == FALSE) {
4503 if ('Date' == civicrm_api3('CustomField', 'getvalue', array('id' => $customFieldID, 'return' => 'data_type'))) {
4510 * Has this field already been reformatting to Query object syntax.
4512 * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems
4513 * to come with associated double queries & is possibly damaging performance.
4515 * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns
4518 * @param mixed $values
4519 * Value in formValues for the field.
4523 public static function isAlreadyProcessedForQueryFormat($values) {
4524 if (!is_array($values)) {
4527 if (($operator = CRM_Utils_Array
::value(1, $values)) == FALSE) {
4530 return in_array($operator, CRM_Core_DAO
::acceptedSQLOperators());
4534 * Create and query the db for an contact search.
4536 * @param int $offset
4537 * The offset for the query.
4538 * @param int $rowCount
4539 * The number of rows to return.
4540 * @param string|CRM_Utils_Sort $sort
4541 * The order by string.
4542 * @param bool $count
4543 * Is this a count only query ?.
4544 * @param bool $includeContactIds
4545 * Should we include contact ids?.
4546 * @param bool $sortByChar
4547 * If true returns the distinct array of first characters for search results.
4548 * @param bool $groupContacts
4549 * If true, return only the contact ids.
4550 * @param bool $returnQuery
4551 * Should we return the query as a string.
4552 * @param string $additionalWhereClause
4553 * If the caller wants to further restrict the search (used for components).
4554 * @param null $sortOrder
4555 * @param string $additionalFromClause
4556 * Should be clause with proper joins, effective to reduce where clause load.
4558 * @param bool $skipOrderAndLimit
4560 * @return CRM_Core_DAO
4562 public function searchQuery(
4563 $offset = 0, $rowCount = 0, $sort = NULL,
4564 $count = FALSE, $includeContactIds = FALSE,
4565 $sortByChar = FALSE, $groupContacts = FALSE,
4566 $returnQuery = FALSE,
4567 $additionalWhereClause = NULL, $sortOrder = NULL,
4568 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4571 if ($includeContactIds) {
4572 $this->_includeContactIds
= TRUE;
4573 $this->_whereClause
= $this->whereClause();
4576 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4578 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4579 // and that contact happens to be deleted, set $onlyDeleted to true
4580 foreach ($this->_params
as $values) {
4581 $name = CRM_Utils_Array
::value(0, $values);
4582 $op = CRM_Utils_Array
::value(1, $values);
4583 $value = CRM_Utils_Array
::value(2, $values);
4584 if ($name == 'contact_id' and $op == '=') {
4585 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4586 $onlyDeleted = TRUE;
4592 // building the query string
4595 if (isset($this->_groupByComponentClause
)) {
4596 $groupBy = $this->_groupByComponentClause
;
4598 elseif ($this->_useGroupBy
) {
4599 $groupBy = ' GROUP BY contact_a.id';
4602 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
4603 $groupBy = 'GROUP BY civicrm_activity.id ';
4606 $order = $orderBy = $limit = '';
4608 list($order, $additionalFromClause) = $this->prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause);
4610 if ($rowCount > 0 && $offset >= 0) {
4611 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4612 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
4613 $limit = " LIMIT $offset, $rowCount ";
4618 $this->_sort
= $sort;
4620 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4622 if ($additionalWhereClause) {
4623 $where = $where . ' AND ' . $additionalWhereClause;
4626 //additional from clause should be w/ proper joins.
4627 if ($additionalFromClause) {
4628 $from .= "\n" . $additionalFromClause;
4631 // if we are doing a transform, do it here
4632 // use the $from, $where and $having to get the contact ID
4633 if ($this->_displayRelationshipType
) {
4634 $this->filterRelatedContacts($from, $where, $having);
4637 if ($skipOrderAndLimit) {
4638 $query = "$select $from $where $having $groupBy";
4641 $query = "$select $from $where $having $groupBy $order $limit";
4648 return CRM_Core_DAO
::singleValueQuery($query);
4651 $dao = CRM_Core_DAO
::executeQuery($query);
4652 if ($groupContacts) {
4654 while ($dao->fetch()) {
4657 return implode(',', $ids);
4664 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4666 * @param string $cacheKey
4667 * @param int $offset
4668 * @param int $rowCount
4669 * @param bool $includeContactIds
4670 * @return CRM_Core_DAO
4672 public function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4673 $this->_includeContactIds
= $includeContactIds;
4674 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4675 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
4676 $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);
4677 $order = " ORDER BY pnc.id";
4678 $groupBy = " GROUP BY contact_a.id";
4679 $limit = " LIMIT $offset, $rowCount";
4680 $query = "$select $from $where $groupBy $order $limit";
4682 return CRM_Core_DAO
::executeQuery($query);
4686 * Populate $this->_permissionWhereClause with permission related clause and update other
4687 * query related properties.
4689 * Function calls ACL permission class and hooks to filter the query appropriately
4691 * Note that these 2 params were in the code when extracted from another function
4692 * and a second round extraction would be to make them properties of the class
4694 * @param bool $onlyDeleted
4695 * Only get deleted contacts.
4696 * @param bool $count
4697 * Return Count only.
4699 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4700 if (!$this->_skipPermission
) {
4701 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4702 CRM_Core_Permission
::VIEW
,
4704 $this->_whereTables
,
4707 $this->_skipDeleteClause
4710 // regenerate fromClause since permission might have added tables
4711 if ($this->_permissionWhereClause
) {
4712 //fix for row count in qill (in contribute/membership find)
4714 $this->_useDistinct
= TRUE;
4717 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4718 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
4719 // note : this modifies _fromClause and _simpleFromClause
4720 $this->includePseudoFieldsJoin($this->_sort
);
4724 // add delete clause if needed even if we are skipping permission
4726 if (!$this->_skipDeleteClause
) {
4727 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
4728 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
4732 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
4741 public function setSkipPermission($val) {
4742 $this->_skipPermission
= $val;
4746 * @param null $context
4750 public function &summaryContribution($context = NULL) {
4751 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4755 SELECT COUNT( conts.total_amount ) as total_count,
4756 SUM( conts.total_amount ) as total_amount,
4757 AVG( conts.total_amount ) as total_avg,
4758 conts.currency as currency";
4759 if ($this->_permissionWhereClause
) {
4760 $where .= " AND " . $this->_permissionWhereClause
;
4762 if ($context == 'search') {
4763 $where .= " AND contact_a.is_deleted = 0 ";
4766 // make sure contribution is completed - CRM-4989
4767 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4770 $summary['total'] = array();
4771 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4773 $query = "$select FROM (
4774 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $completedWhere
4775 GROUP BY civicrm_contribution.id
4779 $dao = CRM_Core_DAO
::executeQuery($query);
4781 $summary['total']['count'] = 0;
4782 $summary['total']['amount'] = $summary['total']['avg'] = array();
4783 while ($dao->fetch()) {
4784 $summary['total']['count'] +
= $dao->total_count
;
4785 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4786 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4788 if (!empty($summary['total']['amount'])) {
4789 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
4790 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
4793 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4796 // soft credit summary
4797 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
4798 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
4801 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
4802 GROUP BY civicrm_contribution_soft.id
4805 $dao = CRM_Core_DAO
::executeQuery($query);
4806 $summary['soft_credit']['count'] = 0;
4807 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
4808 while ($dao->fetch()) {
4809 $summary['soft_credit']['count'] +
= $dao->total_count
;
4810 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
4811 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
4813 if (!empty($summary['soft_credit']['amount'])) {
4814 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
4815 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
4818 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
4823 //@todo - this could be one query using the IF in mysql - eg
4824 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
4825 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
4826 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
4827 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
4828 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
4829 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
4830 // FROM civicrm_contact contact_a
4831 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
4832 // WHERE ( ... where clause....
4833 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
4837 SELECT COUNT( conts.total_amount ) as cancel_count,
4838 SUM( conts.total_amount ) as cancel_amount,
4839 AVG( conts.total_amount ) as cancel_avg,
4840 conts.currency as currency";
4842 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4843 if ($context == 'search') {
4844 $where .= " AND contact_a.is_deleted = 0 ";
4847 $query = "$select FROM (
4848 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
4849 GROUP BY civicrm_contribution.id
4853 $dao = CRM_Core_DAO
::executeQuery($query);
4856 if ($dao->fetch()) {
4857 $summary['cancel']['count'] = $dao->cancel_count
;
4858 $summary['cancel']['amount'] = $dao->cancel_amount
;
4859 $summary['cancel']['avg'] = $dao->cancel_avg
;
4863 $summary['cancel']['count'] = 0;
4864 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4865 while ($dao->fetch()) {
4866 $summary['cancel']['count'] +
= $dao->cancel_count
;
4867 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
4868 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
4870 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
4871 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
4878 * Getter for the qill object.
4882 public function qill() {
4883 return $this->_qill
;
4887 * Default set of return default hier return properties.
4891 public static function &defaultHierReturnProperties() {
4892 if (!isset(self
::$_defaultHierReturnProperties)) {
4893 self
::$_defaultHierReturnProperties = array(
4896 'legal_identifier' => 1,
4897 'external_identifier' => 1,
4898 'contact_type' => 1,
4899 'contact_sub_type' => 1,
4901 'display_name' => 1,
4908 'formal_title' => 1,
4909 'communication_style_id' => 1,
4910 'email_greeting' => 1,
4911 'postal_greeting' => 1,
4915 'preferred_communication_method' => 1,
4916 'do_not_phone' => 1,
4917 'do_not_email' => 1,
4920 'do_not_trade' => 1,
4921 'location' => array(
4923 'location_type' => 1,
4924 'street_address' => 1,
4926 'state_province' => 1,
4928 'postal_code_suffix' => 1,
4931 'phone-Mobile' => 1,
4944 'location_type' => 1,
4945 'street_address' => 1,
4947 'state_province' => 1,
4949 'postal_code_suffix' => 1,
4952 'phone-Mobile' => 1,
4966 return self
::$_defaultHierReturnProperties;
4970 * Build query for a date field.
4972 * @param array $values
4973 * @param string $tableName
4974 * @param string $fieldName
4975 * @param string $dbFieldName
4976 * @param string $fieldTitle
4977 * @param bool $appendTimeStamp
4979 public function dateQueryBuilder(
4980 &$values, $tableName, $fieldName,
4981 $dbFieldName, $fieldTitle,
4982 $appendTimeStamp = TRUE
4984 list($name, $op, $value, $grouping, $wildcard) = $values;
4986 if ($name == "{$fieldName}_low" ||
4987 $name == "{$fieldName}_high"
4989 if (isset($this->_rangeCache
[$fieldName]) ||
!$value) {
4992 $this->_rangeCache
[$fieldName] = 1;
4994 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4996 if ($name == $fieldName . '_low') {
4998 $firstPhrase = ts('greater than or equal to');
4999 $firstDate = CRM_Utils_Date
::processDate($value);
5001 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5002 if (!empty($secondValues) && $secondValues[2]) {
5004 $secondPhrase = ts('less than or equal to');
5005 $secondValue = $secondValues[2];
5007 if ($appendTimeStamp && strlen($secondValue) == 10) {
5008 $secondValue .= ' 23:59:59';
5010 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5013 elseif ($name == $fieldName . '_high') {
5015 $firstPhrase = ts('less than or equal to');
5017 if ($appendTimeStamp && strlen($value) == 10) {
5018 $value .= ' 23:59:59';
5020 $firstDate = CRM_Utils_Date
::processDate($value);
5022 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5023 if (!empty($secondValues) && $secondValues[2]) {
5025 $secondPhrase = ts('greater than or equal to');
5026 $secondValue = $secondValues[2];
5027 $secondDate = CRM_Utils_Date
::processDate($secondValue);
5031 if (!$appendTimeStamp) {
5032 $firstDate = substr($firstDate, 0, 8);
5034 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5037 if (!$appendTimeStamp) {
5038 $secondDate = substr($secondDate, 0, 8);
5040 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5043 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5045 $this->_where
[$grouping][] = "
5046 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5047 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5049 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5052 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5053 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5057 if ($name == $fieldName) {
5058 //In Get API, for operators other then '=' the $value is in array(op => value) format
5059 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5061 $value = $value[$op];
5064 $date = $format = NULL;
5065 if (strstr($op, 'IN')) {
5067 foreach ($value as &$date) {
5068 $date = CRM_Utils_Date
::processDate($date);
5069 if (!$appendTimeStamp) {
5070 $date = substr($date, 0, 8);
5072 $format[] = CRM_Utils_Date
::customFormat($date);
5074 $date = "('" . implode("','", $value) . "')";
5075 $format = implode(', ', $format);
5077 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5078 $date = CRM_Utils_Date
::processDate($value);
5079 if (!$appendTimeStamp) {
5080 $date = substr($date, 0, 8);
5082 $format = CRM_Utils_Date
::customFormat($date);
5087 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5090 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op";
5093 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5095 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
5096 $this->_qill
[$grouping][] = "$fieldTitle $op $format";
5102 * @param string $tableName
5103 * @param string $fieldName
5104 * @param string $dbFieldName
5105 * @param $fieldTitle
5106 * @param null $options
5108 public function numberRangeBuilder(
5110 $tableName, $fieldName,
5111 $dbFieldName, $fieldTitle,
5114 list($name, $op, $value, $grouping, $wildcard) = $values;
5116 if ($name == "{$fieldName}_low" ||
5117 $name == "{$fieldName}_high"
5119 if (isset($this->_rangeCache
[$fieldName])) {
5122 $this->_rangeCache
[$fieldName] = 1;
5124 $secondOP = $secondPhrase = $secondValue = NULL;
5126 if ($name == "{$fieldName}_low") {
5128 $firstPhrase = ts('greater than');
5130 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5131 if (!empty($secondValues)) {
5133 $secondPhrase = ts('less than');
5134 $secondValue = $secondValues[2];
5139 $firstPhrase = ts('less than');
5141 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5142 if (!empty($secondValues)) {
5144 $secondPhrase = ts('greater than');
5145 $secondValue = $secondValues[2];
5150 $this->_where
[$grouping][] = "
5151 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5152 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5154 $displayValue = $options ?
$options[$value] : $value;
5155 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5157 $this->_qill
[$grouping][]
5158 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5161 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5162 $displayValue = $options ?
$options[$value] : $value;
5163 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5165 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5170 if ($name == $fieldName) {
5174 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5176 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5177 $displayValue = $options ?
$options[$value] : $value;
5178 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5183 * Given the field name, operator, value & its data type
5184 * builds the where Clause for the query
5185 * used for handling 'IS NULL'/'IS NOT NULL' operators
5187 * @param string $field
5191 * @param string $value
5193 * @param string $dataType
5194 * Data type of the field.
5197 * Where clause for the query.
5199 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5201 $clause = "$field $op";
5209 $clause = " (NULLIF($field, '') IS NULL) ";
5212 case 'IS NOT EMPTY':
5213 $clause = " (NULLIF($field, '') IS NOT NULL) ";
5218 // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
5219 if (!empty($value) && is_array($value) && !array_key_exists($op, $value)) {
5220 $value = array($op => $value);
5224 if (empty($dataType)) {
5225 $dataType = 'String';
5227 if (is_array($value)) {
5228 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5229 // widely used and consistent across the codebase
5230 // adding this here won't accept the search functions which don't submit an array
5231 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, $value, $dataType)) != FALSE) {
5233 return $queryString;
5236 // This is the here-be-dragons zone. We have no other hopes left for an array so lets assume it 'should' be array('IN' => array(2,5))
5237 // but we got only array(2,5) from the form.
5238 // We could get away with keeping this in 4.6 if we make it such that it throws an enotice in 4.7 so
5239 // people have to de-slopify it.
5240 if (!empty($value[0])) {
5241 if ($op != 'BETWEEN') {
5242 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReport;
5244 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => $value), $dataType)) != FALSE) {
5245 return $queryString;
5250 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReportUsingOldFormat;
5251 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => array_keys($value)), $dataType)) != FALSE) {
5252 return $queryString;
5257 $value = CRM_Utils_Type
::escape($value, $dataType);
5258 // if we don't have a dataType we should assume
5259 if ($dataType == 'String' ||
$dataType == 'Text') {
5260 $value = "'" . strtolower($value) . "'";
5262 return "$clause $value";
5267 * @param bool $reset
5271 public function openedSearchPanes($reset = FALSE) {
5272 if (!$reset ||
empty($this->_whereTables
)) {
5273 return self
::$_openedPanes;
5276 // pane name to table mapper
5277 $panesMapper = array(
5278 ts('Contributions') => 'civicrm_contribution',
5279 ts('Memberships') => 'civicrm_membership',
5280 ts('Events') => 'civicrm_participant',
5281 ts('Relationships') => 'civicrm_relationship',
5282 ts('Activities') => 'civicrm_activity',
5283 ts('Pledges') => 'civicrm_pledge',
5284 ts('Cases') => 'civicrm_case',
5285 ts('Grants') => 'civicrm_grant',
5286 ts('Address Fields') => 'civicrm_address',
5287 ts('Notes') => 'civicrm_note',
5288 ts('Change Log') => 'civicrm_log',
5289 ts('Mailings') => 'civicrm_mailing_event_queue',
5291 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5293 foreach (array_keys($this->_whereTables
) as $table) {
5294 if ($panName = array_search($table, $panesMapper)) {
5295 self
::$_openedPanes[$panName] = TRUE;
5299 return self
::$_openedPanes;
5305 public function setOperator($operator) {
5306 $validOperators = array('AND', 'OR');
5307 if (!in_array($operator, $validOperators)) {
5310 $this->_operator
= $operator;
5316 public function getOperator() {
5317 return $this->_operator
;
5325 public function filterRelatedContacts(&$from, &$where, &$having) {
5326 static $_rTypeProcessed = NULL;
5327 static $_rTypeFrom = NULL;
5328 static $_rTypeWhere = NULL;
5330 if (!$_rTypeProcessed) {
5331 $_rTypeProcessed = TRUE;
5333 // create temp table with contact ids
5334 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5335 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5336 CRM_Core_DAO
::executeQuery($sql);
5339 REPLACE INTO $tableName ( contact_id )
5345 CRM_Core_DAO
::executeQuery($sql);
5347 $qillMessage = ts('Contacts with a Relationship Type of: ');
5348 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5350 if (is_numeric($this->_displayRelationshipType
)) {
5351 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5353 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5354 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5357 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5358 AND displayRelType.is_active = 1
5362 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5363 if ($dirOne == 'a') {
5364 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5366 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5367 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5371 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5373 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5374 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5378 WHERE displayRelType.relationship_type_id = $relType
5379 AND displayRelType.is_active = 1
5382 $this->_qill
[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5385 if (!empty($this->_permissionWhereClause
)) {
5386 $_rTypeWhere .= "AND $this->_permissionWhereClause";
5389 if (strpos($from, $_rTypeFrom) === FALSE) {
5390 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5391 // this happens when we have an event_type in the quert (CRM-7969)
5392 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5393 $from .= $_rTypeFrom;
5394 $where = $_rTypeWhere;
5405 public static function caseImportant($op) {
5407 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5411 * @param $returnProperties
5416 public static function componentPresent(&$returnProperties, $prefix) {
5417 foreach ($returnProperties as $name => $dontCare) {
5418 if (substr($name, 0, strlen($prefix)) == $prefix) {
5426 * Builds the necessary structures for all fields that are similar to option value look-ups.
5428 * @param string $name
5429 * the name of the field.
5431 * the sql operator, this function should handle ALL SQL operators.
5432 * @param string $value
5433 * depends on the operator and who's calling the query builder.
5434 * @param int $grouping
5435 * the index where to place the where clause.
5436 * @param $selectValues
5437 * The key value pairs for this element. This allows us to use this function for things besides option-value pairs.
5438 * @param array $field
5439 * an array that contains various properties of the field identified by $name.
5440 * @param string $label
5441 * The label for this field element.
5442 * @param string $dataType
5443 * The data type for this element.
5444 * @param bool $useIDsOnly
5447 * adds the where clause and qill to the query object
5449 public function optionValueQuery(
5457 $dataType = 'String',
5461 if (!empty($selectValues) && !is_array($value) && !empty($selectValues[$value])) {
5462 $qill = $selectValues[$value];
5468 $pseudoFields = array(
5475 'communication_style_id',
5478 if (is_numeric($value)) {
5479 $qill = $selectValues[(int ) $value];
5481 elseif ($op == 'IN' ||
$op == 'NOT IN') {
5482 if (is_array($value)) {
5484 $newValues = array();
5485 foreach ($value as $k => $v) {
5486 $intVals[$k] = (int) $k;
5487 $newValues[] = $selectValues[(int) $k];
5490 $value = (in_array($name, $pseudoFields)) ?
$intVals : $newValues;
5491 $qill = implode(', ', $newValues);
5494 elseif (!array_key_exists($value, $selectValues)) {
5495 // its a string, lets get the int value
5496 $value = array_search($value, $selectValues);
5499 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5500 if ($tableName == 'civicrm_contact') {
5501 $wc = "contact_a.$fieldName";
5504 $wc = "$tableName.id";
5508 $wc = self
::caseImportant($op) ?
"LOWER({$field['where']})" : "{$field['where']}";
5511 if (in_array($name, $pseudoFields)) {
5512 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5513 $wc = "contact_a.{$name}_id";
5515 $dataType = 'Positive';
5516 $value = (!$value) ?
0 : $value;
5519 $this->_qill
[$grouping][] = $label . " $op '$qill'";
5520 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' ||
$op == 'RLIKE')) ?
'=' : $op;
5521 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5525 * Check and explode a user defined numeric string into an array
5526 * this was the protocol used by search builder in the old old days before we had
5527 * super nice js widgets to do the hard work
5529 * @param string $string
5530 * @param string $dataType
5531 * The dataType we should check for the values, default integer.
5533 * @return bool|array
5534 * false if string does not match the pattern
5535 * array of numeric values if string does match the pattern
5537 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5538 $string = trim($string);
5539 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5543 $string = substr($string, 1, -1);
5544 $values = explode(',', $string);
5545 if (empty($values)) {
5549 $returnValues = array();
5550 foreach ($values as $v) {
5551 if ($dataType == 'Integer' && !is_numeric($v)) {
5554 elseif ($dataType == 'String' && !is_string($v)) {
5557 $returnValues[] = trim($v);
5560 if (empty($returnValues)) {
5564 return $returnValues;
5568 * Convert the pseudo constants id's to their names
5570 * @param CRM_Core_DAO $dao
5571 * @param bool $return
5572 * @param bool $usedForAPI
5574 * @return array|NULL
5576 public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) {
5577 if (empty($this->_pseudoConstantsSelect
)) {
5581 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5582 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5586 if (is_object($dao) && property_exists($dao, $value['idCol'])) {
5587 $val = $dao->{$value['idCol']};
5589 if (CRM_Utils_System
::isNull($val)) {
5592 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5594 $idColumn = "{$key}_id";
5595 $dao->$idColumn = $val;
5597 if ($key == 'state_province_name') {
5598 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5601 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5604 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5605 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5607 // FIX ME: we should potentially move this to component Query and write a wrapper function that
5608 // handles pseudoconstant fixes for all component
5609 elseif (in_array($value['pseudoField'], array('participant_role_id', 'participant_role'))) {
5610 $viewValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val);
5612 if ($value['pseudoField'] == 'participant_role') {
5613 $pseudoOptions = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'role_id');
5614 foreach ($viewValues as $k => $v) {
5615 $viewValues[$k] = $pseudoOptions[$v];
5618 $dao->$key = ($usedForAPI && count($viewValues) > 1) ?
$viewValues : implode(', ', $viewValues);
5621 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5622 $dao->$key = $labels[$val];
5625 // return converted values in array format
5627 if (strpos($key, '-') !== FALSE) {
5628 $keyVal = explode('-', $key);
5629 $current = &$values;
5630 $lastElement = array_pop($keyVal);
5631 foreach ($keyVal as $v) {
5632 if (!array_key_exists($v, $current)) {
5633 $current[$v] = array();
5635 $current = &$current[$v];
5637 $current[$lastElement] = $dao->$key;
5640 $values[$key] = $dao->$key;
5649 * Include pseudo fields LEFT JOIN.
5650 * @param string|array $sort can be a object or string
5652 * @return array|NULL
5654 public function includePseudoFieldsJoin($sort) {
5655 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
5658 $sort = is_string($sort) ?
$sort : $sort->orderBy();
5661 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
5662 if (!empty($value['table'])) {
5663 $regex = "/({$value['table']}\.|{$name})/";
5664 if (preg_match($regex, $sort)) {
5665 $this->_elemnt
[$value['element']] = 1;
5666 $this->_select
[$value['element']] = $value['select'];
5667 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
5668 $present[$value['table']] = $value['join'];
5672 $presentSimpleFrom = $present;
5674 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
5675 array_key_exists('civicrm_country', $presentSimpleFrom)
5677 unset($presentSimpleFrom['civicrm_country']);
5679 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
5680 array_key_exists('civicrm_country', $present)
5682 unset($present['civicrm_country']);
5685 $presentClause = $presentSimpleFromClause = NULL;
5686 if (!empty($present)) {
5687 $presentClause = implode(' ', $present);
5689 if (!empty($presentSimpleFrom)) {
5690 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5693 $this->_fromClause
= $this->_fromClause
. $presentClause;
5694 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
5696 return array($presentClause, $presentSimpleFromClause);
5700 * Build qill for field.
5702 * Qill refers to the query detail visible on the UI.
5704 * @param string $daoName
5705 * @param string $fieldName
5706 * @param mixed $fieldValue
5708 * @param array $pseudoExtraParam
5710 * Type of the field per CRM_Utils_Type
5714 public static function buildQillForFieldValue(
5719 $pseudoExtraParam = array(),
5720 $type = CRM_Utils_Type
::T_STRING
5722 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
5724 if ($fieldName == 'activity_type_id') {
5725 $pseudoOptions = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
5727 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
5728 $pseudoOptions = CRM_Event_BAO_Event
::getEvents(0, $fieldValue, TRUE, TRUE, TRUE);
5730 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
5731 $pseudoOptions = CRM_Core_PseudoConstant
::group();
5733 elseif ($fieldName == 'country_id') {
5734 $pseudoOptions = CRM_Core_PseudoConstant
::country();
5737 $pseudoOptions = CRM_Core_PseudoConstant
::get($daoName, $fieldName, $pseudoExtraParam = array());
5740 //API usually have fieldValue format as array(operator => array(values)),
5741 //so we need to separate operator out of fieldValue param
5742 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5743 $op = key($fieldValue);
5744 $fieldValue = $fieldValue[$op];
5747 if (is_array($fieldValue)) {
5748 $qillString = array();
5749 if (!empty($pseudoOptions)) {
5750 foreach ((array) $fieldValue as $val) {
5751 $qillString[] = CRM_Utils_Array
::value($val, $pseudoOptions, $val);
5753 $fieldValue = implode(', ', $qillString);
5756 if ($type == CRM_Utils_Type
::T_DATE
) {
5757 foreach ($fieldValue as $index => $value) {
5758 $fieldValue[$index] = CRM_Utils_Date
::customFormat($value);
5762 // @todo - this is a bit specific (one operator).
5763 // However it is covered by a unit test so can be altered later with
5765 if ($op == 'BETWEEN') {
5766 $separator = ' AND ';
5768 $fieldValue = implode($separator, $fieldValue);
5771 elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) {
5772 $fieldValue = $pseudoOptions[$fieldValue];
5774 elseif ($type === CRM_Utils_Type
::T_DATE
) {
5775 $fieldValue = CRM_Utils_Date
::customFormat($fieldValue);
5778 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), $fieldValue);
5782 * Parse and assimilate the various sort options.
5784 * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`,
5785 * `email`), the related table may be joined automatically.
5787 * At time of writing, this code is deeply flawed and should be rewritten. For the moment,
5788 * it's been extracted to a standalone function.
5790 * @param string|CRM_Utils_Sort $sort
5791 * The order by string.
5792 * @param bool $sortByChar
5793 * If true returns the distinct array of first characters for search results.
5794 * @param null $sortOrder
5795 * Who knows? Hu knows. He who knows Hu knows who.
5796 * @param string $additionalFromClause
5797 * Should be clause with proper joins, effective to reduce where clause load.
5799 * list(string $orderByClause, string $additionalFromClause).
5801 protected function prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause) {
5803 $config = CRM_Core_Config
::singleton();
5804 if ($config->includeOrderByClause ||
5805 isset($this->_distinctComponentClause
)
5808 if (is_string($sort)) {
5812 $orderBy = trim($sort->orderBy());
5814 // Deliberately remove the backticks again, as they mess up the evil
5815 // string munging below. This balanced by re-escaping before use.
5816 $orderBy = str_replace('`', '', $orderBy);
5818 if (!empty($orderBy)) {
5819 // this is special case while searching for
5820 // change log CRM-1718
5821 if (preg_match('/sort_name/i', $orderBy)) {
5822 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
5825 $orderBy = CRM_Utils_Type
::escape($orderBy, 'String');
5826 $order = " ORDER BY $orderBy";
5829 $sortOrder = CRM_Utils_Type
::escape($sortOrder, 'String');
5830 $order .= " $sortOrder";
5833 // always add contact_a.id to the ORDER clause
5834 // so the order is deterministic
5835 if (strpos('contact_a.id', $order) === FALSE) {
5836 $order .= ", contact_a.id";
5840 elseif ($sortByChar) {
5841 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
5844 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
5848 // hack for order clause
5850 $fieldStr = trim(str_replace('ORDER BY', '', $order));
5851 $fieldOrder = explode(' ', $fieldStr);
5852 $field = $fieldOrder[0];
5858 $this->_whereTables
["civicrm_address"] = 1;
5859 $order = str_replace($field, "civicrm_address.{$field}", $order);
5863 case 'state_province':
5864 $this->_whereTables
["civicrm_{$field}"] = 1;
5865 $order = str_replace($field, "civicrm_{$field}.name", $order);
5869 $this->_whereTables
["civicrm_email"] = 1;
5870 $order = str_replace($field, "civicrm_email.{$field}", $order);
5874 //CRM-12565 add "`" around $field if it is a pseudo constant
5875 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5876 if (!empty($value['element']) && $value['element'] == $field) {
5877 $order = str_replace($field, "`{$field}`", $order);
5881 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
5882 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
5886 // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
5887 // clause. But this magic helper which forgivingly reescapes ORDER BY.
5888 // Note: $sortByChar implies that $order was hard-coded/trusted, so it can do funky things.
5889 if ($order && !$sortByChar) {
5890 $order = ' ORDER BY ' . CRM_Utils_Type
::escape(preg_replace('/^\s*ORDER BY\s*/', '', $order), 'MysqlOrderBy');
5891 return array($order, $additionalFromClause);
5893 return array($order, $additionalFromClause);