Merge pull request #12153 from JMAConsulting/dev_core_116
[civicrm-core.git] / CRM / Contact / BAO / Query.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2018
32 */
33
34 /**
35 * This is the heart of the search query building mechanism.
36 */
37 class CRM_Contact_BAO_Query {
38
39 /**
40 * The various search modes.
41 *
42 * As of February 2017, entries not present for 4, 32, 64, 1024.
43 *
44 * MODE_ALL seems to be out of sync with the available constants;
45 * if this is intentionally excluding MODE_MAILING then that may
46 * bear documenting?
47 *
48 * Likewise if there's reason for the missing modes (4, 32, 64 etc).
49 *
50 * @var int
51 */
52 const
53 NO_RETURN_PROPERTIES = 'CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES',
54 MODE_CONTACTS = 1,
55 MODE_CONTRIBUTE = 2,
56 // There is no 4,
57 MODE_MEMBER = 8,
58 MODE_EVENT = 16,
59 MODE_CONTACTSRELATED = 32,
60 // no 64.
61 MODE_GRANT = 128,
62 MODE_PLEDGEBANK = 256,
63 MODE_PLEDGE = 512,
64 // There is no 1024,
65 MODE_CASE = 2048,
66 MODE_ACTIVITY = 4096,
67 MODE_CAMPAIGN = 8192,
68 MODE_MAILING = 16384,
69 MODE_ALL = 17407;
70
71 /**
72 * Constants for search operators
73 */
74 const
75 SEARCH_OPERATOR_AND = 'AND',
76 SEARCH_OPERATOR_OR = 'OR';
77
78 /**
79 * The default set of return properties.
80 *
81 * @var array
82 */
83 static $_defaultReturnProperties = NULL;
84
85 /**
86 * The default set of hier return properties.
87 *
88 * @var array
89 */
90 static $_defaultHierReturnProperties;
91
92 /**
93 * The set of input params.
94 *
95 * @var array
96 */
97 public $_params;
98
99 public $_cfIDs;
100
101 public $_paramLookup;
102
103 public $_sort;
104
105 /**
106 * The set of output params
107 *
108 * @var array
109 */
110 public $_returnProperties;
111
112 /**
113 * The select clause
114 *
115 * @var array
116 */
117 public $_select;
118
119 /**
120 * The name of the elements that are in the select clause
121 * used to extract the values.
122 *
123 * @var array
124 */
125 public $_element;
126
127 /**
128 * The tables involved in the query.
129 *
130 * @var array
131 */
132 public $_tables;
133
134 /**
135 * The table involved in the where clause.
136 *
137 * @var array
138 */
139 public $_whereTables;
140
141 /**
142 * Array of WHERE clause components.
143 *
144 * @var array
145 */
146 public $_where;
147
148 /**
149 * The WHERE clause as a string.
150 *
151 * @var string
152 */
153 public $_whereClause;
154
155 /**
156 * Additional WHERE clause for permissions.
157 *
158 * @var string
159 */
160 public $_permissionWhereClause;
161
162 /**
163 * The from string
164 *
165 * @var string
166 */
167 public $_fromClause;
168
169 /**
170 * Additional permission from clause
171 *
172 * @var string
173 */
174 public $_permissionFromClause;
175
176 /**
177 * The from clause for the simple select and alphabetical
178 * select
179 *
180 * @var string
181 */
182 public $_simpleFromClause;
183
184 /**
185 * The having values
186 *
187 * @var string
188 */
189 public $_having;
190
191 /**
192 * The english language version of the query
193 *
194 * @var array
195 */
196 public $_qill;
197
198 /**
199 * All the fields that could potentially be involved in
200 * this query
201 *
202 * @var array
203 */
204 public $_fields;
205
206 /**
207 * The cache to translate the option values into labels.
208 *
209 * @var array
210 */
211 public $_options;
212
213 /**
214 * Are we in search mode.
215 *
216 * @var boolean
217 */
218 public $_search = TRUE;
219
220 /**
221 * Should we skip permission checking.
222 *
223 * @var boolean
224 */
225 public $_skipPermission = FALSE;
226
227 /**
228 * Should we skip adding of delete clause.
229 *
230 * @var boolean
231 */
232 public $_skipDeleteClause = FALSE;
233
234 /**
235 * Are we in strict mode (use equality over LIKE)
236 *
237 * @var boolean
238 */
239 public $_strict = FALSE;
240
241 /**
242 * What operator to use to group the clauses.
243 *
244 * @var string
245 */
246 public $_operator = 'AND';
247
248 public $_mode = 1;
249
250 /**
251 * Should we only search on primary location.
252 *
253 * @var boolean
254 */
255 public $_primaryLocation = TRUE;
256
257 /**
258 * Are contact ids part of the query.
259 *
260 * @var boolean
261 */
262 public $_includeContactIds = FALSE;
263
264 /**
265 * Should we use the smart group cache.
266 *
267 * @var boolean
268 */
269 public $_smartGroupCache = TRUE;
270
271 /**
272 * Should we display contacts with a specific relationship type.
273 *
274 * @var string
275 */
276 public $_displayRelationshipType = NULL;
277
278 /**
279 * Reference to the query object for custom values.
280 *
281 * @var Object
282 */
283 public $_customQuery;
284
285 /**
286 * Should we enable the distinct clause, used if we are including
287 * more than one group
288 *
289 * @var boolean
290 */
291 public $_useDistinct = FALSE;
292
293 /**
294 * Should we just display one contact record
295 */
296 public $_useGroupBy = FALSE;
297
298 /**
299 * The relationship type direction
300 *
301 * @var array
302 */
303 static $_relType;
304
305 /**
306 * The activity role
307 *
308 * @var array
309 */
310 static $_activityRole;
311
312 /**
313 * Consider the component activity type
314 * during activity search.
315 *
316 * @var array
317 */
318 static $_considerCompActivities;
319
320 /**
321 * Consider with contact activities only,
322 * during activity search.
323 *
324 * @var array
325 */
326 static $_withContactActivitiesOnly;
327
328 /**
329 * Use distinct component clause for component searches
330 *
331 * @var string
332 */
333 public $_distinctComponentClause;
334
335 public $_rowCountClause;
336
337 /**
338 * Use groupBy component clause for component searches
339 *
340 * @var string
341 */
342 public $_groupByComponentClause;
343
344 /**
345 * Track open panes, useful in advance search
346 *
347 * @var array
348 */
349 public static $_openedPanes = array();
350
351 /**
352 * For search builder - which custom fields are location-dependent
353 * @var array
354 */
355 public $_locationSpecificCustomFields = array();
356
357 /**
358 * The tables which have a dependency on location and/or address
359 *
360 * @var array
361 */
362 static $_dependencies = array(
363 'civicrm_state_province' => 1,
364 'civicrm_country' => 1,
365 'civicrm_county' => 1,
366 'civicrm_address' => 1,
367 'civicrm_location_type' => 1,
368 );
369
370 /**
371 * List of location specific fields.
372 */
373 static $_locationSpecificFields = array(
374 'street_address',
375 'street_number',
376 'street_name',
377 'street_unit',
378 'supplemental_address_1',
379 'supplemental_address_2',
380 'supplemental_address_3',
381 'city',
382 'postal_code',
383 'postal_code_suffix',
384 'geo_code_1',
385 'geo_code_2',
386 'state_province',
387 'country',
388 'county',
389 'phone',
390 'email',
391 'im',
392 'address_name',
393 'master_id',
394 );
395
396 /**
397 * Remember if we handle either end of a number or date range
398 * so we can skip the other
399 */
400 protected $_rangeCache = array();
401 /**
402 * Set to true when $this->relationship is run to avoid adding twice
403 * @var Boolean
404 */
405 protected $_relationshipValuesAdded = FALSE;
406
407 /**
408 * Set to the name of the temp table if one has been created
409 * @var String
410 */
411 static $_relationshipTempTable = NULL;
412
413 public $_pseudoConstantsSelect = array();
414
415 /**
416 * Class constructor which also does all the work.
417 *
418 * @param array $params
419 * @param array $returnProperties
420 * @param array $fields
421 * @param bool $includeContactIds
422 * @param bool $strict
423 * @param bool|int $mode - mode the search is operating on
424 *
425 * @param bool $skipPermission
426 * @param bool $searchDescendentGroups
427 * @param bool $smartGroupCache
428 * @param null $displayRelationshipType
429 * @param string $operator
430 * @param string $apiEntity
431 * @param bool|NULL $primaryLocationOnly
432 */
433 public function __construct(
434 $params = NULL, $returnProperties = NULL, $fields = NULL,
435 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
436 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
437 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
438 $operator = 'AND',
439 $apiEntity = NULL,
440 $primaryLocationOnly = NULL
441 ) {
442 if ($primaryLocationOnly === NULL) {
443 $primaryLocationOnly = Civi::settings()->get('searchPrimaryDetailsOnly');
444 }
445 $this->_primaryLocation = $primaryLocationOnly;
446 $this->_params = &$params;
447 if ($this->_params == NULL) {
448 $this->_params = array();
449 }
450
451 if ($returnProperties === self::NO_RETURN_PROPERTIES) {
452 $this->_returnProperties = array();
453 }
454 elseif (empty($returnProperties)) {
455 $this->_returnProperties = self::defaultReturnProperties($mode);
456 }
457 else {
458 $this->_returnProperties = &$returnProperties;
459 }
460
461 $this->_includeContactIds = $includeContactIds;
462 $this->_strict = $strict;
463 $this->_mode = $mode;
464 $this->_skipPermission = $skipPermission;
465 $this->_smartGroupCache = $smartGroupCache;
466 $this->_displayRelationshipType = $displayRelationshipType;
467 $this->setOperator($operator);
468
469 if ($fields) {
470 $this->_fields = &$fields;
471 $this->_search = FALSE;
472 $this->_skipPermission = TRUE;
473 }
474 else {
475 $this->_fields = CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE, TRUE, FALSE, !$skipPermission);
476
477 $fields = CRM_Core_Component::getQueryFields(!$this->_skipPermission);
478 unset($fields['note']);
479 $this->_fields = array_merge($this->_fields, $fields);
480
481 // add activity fields
482 $fields = CRM_Activity_BAO_Activity::exportableFields();
483 $this->_fields = array_merge($this->_fields, $fields);
484
485 // add any fields provided by hook implementers
486 $extFields = CRM_Contact_BAO_Query_Hook::singleton()->getFields();
487 $this->_fields = array_merge($this->_fields, $extFields);
488 }
489
490 // basically do all the work once, and then reuse it
491 $this->initialize($apiEntity);
492 }
493
494 /**
495 * Function which actually does all the work for the constructor.
496 *
497 * @param string $apiEntity
498 * The api entity being called.
499 * This sort-of duplicates $mode in a confusing way. Probably not by design.
500 */
501 public function initialize($apiEntity = NULL) {
502 $this->_select = array();
503 $this->_element = array();
504 $this->_tables = array();
505 $this->_whereTables = array();
506 $this->_where = array();
507 $this->_qill = array();
508 $this->_options = array();
509 $this->_cfIDs = array();
510 $this->_paramLookup = array();
511 $this->_having = array();
512
513 $this->_customQuery = NULL;
514
515 // reset cached static variables - CRM-5803
516 self::$_activityRole = NULL;
517 self::$_considerCompActivities = NULL;
518 self::$_withContactActivitiesOnly = NULL;
519
520 $this->_select['contact_id'] = 'contact_a.id as contact_id';
521 $this->_element['contact_id'] = 1;
522 $this->_tables['civicrm_contact'] = 1;
523
524 if (!empty($this->_params)) {
525 $this->buildParamsLookup();
526 }
527
528 $this->_whereTables = $this->_tables;
529
530 $this->selectClause($apiEntity);
531 $this->_whereClause = $this->whereClause($apiEntity);
532 if (array_key_exists('civicrm_contribution', $this->_whereTables)) {
533 $component = 'contribution';
534 }
535 if (array_key_exists('civicrm_membership', $this->_whereTables)) {
536 $component = 'membership';
537 }
538 if (isset($component)) {
539 CRM_Financial_BAO_FinancialType::buildPermissionedClause($this->_whereClause, $component);
540 }
541
542 $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode, $apiEntity);
543 $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode);
544
545 $this->openedSearchPanes(TRUE);
546 }
547
548 /**
549 * Function for same purpose as convertFormValues.
550 *
551 * Like convert form values this function exists to pre-Process parameters from the form.
552 *
553 * It is unclear why they are different functions & likely relates to advances search
554 * versus search builder.
555 *
556 * The direction we are going is having the form convert values to a standardised format &
557 * moving away from weird & wonderful where clause switches.
558 *
559 * Fix and handle contact deletion nicely.
560 *
561 * this code is primarily for search builder use case where different clauses can specify if they want deleted.
562 *
563 * CRM-11971
564 */
565 public function buildParamsLookup() {
566 $trashParamExists = FALSE;
567 $paramByGroup = array();
568 foreach ($this->_params as $k => $param) {
569 if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
570 $trashParamExists = TRUE;
571 }
572 if (!empty($param[3])) {
573 $paramByGroup[$param[3]][$k] = $param;
574 }
575 }
576
577 if ($trashParamExists) {
578 $this->_skipDeleteClause = TRUE;
579
580 //cycle through group sets and explicitly add trash param if not set
581 foreach ($paramByGroup as $setID => $set) {
582 if (
583 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params) &&
584 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params)
585 ) {
586 $this->_params[] = array(
587 'contact_is_deleted',
588 '=',
589 '0',
590 $setID,
591 '0',
592 );
593 }
594 }
595 }
596
597 foreach ($this->_params as $value) {
598 if (empty($value[0])) {
599 continue;
600 }
601 $cfID = CRM_Core_BAO_CustomField::getKeyID($value[0]);
602 if ($cfID) {
603 if (!array_key_exists($cfID, $this->_cfIDs)) {
604 $this->_cfIDs[$cfID] = array();
605 }
606 // Set wildcard value based on "and/or" selection
607 foreach ($this->_params as $key => $param) {
608 if ($param[0] == $value[0] . '_operator') {
609 $value[4] = $param[2] == 'or';
610 break;
611 }
612 }
613 $this->_cfIDs[$cfID][] = $value;
614 }
615
616 if (!array_key_exists($value[0], $this->_paramLookup)) {
617 $this->_paramLookup[$value[0]] = array();
618 }
619 if ($value[0] !== 'group') {
620 // Just trying to unravel how group interacts here! This whole function is weird.
621 $this->_paramLookup[$value[0]][] = $value;
622 }
623 }
624 }
625
626 /**
627 * Some composite fields do not appear in the fields array hack to make them part of the query.
628 *
629 * @param $apiEntity
630 * The api entity being called.
631 * This sort-of duplicates $mode in a confusing way. Probably not by design.
632 */
633 public function addSpecialFields($apiEntity) {
634 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
635 // if get called via Contact.get API having address_id as return parameter
636 if ($apiEntity == 'Contact') {
637 $special[] = 'address_id';
638 }
639 foreach ($special as $name) {
640 if (!empty($this->_returnProperties[$name])) {
641 if ($name == 'address_id') {
642 $this->_tables['civicrm_address'] = 1;
643 $this->_select['address_id'] = 'civicrm_address.id as address_id';
644 $this->_element['address_id'] = 1;
645 }
646 else {
647 $this->_select[$name] = "contact_a.{$name} as $name";
648 $this->_element[$name] = 1;
649 }
650 }
651 }
652 }
653
654 /**
655 * Given a list of conditions in params and a list of desired
656 * return Properties generate the required select and from
657 * clauses. Note that since the where clause introduces new
658 * tables, the initial attempt also retrieves all variables used
659 * in the params list
660 *
661 * @param string $apiEntity
662 * The api entity being called.
663 * This sort-of duplicates $mode in a confusing way. Probably not by design.
664 */
665 public function selectClause($apiEntity = NULL) {
666
667 // @todo Tidy up this. This arises because 1) we are ignoring the $mode & adding a new
668 // param ($apiEntity) instead - presumably an oversight & 2 because
669 // contact is not implemented as a component.
670 $this->addSpecialFields($apiEntity);
671
672 foreach ($this->_fields as $name => $field) {
673 // skip component fields
674 // there are done by the alter query below
675 // and need not be done on every field
676 // @todo remove these & handle using metadata - only obscure fields
677 // that are hack-added should need to be excluded from the main loop.
678 if (
679 (substr($name, 0, 12) == 'participant_') ||
680 (substr($name, 0, 7) == 'pledge_') ||
681 (substr($name, 0, 5) == 'case_')
682 ) {
683 continue;
684 }
685
686 // redirect to activity select clause
687 if (
688 (substr($name, 0, 9) == 'activity_') ||
689 ($name == 'parent_id')
690 ) {
691 CRM_Activity_BAO_Query::select($this);
692 }
693
694 // if this is a hierarchical name, we ignore it
695 $names = explode('-', $name);
696 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
697 continue;
698 }
699
700 // make an exception for special cases, to add the field in select clause
701 $makeException = FALSE;
702
703 //special handling for groups/tags
704 if (in_array($name, array('groups', 'tags', 'notes'))
705 && isset($this->_returnProperties[substr($name, 0, -1)])
706 ) {
707 // @todo instead of setting make exception to get us into
708 // an if clause that has handling for these fields buried with in it
709 // move the handling to here.
710 $makeException = TRUE;
711 }
712
713 // since note has 3 different options we need special handling
714 // note / note_subject / note_body
715 if ($name == 'notes') {
716 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
717 if (isset($this->_returnProperties[$noteField])) {
718 $makeException = TRUE;
719 break;
720 }
721 }
722 }
723
724 $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
725 if (
726 !empty($this->_paramLookup[$name])
727 || !empty($this->_returnProperties[$name])
728 || $this->pseudoConstantNameIsInReturnProperties($field)
729 || $makeException
730 ) {
731 if ($cfID) {
732 // add to cfIDs array if not present
733 if (!array_key_exists($cfID, $this->_cfIDs)) {
734 $this->_cfIDs[$cfID] = array();
735 }
736 }
737 elseif (isset($field['where'])) {
738 list($tableName, $fieldName) = explode('.', $field['where'], 2);
739 if (isset($tableName)) {
740 if (CRM_Utils_Array::value($tableName, self::$_dependencies)) {
741 $this->_tables['civicrm_address'] = 1;
742 $this->_select['address_id'] = 'civicrm_address.id as address_id';
743 $this->_element['address_id'] = 1;
744 }
745
746 if ($tableName == 'im_provider' || $tableName == 'email_greeting' ||
747 $tableName == 'postal_greeting' || $tableName == 'addressee'
748 ) {
749 if ($tableName == 'im_provider') {
750 CRM_Core_OptionValue::select($this);
751 }
752
753 if (in_array($tableName,
754 array('email_greeting', 'postal_greeting', 'addressee'))) {
755 $this->_element["{$name}_id"] = 1;
756 $this->_select["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
757 $this->_pseudoConstantsSelect[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
758 $this->_pseudoConstantsSelect[$name]['select'] = "{$name}.{$fieldName} as $name";
759 $this->_pseudoConstantsSelect[$name]['element'] = $name;
760
761 if ($tableName == 'email_greeting') {
762 // @todo bad join.
763 $this->_pseudoConstantsSelect[$name]['join']
764 = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
765 $this->_pseudoConstantsSelect[$name]['join'] .=
766 " 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 ) ";
767 }
768 elseif ($tableName == 'postal_greeting') {
769 // @todo bad join.
770 $this->_pseudoConstantsSelect[$name]['join']
771 = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
772 $this->_pseudoConstantsSelect[$name]['join'] .=
773 " 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 ) ";
774 }
775 elseif ($tableName == 'addressee') {
776 // @todo bad join.
777 $this->_pseudoConstantsSelect[$name]['join']
778 = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
779 $this->_pseudoConstantsSelect[$name]['join'] .=
780 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
781 }
782 $this->_pseudoConstantsSelect[$name]['table'] = $tableName;
783
784 //get display
785 $greetField = "{$name}_display";
786 $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}";
787 $this->_element[$greetField] = 1;
788 //get custom
789 $greetField = "{$name}_custom";
790 $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}";
791 $this->_element[$greetField] = 1;
792 }
793 }
794 else {
795 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
796 $this->_tables[$tableName] = 1;
797 }
798
799 // also get the id of the tableName
800 $tName = substr($tableName, 8);
801 if (in_array($tName, array('country', 'state_province', 'county'))) {
802 if ($tName == 'state_province') {
803 $this->_pseudoConstantsSelect['state_province_name'] = array(
804 'pseudoField' => "{$tName}",
805 'idCol' => "{$tName}_id",
806 'bao' => 'CRM_Core_BAO_Address',
807 'table' => "civicrm_{$tName}",
808 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
809 );
810
811 $this->_pseudoConstantsSelect[$tName] = array(
812 'pseudoField' => 'state_province_abbreviation',
813 'idCol' => "{$tName}_id",
814 'table' => "civicrm_{$tName}",
815 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
816 );
817 }
818 else {
819 $this->_pseudoConstantsSelect[$name] = array(
820 'pseudoField' => "{$tName}_id",
821 'idCol' => "{$tName}_id",
822 'bao' => 'CRM_Core_BAO_Address',
823 'table' => "civicrm_{$tName}",
824 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
825 );
826 }
827
828 $this->_select["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
829 $this->_element["{$tName}_id"] = 1;
830 }
831 elseif ($tName != 'contact') {
832 $this->_select["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
833 $this->_element["{$tName}_id"] = 1;
834 }
835
836 //special case for phone
837 if ($name == 'phone') {
838 $this->_select['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
839 $this->_element['phone_type_id'] = 1;
840 }
841
842 // if IM then select provider_id also
843 // to get "IM Service Provider" in a file to be exported, CRM-3140
844 if ($name == 'im') {
845 $this->_select['provider_id'] = "civicrm_im.provider_id as provider_id";
846 $this->_element['provider_id'] = 1;
847 }
848
849 if ($tName == 'contact' && $fieldName == 'organization_name') {
850 // special case, when current employer is set for Individual contact
851 $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
852 }
853 elseif ($tName == 'contact' && $fieldName === 'id') {
854 // Handled elsewhere, explicitly ignore. Possibly for all tables...
855 }
856 elseif (in_array($tName, array('country', 'county'))) {
857 $this->_pseudoConstantsSelect[$name]['select'] = "{$field['where']} as `$name`";
858 $this->_pseudoConstantsSelect[$name]['element'] = $name;
859 }
860 elseif ($tName == 'state_province') {
861 $this->_pseudoConstantsSelect[$tName]['select'] = "{$field['where']} as `$name`";
862 $this->_pseudoConstantsSelect[$tName]['element'] = $name;
863 }
864 elseif (strpos($name, 'contribution_soft_credit') !== FALSE) {
865 if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled($this->_params)) {
866 $this->_select[$name] = "{$field['where']} as `$name`";
867 }
868 }
869 else {
870 // If we have an option group defined then rather than joining the option value table in
871 // (which is an unindexed join) we render the option value on output.
872 // @todo - extend this to other pseudoconstants.
873 if ($this->pseudoConstantNameIsInReturnProperties($field, $name)) {
874 $pseudoFieldName = $field['pseudoconstant']['optionGroupName'];
875 $this->_pseudoConstantsSelect[$pseudoFieldName] = array(
876 'pseudoField' => $field['name'],
877 'idCol' => $name,
878 'field_name' => $field['name'],
879 'bao' => $field['bao'],
880 'pseudoconstant' => $field['pseudoconstant'],
881 );
882 $this->_tables[$tableName] = 1;
883 $this->_element[$pseudoFieldName] = 1;
884 }
885 $this->_select[$name] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$name`");
886 }
887 if (!in_array($tName, array('state_province', 'country', 'county'))) {
888 $this->_element[$name] = 1;
889 }
890 }
891 }
892 }
893 elseif ($name === 'tags') {
894 //@todo move this handling outside the big IF & ditch $makeException
895 $this->_useGroupBy = TRUE;
896 $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
897 $this->_element[$name] = 1;
898 $this->_tables['civicrm_tag'] = 1;
899 $this->_tables['civicrm_entity_tag'] = 1;
900 }
901 elseif ($name === 'groups') {
902 //@todo move this handling outside the big IF & ditch $makeException
903 $this->_useGroupBy = TRUE;
904 // Duplicates will be created here but better to sort them out in php land.
905 $this->_select[$name] = "
906 CONCAT_WS(',',
907 GROUP_CONCAT(DISTINCT IF(civicrm_group_contact.status = 'Added', civicrm_group_contact.group_id, '')),
908 GROUP_CONCAT(DISTINCT civicrm_group_contact_cache.group_id)
909 )
910 as groups";
911 $this->_element[$name] = 1;
912 $this->_tables['civicrm_group_contact'] = 1;
913 $this->_tables['civicrm_group_contact_cache'] = 1;
914 $this->_pseudoConstantsSelect["{$name}"] = array(
915 'pseudoField' => "groups",
916 'idCol' => "groups",
917 );
918 }
919 elseif ($name === 'notes') {
920 //@todo move this handling outside the big IF & ditch $makeException
921 // if note field is subject then return subject else body of the note
922 $noteColumn = 'note';
923 if (isset($noteField) && $noteField == 'note_subject') {
924 $noteColumn = 'subject';
925 }
926
927 $this->_useGroupBy = TRUE;
928 $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
929 $this->_element[$name] = 1;
930 $this->_tables['civicrm_note'] = 1;
931 }
932 elseif ($name === 'current_employer') {
933 $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
934 $this->_element[$name] = 1;
935 }
936 }
937
938 if ($cfID && !empty($field['is_search_range'])) {
939 // this is a custom field with range search enabled, so we better check for two/from values
940 if (!empty($this->_paramLookup[$name . '_from'])) {
941 if (!array_key_exists($cfID, $this->_cfIDs)) {
942 $this->_cfIDs[$cfID] = array();
943 }
944 foreach ($this->_paramLookup[$name . '_from'] as $pID => $p) {
945 // search in the cdID array for the same grouping
946 $fnd = FALSE;
947 foreach ($this->_cfIDs[$cfID] as $cID => $c) {
948 if ($c[3] == $p[3]) {
949 $this->_cfIDs[$cfID][$cID][2]['from'] = $p[2];
950 $fnd = TRUE;
951 }
952 }
953 if (!$fnd) {
954 $p[2] = array('from' => $p[2]);
955 $this->_cfIDs[$cfID][] = $p;
956 }
957 }
958 }
959 if (!empty($this->_paramLookup[$name . '_to'])) {
960 if (!array_key_exists($cfID, $this->_cfIDs)) {
961 $this->_cfIDs[$cfID] = array();
962 }
963 foreach ($this->_paramLookup[$name . '_to'] as $pID => $p) {
964 // search in the cdID array for the same grouping
965 $fnd = FALSE;
966 foreach ($this->_cfIDs[$cfID] as $cID => $c) {
967 if ($c[4] == $p[4]) {
968 $this->_cfIDs[$cfID][$cID][2]['to'] = $p[2];
969 $fnd = TRUE;
970 }
971 }
972 if (!$fnd) {
973 $p[2] = array('to' => $p[2]);
974 $this->_cfIDs[$cfID][] = $p;
975 }
976 }
977 }
978 }
979 }
980
981 // add location as hierarchical elements
982 $this->addHierarchicalElements();
983
984 // add multiple field like website
985 $this->addMultipleElements();
986
987 //fix for CRM-951
988 CRM_Core_Component::alterQuery($this, 'select');
989
990 CRM_Contact_BAO_Query_Hook::singleton()->alterSearchQuery($this, 'select');
991
992 if (!empty($this->_cfIDs)) {
993 // @todo This function is the select function but instead of running 'select' it
994 // is running the whole query.
995 $this->_customQuery = new CRM_Core_BAO_CustomQuery($this->_cfIDs, TRUE, $this->_locationSpecificCustomFields);
996 $this->_customQuery->query();
997 $this->_select = array_merge($this->_select, $this->_customQuery->_select);
998 $this->_element = array_merge($this->_element, $this->_customQuery->_element);
999 $this->_tables = array_merge($this->_tables, $this->_customQuery->_tables);
1000 $this->_whereTables = array_merge($this->_whereTables, $this->_customQuery->_whereTables);
1001 $this->_options = $this->_customQuery->_options;
1002 }
1003 }
1004
1005 /**
1006 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1007 */
1008 public function addHierarchicalElements() {
1009 if (empty($this->_returnProperties['location'])) {
1010 return;
1011 }
1012 if (!is_array($this->_returnProperties['location'])) {
1013 return;
1014 }
1015
1016 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
1017 $processed = array();
1018 $index = 0;
1019
1020 $addressCustomFields = CRM_Core_BAO_CustomField::getFieldsForImport('Address');
1021 $addressCustomFieldIds = array();
1022
1023 foreach ($this->_returnProperties['location'] as $name => $elements) {
1024 $lCond = self::getPrimaryCondition($name);
1025
1026 if (!$lCond) {
1027 $locationTypeId = array_search($name, $locationTypes);
1028 if ($locationTypeId === FALSE) {
1029 continue;
1030 }
1031 $lCond = "location_type_id = $locationTypeId";
1032 $this->_useDistinct = TRUE;
1033
1034 //commented for CRM-3256
1035 $this->_useGroupBy = TRUE;
1036 }
1037
1038 $name = str_replace(' ', '_', $name);
1039
1040 $tName = "$name-location_type";
1041 $ltName = "`$name-location_type`";
1042 $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1043 $this->_select["{$tName}"] = "`$tName`.name as `{$tName}`";
1044 $this->_element["{$tName}_id"] = 1;
1045 $this->_element["{$tName}"] = 1;
1046
1047 $locationTypeName = $tName;
1048 $locationTypeJoin = array();
1049
1050 $addAddress = FALSE;
1051 $addWhereCount = 0;
1052 foreach ($elements as $elementFullName => $dontCare) {
1053 $index++;
1054 $elementName = $elementCmpName = $elementFullName;
1055
1056 if (substr($elementCmpName, 0, 5) == 'phone') {
1057 $elementCmpName = 'phone';
1058 }
1059
1060 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
1061 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($elementCmpName)) {
1062 $addressCustomFieldIds[$cfID][$name] = 1;
1063 }
1064 }
1065 //add address table only once
1066 if ((in_array($elementCmpName, self::$_locationSpecificFields) || !empty($addressCustomFieldIds))
1067 && !$addAddress
1068 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
1069 ) {
1070 $tName = "$name-address";
1071 $aName = "`$name-address`";
1072 $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1073 $this->_element["{$tName}_id"] = 1;
1074 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
1075 $this->_tables[$tName] = $addressJoin;
1076 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1077 $processed[$aName] = 1;
1078 $addAddress = TRUE;
1079 }
1080
1081 $cond = $elementType = '';
1082 if (strpos($elementName, '-') !== FALSE) {
1083 // this is either phone, email or IM
1084 list($elementName, $elementType) = explode('-', $elementName);
1085
1086 if (($elementName != 'phone') && ($elementName != 'im')) {
1087 $cond = self::getPrimaryCondition($elementType);
1088 }
1089 // CRM-13011 : If location type is primary, do not restrict search to the phone
1090 // type id - we want the primary phone, regardless of what type it is.
1091 // Otherwise, restrict to the specified phone type for the given field.
1092 if ((!$cond) && ($elementName == 'phone')) {
1093 $cond = "phone_type_id = '$elementType'";
1094 }
1095 elseif ((!$cond) && ($elementName == 'im')) {
1096 // IM service provider id, CRM-3140
1097 $cond = "provider_id = '$elementType'";
1098 }
1099 $elementType = '-' . $elementType;
1100 }
1101
1102 $field = CRM_Utils_Array::value($elementName, $this->_fields);
1103
1104 // hack for profile, add location id
1105 if (!$field) {
1106 if ($elementType &&
1107 // fix for CRM-882( to handle phone types )
1108 !is_numeric($elementType)
1109 ) {
1110 if (is_numeric($name)) {
1111 $field = CRM_Utils_Array::value($elementName . "-Primary$elementType", $this->_fields);
1112 }
1113 else {
1114 $field = CRM_Utils_Array::value($elementName . "-$locationTypeId$elementType", $this->_fields);
1115 }
1116 }
1117 elseif (is_numeric($name)) {
1118 //this for phone type to work
1119 if (in_array($elementName, array('phone', 'phone_ext'))) {
1120 $field = CRM_Utils_Array::value($elementName . "-Primary" . $elementType, $this->_fields);
1121 }
1122 else {
1123 $field = CRM_Utils_Array::value($elementName . "-Primary", $this->_fields);
1124 }
1125 }
1126 else {
1127 //this is for phone type to work for profile edit
1128 if (in_array($elementName, array('phone', 'phone_ext'))) {
1129 $field = CRM_Utils_Array::value($elementName . "-$locationTypeId$elementType", $this->_fields);
1130 }
1131 else {
1132 $field = CRM_Utils_Array::value($elementName . "-$locationTypeId", $this->_fields);
1133 }
1134 }
1135 }
1136
1137 // Check if there is a value, if so also add to where Clause
1138 $addWhere = FALSE;
1139 if ($this->_params) {
1140 $nm = $elementName;
1141 if (isset($locationTypeId)) {
1142 $nm .= "-$locationTypeId";
1143 }
1144 if (!is_numeric($elementType)) {
1145 $nm .= "$elementType";
1146 }
1147
1148 foreach ($this->_params as $id => $values) {
1149 if ((is_array($values) && $values[0] == $nm) ||
1150 (in_array($elementName, array('phone', 'im'))
1151 && (strpos($values[0], $nm) !== FALSE)
1152 )
1153 ) {
1154 $addWhere = TRUE;
1155 $addWhereCount++;
1156 break;
1157 }
1158 }
1159 }
1160
1161 if ($field && isset($field['where'])) {
1162 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1163 $pf = substr($tableName, 8);
1164 $tName = $name . '-' . $pf . $elementType;
1165 if (isset($tableName)) {
1166 if ($tableName == 'civicrm_state_province' || $tableName == 'civicrm_country' || $tableName == 'civicrm_county') {
1167 $this->_select["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1168 }
1169 else {
1170 $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1171 }
1172
1173 $this->_element["{$tName}_id"] = 1;
1174 if (substr($tName, -15) == '-state_province') {
1175 // FIXME: hack to fix CRM-1900
1176 $a = Civi::settings()->get('address_format');
1177
1178 if (substr_count($a, 'state_province_name') > 0) {
1179 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = array(
1180 'pseudoField' => "{$pf}_id",
1181 'idCol' => "{$tName}_id",
1182 'bao' => 'CRM_Core_BAO_Address',
1183 );
1184 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1185 }
1186 else {
1187 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = array(
1188 'pseudoField' => 'state_province_abbreviation',
1189 'idCol' => "{$tName}_id",
1190 );
1191 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1192 }
1193 }
1194 else {
1195 if (substr($elementFullName, 0, 2) == 'im') {
1196 $provider = "{$name}-{$elementFullName}-provider_id";
1197 $this->_select[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1198 $this->_element[$provider] = 1;
1199 }
1200 if ($pf == 'country' || $pf == 'county') {
1201 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = array(
1202 'pseudoField' => "{$pf}_id",
1203 'idCol' => "{$tName}_id",
1204 'bao' => 'CRM_Core_BAO_Address',
1205 );
1206 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1207 }
1208 else {
1209 $this->_select["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1210 }
1211 }
1212
1213 if (in_array($pf, array('state_province', 'country', 'county'))) {
1214 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1215 }
1216 else {
1217 $this->_element["{$name}-{$elementFullName}"] = 1;
1218 }
1219
1220 if (empty($processed["`$tName`"])) {
1221 $processed["`$tName`"] = 1;
1222 $newName = $tableName . '_' . $index;
1223 switch ($tableName) {
1224 case 'civicrm_phone':
1225 case 'civicrm_email':
1226 case 'civicrm_im':
1227 case 'civicrm_openid':
1228
1229 $this->_tables[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1230 if ($tableName != 'civicrm_phone') {
1231 $this->_tables[$tName] .= " AND `$tName`.$lCond";
1232 }
1233 elseif (is_numeric($name)) {
1234 $this->_select[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1235 }
1236
1237 // this special case to add phone type
1238 if ($cond) {
1239 $phoneTypeCondition = " AND `$tName`.$cond ";
1240 //gross hack to pickup corrupted data also, CRM-7603
1241 if (strpos($cond, 'phone_type_id') !== FALSE) {
1242 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1243 if (!empty($lCond)) {
1244 $phoneTypeCondition .= " AND ( `$tName`.$lCond ) ";
1245 }
1246 }
1247 $this->_tables[$tName] .= $phoneTypeCondition;
1248 }
1249
1250 //build locationType join
1251 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1252
1253 if ($addWhere) {
1254 $this->_whereTables[$tName] = $this->_tables[$tName];
1255 }
1256 break;
1257
1258 case 'civicrm_state_province':
1259 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['table'] = $tName;
1260 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['join']
1261 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1262 if ($addWhere) {
1263 $this->_whereTables["{$name}-address"] = $addressJoin;
1264 }
1265 break;
1266
1267 case 'civicrm_country':
1268 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['table'] = $newName;
1269 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['join']
1270 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1271 if ($addWhere) {
1272 $this->_whereTables["{$name}-address"] = $addressJoin;
1273 }
1274 break;
1275
1276 case 'civicrm_county':
1277 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['table'] = $newName;
1278 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['join']
1279 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1280 if ($addWhere) {
1281 $this->_whereTables["{$name}-address"] = $addressJoin;
1282 }
1283 break;
1284
1285 default:
1286 if ($addWhere) {
1287 $this->_whereTables["{$name}-address"] = $addressJoin;
1288 }
1289 break;
1290 }
1291 }
1292 }
1293 }
1294 }
1295
1296 // add location type join
1297 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1298 $this->_tables[$locationTypeName] = $ltypeJoin;
1299
1300 // table should be present in $this->_whereTables,
1301 // to add its condition in location type join, CRM-3939.
1302 if ($addWhereCount) {
1303 $locClause = array();
1304 foreach ($this->_whereTables as $tableName => $clause) {
1305 if (!empty($locationTypeJoin[$tableName])) {
1306 $locClause[] = $locationTypeJoin[$tableName];
1307 }
1308 }
1309
1310 if (!empty($locClause)) {
1311 $this->_whereTables[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1312 }
1313 }
1314 }
1315
1316 if (!empty($addressCustomFieldIds)) {
1317 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1318 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1319 foreach ($locTypeName as $name => $dnc) {
1320 $this->_locationSpecificCustomFields[$cfID] = array($name, array_search($name, $locationTypes));
1321 $fieldName = "$name-custom_{$cfID}";
1322 $tName = "$name-address-custom-{$cfID}";
1323 $aName = "`$name-address-custom-{$cfID}`";
1324 $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1325 $this->_element["{$tName}_id"] = 1;
1326 $this->_select[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1327 $this->_element[$fieldName] = 1;
1328 $this->_tables[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1329 }
1330 }
1331 }
1332 }
1333
1334 /**
1335 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1336 */
1337 public function addMultipleElements() {
1338 if (empty($this->_returnProperties['website'])) {
1339 return;
1340 }
1341 if (!is_array($this->_returnProperties['website'])) {
1342 return;
1343 }
1344
1345 foreach ($this->_returnProperties['website'] as $key => $elements) {
1346 foreach ($elements as $elementFullName => $dontCare) {
1347 $tName = "website-{$key}-{$elementFullName}";
1348 $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1349 $this->_select["{$tName}"] = "`$tName`.url as `{$tName}`";
1350 $this->_element["{$tName}_id"] = 1;
1351 $this->_element["{$tName}"] = 1;
1352
1353 $type = "website-{$key}-website_type_id";
1354 $this->_select[$type] = "`$tName`.website_type_id as `{$type}`";
1355 $this->_element[$type] = 1;
1356 $this->_tables[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1357 }
1358 }
1359 }
1360
1361 /**
1362 * Generate the query based on what type of query we need.
1363 *
1364 * @param bool $count
1365 * @param bool $sortByChar
1366 * @param bool $groupContacts
1367 * @param bool $onlyDeleted
1368 *
1369 * @return array
1370 * sql query parts as an array
1371 */
1372 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1373 // build permission clause
1374 $this->generatePermissionClause($onlyDeleted, $count);
1375
1376 if ($count) {
1377 if (isset($this->_rowCountClause)) {
1378 $select = "SELECT {$this->_rowCountClause}";
1379 }
1380 elseif (isset($this->_distinctComponentClause)) {
1381 // we add distinct to get the right count for components
1382 // for the more complex result set, we use GROUP BY the same id
1383 // CRM-9630
1384 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} ) as rowCount";
1385 }
1386 else {
1387 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1388 }
1389 $from = $this->_simpleFromClause;
1390 if ($this->_useDistinct) {
1391 $this->_useGroupBy = TRUE;
1392 }
1393 }
1394 elseif ($sortByChar) {
1395 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1396 $from = $this->_simpleFromClause;
1397 }
1398 elseif ($groupContacts) {
1399 $select = 'SELECT contact_a.id as id';
1400 if ($this->_useDistinct) {
1401 $this->_useGroupBy = TRUE;
1402 }
1403 $from = $this->_simpleFromClause;
1404 }
1405 else {
1406 if (!empty($this->_paramLookup['group'])) {
1407
1408 list($name, $op, $value, $grouping, $wildcard) = $this->_paramLookup['group'][0];
1409
1410 if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
1411 $this->_paramLookup['group'][0][1] = key($value);
1412 }
1413
1414 // Presumably the lines below come into manage groups screen.
1415 // make sure there is only one element
1416 // this is used when we are running under smog and need to know
1417 // how the contact was added (CRM-1203)
1418 $groups = (array) CRM_Utils_Array::value($this->_paramLookup['group'][0][1], $this->_paramLookup['group'][0][2], $this->_paramLookup['group'][0][2]);
1419 if ((count($this->_paramLookup['group']) == 1) &&
1420 (count($groups) == 1)
1421 ) {
1422 $groupId = $groups[0];
1423
1424 //check if group is saved search
1425 $group = new CRM_Contact_BAO_Group();
1426 $group->id = $groupId;
1427 $group->find(TRUE);
1428
1429 if (!isset($group->saved_search_id)) {
1430 $tbName = "`civicrm_group_contact-{$groupId}`";
1431 // CRM-17254 don't retrieve extra fields if contact_id is specifically requested
1432 // as this will add load to an intentionally light query.
1433 // ideally this code would be removed as it appears to be to support CRM-1203
1434 // and passing in the required returnProperties from the url would
1435 // make more sense that globally applying the requirements of one form.
1436 if (($this->_returnProperties != array('contact_id'))) {
1437 $this->_select['group_contact_id'] = "$tbName.id as group_contact_id";
1438 $this->_element['group_contact_id'] = 1;
1439 $this->_select['status'] = "$tbName.status as status";
1440 $this->_element['status'] = 1;
1441 }
1442 }
1443 }
1444 $this->_useGroupBy = TRUE;
1445 }
1446 if ($this->_useDistinct && !isset($this->_distinctComponentClause)) {
1447 if (!($this->_mode & CRM_Contact_BAO_Query::MODE_ACTIVITY)) {
1448 // CRM-5954
1449 $this->_select['contact_id'] = 'contact_a.id as contact_id';
1450 $this->_useDistinct = FALSE;
1451 $this->_useGroupBy = TRUE;
1452 }
1453 }
1454
1455 $select = $this->getSelect();
1456 $from = $this->_fromClause;
1457 }
1458
1459 $where = '';
1460 if (!empty($this->_whereClause)) {
1461 $where = "WHERE {$this->_whereClause}";
1462 }
1463
1464 if (!empty($this->_permissionWhereClause) && empty($this->_displayRelationshipType)) {
1465 if (empty($where)) {
1466 $where = "WHERE $this->_permissionWhereClause";
1467 }
1468 else {
1469 $where = "$where AND $this->_permissionWhereClause";
1470 }
1471 }
1472
1473 $having = '';
1474 if (!empty($this->_having)) {
1475 foreach ($this->_having as $havingSets) {
1476 foreach ($havingSets as $havingSet) {
1477 $havingValue[] = $havingSet;
1478 }
1479 }
1480 $having = ' HAVING ' . implode(' AND ', $havingValue);
1481 }
1482
1483 // if we are doing a transform, do it here
1484 // use the $from, $where and $having to get the contact ID
1485 if ($this->_displayRelationshipType) {
1486 $this->filterRelatedContacts($from, $where, $having);
1487 }
1488
1489 return array($select, $from, $where, $having);
1490 }
1491
1492 /**
1493 * Get where values from the parameters.
1494 *
1495 * @param string $name
1496 * @param mixed $grouping
1497 *
1498 * @return mixed
1499 */
1500 public function getWhereValues($name, $grouping) {
1501 $result = NULL;
1502 foreach ($this->_params as $values) {
1503 if ($values[0] == $name && $values[3] == $grouping) {
1504 return $values;
1505 }
1506 }
1507
1508 return $result;
1509 }
1510
1511 /**
1512 * Fix date values.
1513 *
1514 * @param bool $relative
1515 * @param string $from
1516 * @param string $to
1517 */
1518 public static function fixDateValues($relative, &$from, &$to) {
1519 if ($relative) {
1520 list($from, $to) = CRM_Utils_Date::getFromTo($relative, $from, $to);
1521 }
1522 }
1523
1524 /**
1525 * Convert values from form-appropriate to query-object appropriate.
1526 *
1527 * The query object is increasingly supporting the sql-filter syntax which is the most flexible syntax.
1528 * So, ideally we would convert all fields to look like
1529 * array(
1530 * 0 => $fieldName
1531 * // Set the operator for legacy reasons, but it is ignored
1532 * 1 => '='
1533 * // array in sql filter syntax
1534 * 2 => array('BETWEEN' => array(1,60),
1535 * 3 => null
1536 * 4 => null
1537 * );
1538 *
1539 * There are some examples of the syntax in
1540 * https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples/Relationship
1541 *
1542 * More notes at CRM_Core_DAO::createSQLFilter
1543 *
1544 * and a list of supported operators in CRM_Core_DAO
1545 *
1546 * @param array $formValues
1547 * @param int $wildcard
1548 * @param bool $useEquals
1549 *
1550 * @param string $apiEntity
1551 *
1552 * @param array $entityReferenceFields
1553 * Field names of any entity reference fields (which will need reformatting to IN syntax).
1554 *
1555 * @return array
1556 */
1557 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL,
1558 $entityReferenceFields = array()) {
1559 $params = array();
1560 if (empty($formValues)) {
1561 return $params;
1562 }
1563
1564 self::filterCountryFromValuesIfStateExists($formValues);
1565
1566 // Handle relative dates first
1567 foreach (array_keys($formValues) as $id) {
1568 if (preg_match('/_date_relative$/', $id) ||
1569 $id == 'event_relative' ||
1570 $id == 'case_from_relative' ||
1571 $id == 'case_to_relative' ||
1572 $id == 'participant_relative'
1573 ) {
1574 if ($id == 'event_relative') {
1575 $fromRange = 'event_start_date_low';
1576 $toRange = 'event_end_date_high';
1577 }
1578 elseif ($id == 'participant_relative') {
1579 $fromRange = 'participant_register_date_low';
1580 $toRange = 'participant_register_date_high';
1581 }
1582 elseif ($id == 'case_from_relative') {
1583 $fromRange = 'case_from_start_date_low';
1584 $toRange = 'case_from_start_date_high';
1585 }
1586 elseif ($id == 'case_to_relative') {
1587 $fromRange = 'case_to_end_date_low';
1588 $toRange = 'case_to_end_date_high';
1589 }
1590 else {
1591 $dateComponent = explode('_date_relative', $id);
1592 $fromRange = "{$dateComponent[0]}_date_low";
1593 $toRange = "{$dateComponent[0]}_date_high";
1594 }
1595
1596 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1597 CRM_Contact_BAO_Query::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1598 }
1599 }
1600 }
1601
1602 foreach ($formValues as $id => $values) {
1603 if (self::isAlreadyProcessedForQueryFormat($values)) {
1604 $params[] = $values;
1605 continue;
1606 }
1607
1608 self::legacyConvertFormValues($id, $values);
1609
1610 // The form uses 1 field to represent two db fields
1611 if ($id == 'contact_type' && $values && (!is_array($values) || !array_intersect(array_keys($values), CRM_Core_DAO::acceptedSQLOperators()))) {
1612 $contactType = array();
1613 $subType = array();
1614 foreach ((array) $values as $key => $type) {
1615 $types = explode('__', is_numeric($type) ? $key : $type);
1616 $contactType[$types[0]] = $types[0];
1617 // Add sub-type if specified
1618 if (!empty($types[1])) {
1619 $subType[$types[1]] = $types[1];
1620 }
1621 }
1622 $params[] = array('contact_type', 'IN', $contactType, 0, 0);
1623 if ($subType) {
1624 $params[] = array('contact_sub_type', 'IN', $subType, 0, 0);
1625 }
1626 }
1627 elseif ($id == 'privacy') {
1628 if (is_array($formValues['privacy'])) {
1629 $op = !empty($formValues['privacy']['do_not_toggle']) ? '=' : '!=';
1630 foreach ($formValues['privacy'] as $key => $value) {
1631 if ($value) {
1632 $params[] = array($key, $op, $value, 0, 0);
1633 }
1634 }
1635 }
1636 }
1637 elseif ($id == 'email_on_hold') {
1638 if ($formValues['email_on_hold']['on_hold']) {
1639 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1640 }
1641 }
1642 elseif (substr($id, 0, 7) == 'custom_'
1643 && (
1644 substr($id, -9, 9) == '_relative'
1645 || substr($id, -5, 5) == '_from'
1646 || substr($id, -3, 3) == '_to'
1647 )
1648 ) {
1649 self::convertCustomRelativeFields($formValues, $params, $values, $id);
1650 }
1651 elseif (preg_match('/_date_relative$/', $id) ||
1652 $id == 'event_relative' ||
1653 $id == 'case_from_relative' ||
1654 $id == 'case_to_relative' ||
1655 $id == 'participant_relative'
1656 ) {
1657 // Already handled in previous loop
1658 continue;
1659 }
1660 elseif (in_array($id, $entityReferenceFields) && !empty($values) && is_string($values) && (strpos($values, ',') !=
1661 FALSE)) {
1662 $params[] = array($id, 'IN', explode(',', $values), 0, 0);
1663 }
1664 else {
1665 $values = CRM_Contact_BAO_Query::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
1666
1667 if (!$values) {
1668 continue;
1669 }
1670 $params[] = $values;
1671 }
1672 }
1673 return $params;
1674 }
1675
1676 /**
1677 * Function to support legacy format for groups and tags.
1678 *
1679 * @param string $id
1680 * @param array|int $values
1681 *
1682 */
1683 public static function legacyConvertFormValues($id, &$values) {
1684 $legacyElements = array(
1685 'group',
1686 'tag',
1687 'contact_tags',
1688 'contact_type',
1689 'membership_type_id',
1690 'membership_status_id',
1691 );
1692 if (in_array($id, $legacyElements) && is_array($values)) {
1693 // prior to 4.7, formValues for some attributes (e.g. group, tag) are stored in array(id1 => 1, id2 => 1),
1694 // as per the recent Search fixes $values need to be in standard array(id1, id2) format
1695 $values = CRM_Utils_Array::convertCheckboxFormatToArray($values);
1696 }
1697 }
1698
1699 /**
1700 * Fix values from query from/to something no-one cared enough to document.
1701 *
1702 * @param int $id
1703 * @param array $values
1704 * @param int $wildcard
1705 * @param bool $useEquals
1706 *
1707 * @param string $apiEntity
1708 *
1709 * @return array|null
1710 */
1711 public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1712 // skip a few search variables
1713 static $skipWhere = NULL;
1714 static $likeNames = NULL;
1715 $result = NULL;
1716
1717 // Change camelCase EntityName to lowercase with underscores
1718 $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity);
1719
1720 // check if $value is in OK (Operator as Key) format as used by Get API
1721 if (CRM_Utils_System::isNull($values)) {
1722 return $result;
1723 }
1724
1725 if (!$skipWhere) {
1726 $skipWhere = array(
1727 'task',
1728 'radio_ts',
1729 'uf_group_id',
1730 'component_mode',
1731 'qfKey',
1732 'operator',
1733 'display_relationship_type',
1734 );
1735 }
1736
1737 if (in_array($id, $skipWhere) ||
1738 substr($id, 0, 4) == '_qf_' ||
1739 substr($id, 0, 7) == 'hidden_'
1740 ) {
1741 return $result;
1742 }
1743
1744 if ($apiEntity &&
1745 (substr($id, 0, strlen($apiEntity)) != $apiEntity) &&
1746 (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_') &&
1747 (substr($id, 0, 7) != 'custom_')
1748 ) {
1749 $id = $apiEntity . '_' . $id;
1750 }
1751
1752 if (!$likeNames) {
1753 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1754 }
1755
1756 // email comes in via advanced search
1757 // so use wildcard always
1758 if ($id == 'email') {
1759 $wildcard = 1;
1760 }
1761
1762 if (!$useEquals && in_array($id, $likeNames)) {
1763 $result = array($id, 'LIKE', $values, 0, 1);
1764 }
1765 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1766 $result = array($id, 'LIKE', $values, 0, 0);
1767 }
1768 elseif ($id == 'contact_type' ||
1769 (!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO::acceptedSQLOperators(), TRUE))
1770 ) {
1771 $result = array($id, 'IN', $values, 0, $wildcard);
1772 }
1773 else {
1774 $result = array($id, '=', $values, 0, $wildcard);
1775 }
1776
1777 return $result;
1778 }
1779
1780 /**
1781 * Get the where clause for a single field.
1782 *
1783 * @param array $values
1784 * @param string $apiEntity
1785 */
1786 public function whereClauseSingle(&$values, $apiEntity = NULL) {
1787 // do not process custom fields or prefixed contact ids or component params
1788 if (CRM_Core_BAO_CustomField::getKeyID($values[0]) ||
1789 (substr($values[0], 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) ||
1790 (substr($values[0], 0, 13) == 'contribution_') ||
1791 (substr($values[0], 0, 6) == 'event_') ||
1792 (substr($values[0], 0, 12) == 'participant_') ||
1793 (substr($values[0], 0, 7) == 'member_') ||
1794 (substr($values[0], 0, 6) == 'grant_') ||
1795 (substr($values[0], 0, 7) == 'pledge_') ||
1796 (substr($values[0], 0, 5) == 'case_') ||
1797 (substr($values[0], 0, 10) == 'financial_') ||
1798 (substr($values[0], 0, 8) == 'payment_') ||
1799 (substr($values[0], 0, 11) == 'membership_')
1800 ) {
1801 return;
1802 }
1803
1804 // skip for hook injected fields / params
1805 $extFields = CRM_Contact_BAO_Query_Hook::singleton()->getFields();
1806 if (array_key_exists($values[0], $extFields)) {
1807 return;
1808 }
1809
1810 switch ($values[0]) {
1811 case 'deleted_contacts':
1812 $this->deletedContacts($values);
1813 return;
1814
1815 case 'contact_sub_type':
1816 $this->contactSubType($values);
1817 return;
1818
1819 case 'group':
1820 case 'group_type':
1821 $this->group($values);
1822 return;
1823
1824 // case tag comes from find contacts
1825 case 'tag_search':
1826 $this->tagSearch($values);
1827 return;
1828
1829 case 'tag':
1830 case 'contact_tags':
1831 $this->tag($values);
1832 return;
1833
1834 case 'note':
1835 case 'note_body':
1836 case 'note_subject':
1837 $this->notes($values);
1838 return;
1839
1840 case 'uf_user':
1841 $this->ufUser($values);
1842 return;
1843
1844 case 'sort_name':
1845 case 'display_name':
1846 $this->sortName($values);
1847 return;
1848
1849 case 'addressee':
1850 case 'postal_greeting':
1851 case 'email_greeting':
1852 $this->greetings($values);
1853 return;
1854
1855 case 'email':
1856 case 'email_id':
1857 $this->email($values, $apiEntity);
1858 return;
1859
1860 case 'phone_numeric':
1861 $this->phone_numeric($values);
1862 return;
1863
1864 case 'phone_phone_type_id':
1865 case 'phone_location_type_id':
1866 $this->phone_option_group($values);
1867 return;
1868
1869 case 'street_address':
1870 $this->street_address($values);
1871 return;
1872
1873 case 'street_number':
1874 $this->street_number($values);
1875 return;
1876
1877 case 'sortByCharacter':
1878 $this->sortByCharacter($values);
1879 return;
1880
1881 case 'location_type':
1882 $this->locationType($values);
1883 return;
1884
1885 case 'county':
1886 $this->county($values);
1887 return;
1888
1889 case 'state_province':
1890 case 'state_province_id':
1891 case 'state_province_name':
1892 $this->stateProvince($values);
1893 return;
1894
1895 case 'country':
1896 case 'country_id':
1897 $this->country($values, FALSE);
1898 return;
1899
1900 case 'postal_code':
1901 case 'postal_code_low':
1902 case 'postal_code_high':
1903 $this->postalCode($values);
1904 return;
1905
1906 case 'activity_date':
1907 case 'activity_date_low':
1908 case 'activity_date_high':
1909 case 'activity_role':
1910 case 'activity_status_id':
1911 case 'activity_status':
1912 case 'activity_priority':
1913 case 'activity_priority_id':
1914 case 'followup_parent_id':
1915 case 'parent_id':
1916 case 'source_contact_id':
1917 case 'activity_text':
1918 case 'activity_option':
1919 case 'test_activities':
1920 case 'activity_type_id':
1921 case 'activity_type':
1922 case 'activity_survey_id':
1923 case 'activity_tags':
1924 case 'activity_taglist':
1925 case 'activity_test':
1926 case 'activity_campaign_id':
1927 case 'activity_engagement_level':
1928 case 'activity_id':
1929 case 'activity_result':
1930 case 'source_contact':
1931 CRM_Activity_BAO_Query::whereClauseSingle($values, $this);
1932 return;
1933
1934 case 'age_low':
1935 case 'age_high':
1936 case 'birth_date_low':
1937 case 'birth_date_high':
1938 case 'deceased_date_low':
1939 case 'deceased_date_high':
1940 $this->demographics($values);
1941 return;
1942
1943 case 'age_asof_date':
1944 // handled by demographics
1945 return;
1946
1947 case 'log_date_low':
1948 case 'log_date_high':
1949 $this->modifiedDates($values);
1950 return;
1951
1952 case 'changed_by':
1953 $this->changeLog($values);
1954 return;
1955
1956 case 'do_not_phone':
1957 case 'do_not_email':
1958 case 'do_not_mail':
1959 case 'do_not_sms':
1960 case 'do_not_trade':
1961 case 'is_opt_out':
1962 $this->privacy($values);
1963 return;
1964
1965 case 'privacy_options':
1966 $this->privacyOptions($values);
1967 return;
1968
1969 case 'privacy_operator':
1970 case 'privacy_toggle':
1971 // these are handled by privacy options
1972 return;
1973
1974 case 'preferred_communication_method':
1975 $this->preferredCommunication($values);
1976 return;
1977
1978 case 'relation_type_id':
1979 case 'relation_start_date_high':
1980 case 'relation_start_date_low':
1981 case 'relation_end_date_high':
1982 case 'relation_end_date_low':
1983 case 'relation_active_period_date_high':
1984 case 'relation_active_period_date_low':
1985 case 'relation_target_name':
1986 case 'relation_status':
1987 case 'relation_date_low':
1988 case 'relation_date_high':
1989 $this->relationship($values);
1990 $this->_relationshipValuesAdded = TRUE;
1991 return;
1992
1993 case 'task_status_id':
1994 $this->task($values);
1995 return;
1996
1997 case 'task_id':
1998 // since this case is handled with the above
1999 return;
2000
2001 case 'prox_distance':
2002 CRM_Contact_BAO_ProximityQuery::process($this, $values);
2003 return;
2004
2005 case 'prox_street_address':
2006 case 'prox_city':
2007 case 'prox_postal_code':
2008 case 'prox_state_province_id':
2009 case 'prox_country_id':
2010 case 'prox_geo_code_1':
2011 case 'prox_geo_code_2':
2012 // handled by the proximity_distance clause
2013 return;
2014
2015 default:
2016 $this->restWhere($values);
2017 return;
2018 }
2019 }
2020
2021 /**
2022 * Given a list of conditions in params generate the required where clause.
2023 *
2024 * @param string $apiEntity
2025 *
2026 * @return string
2027 */
2028 public function whereClause($apiEntity = NULL) {
2029 $this->_where[0] = array();
2030 $this->_qill[0] = array();
2031
2032 $this->includeContactIds();
2033 if (!empty($this->_params)) {
2034 foreach (array_keys($this->_params) as $id) {
2035 if (empty($this->_params[$id][0])) {
2036 continue;
2037 }
2038 // check for both id and contact_id
2039 if ($this->_params[$id][0] == 'id' || $this->_params[$id][0] == 'contact_id') {
2040 $this->_where[0][] = self::buildClause("contact_a.id", $this->_params[$id][1], $this->_params[$id][2]);
2041 }
2042 else {
2043 $this->whereClauseSingle($this->_params[$id], $apiEntity);
2044 }
2045 }
2046
2047 CRM_Core_Component::alterQuery($this, 'where');
2048
2049 CRM_Contact_BAO_Query_Hook::singleton()->alterSearchQuery($this, 'where');
2050 }
2051
2052 if ($this->_customQuery) {
2053 // Added following if condition to avoid the wrong value display for 'my account' / any UF info.
2054 // Hope it wont affect the other part of civicrm.. if it does please remove it.
2055 if (!empty($this->_customQuery->_where)) {
2056 $this->_where = CRM_Utils_Array::crmArrayMerge($this->_where, $this->_customQuery->_where);
2057 }
2058
2059 $this->_qill = CRM_Utils_Array::crmArrayMerge($this->_qill, $this->_customQuery->_qill);
2060 }
2061
2062 $clauses = array();
2063 $andClauses = array();
2064
2065 $validClauses = 0;
2066 if (!empty($this->_where)) {
2067 foreach ($this->_where as $grouping => $values) {
2068 if ($grouping > 0 && !empty($values)) {
2069 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
2070 $validClauses++;
2071 }
2072 }
2073
2074 if (!empty($this->_where[0])) {
2075 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where[0]) . ' ) ';
2076 }
2077 if (!empty($clauses)) {
2078 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
2079 }
2080
2081 if ($validClauses > 1) {
2082 $this->_useDistinct = TRUE;
2083 }
2084 }
2085
2086 return implode(' AND ', $andClauses);
2087 }
2088
2089 /**
2090 * Generate where clause for any parameters not already handled.
2091 *
2092 * @param array $values
2093 *
2094 * @throws Exception
2095 */
2096 public function restWhere(&$values) {
2097 $name = CRM_Utils_Array::value(0, $values);
2098 $op = CRM_Utils_Array::value(1, $values);
2099 $value = CRM_Utils_Array::value(2, $values);
2100 $grouping = CRM_Utils_Array::value(3, $values);
2101 $wildcard = CRM_Utils_Array::value(4, $values);
2102
2103 if (isset($grouping) && empty($this->_where[$grouping])) {
2104 $this->_where[$grouping] = array();
2105 }
2106
2107 $multipleFields = array('url');
2108
2109 //check if the location type exists for fields
2110 $lType = '';
2111 $locType = explode('-', $name);
2112
2113 if (!in_array($locType[0], $multipleFields)) {
2114 //add phone type if exists
2115 if (isset($locType[2]) && $locType[2]) {
2116 $locType[2] = CRM_Core_DAO::escapeString($locType[2]);
2117 }
2118 }
2119
2120 $field = CRM_Utils_Array::value($name, $this->_fields);
2121
2122 if (!$field) {
2123 $field = CRM_Utils_Array::value($locType[0], $this->_fields);
2124
2125 if (!$field) {
2126 return;
2127 }
2128 }
2129
2130 $setTables = TRUE;
2131
2132 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
2133 $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
2134 if (isset($locType[1]) && is_numeric($locType[1])) {
2135 $lType = $locationType[$locType[1]];
2136 }
2137 if ($lType) {
2138 $field['title'] .= " ($lType)";
2139 }
2140
2141 if (substr($name, 0, 14) === 'state_province') {
2142 if (isset($locType[1]) && is_numeric($locType[1])) {
2143 $setTables = FALSE;
2144 $aName = "{$lType}-address";
2145 $where = "`$aName`.state_province_id";
2146 }
2147 else {
2148 $where = "civicrm_address.state_province_id";
2149 }
2150
2151 $this->_where[$grouping][] = self::buildClause($where, $op, $value);
2152 $this->_tables[$aName] = $this->_whereTables[$aName] = 1;
2153 list($qillop, $qillVal) = self::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
2154 $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
2155 }
2156 elseif (!empty($field['pseudoconstant'])) {
2157 $this->optionValueQuery(
2158 $name, $op, $value, $grouping,
2159 'CRM_Contact_DAO_Contact',
2160 $field,
2161 $field['title'],
2162 'String',
2163 TRUE
2164 );
2165 if ($name == 'gender_id') {
2166 self::$_openedPanes[ts('Demographics')] = TRUE;
2167 }
2168 }
2169 elseif (substr($name, 0, 7) === 'country' || substr($name, 0, 6) === 'county') {
2170 $name = (substr($name, 0, 7) === 'country') ? "country_id" : "county_id";
2171 if (isset($locType[1]) && is_numeric($locType[1])) {
2172 $setTables = FALSE;
2173 $aName = "{$lType}-address";
2174 $where = "`$aName`.$name";
2175 }
2176 else {
2177 $where = "civicrm_address.$name";
2178 }
2179
2180 $this->_where[$grouping][] = self::buildClause($where, $op, $value, 'Positive');
2181 $this->_tables[$aName] = $this->_whereTables[$aName] = 1;
2182
2183 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $name, $value, $op);
2184 $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
2185 }
2186 elseif ($name === 'world_region') {
2187 $this->optionValueQuery(
2188 $name, $op, $value, $grouping,
2189 NULL,
2190 $field,
2191 ts('World Region'),
2192 'Positive',
2193 TRUE
2194 );
2195 }
2196 elseif ($name === 'is_deceased') {
2197 $this->setQillAndWhere($name, $op, $value, $grouping, $field);
2198 self::$_openedPanes[ts('Demographics')] = TRUE;
2199 }
2200 elseif ($name === 'created_date' || $name === 'modified_date' || $name === 'deceased_date' || $name === 'birth_date') {
2201 $appendDateTime = TRUE;
2202 if ($name === 'deceased_date' || $name === 'birth_date') {
2203 $appendDateTime = FALSE;
2204 self::$_openedPanes[ts('Demographics')] = TRUE;
2205 }
2206 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2207 }
2208 elseif ($name === 'contact_id') {
2209 if (is_int($value)) {
2210 $this->_where[$grouping][] = self::buildClause($field['where'], $op, $value);
2211 $this->_qill[$grouping][] = "$field[title] $op $value";
2212 }
2213 }
2214 elseif ($name === 'name') {
2215 $value = $strtolower(CRM_Core_DAO::escapeString($value));
2216 if ($wildcard) {
2217 $op = 'LIKE';
2218 $value = self::getWildCardedValue($wildcard, $op, $value);
2219 }
2220 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
2221 $wc = self::caseImportant($op) ? "LOWER({$field['where']})" : "{$field['where']}";
2222 $this->_where[$grouping][] = self::buildClause($wc, $op, "'$value'");
2223 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2224 }
2225 elseif ($name === 'current_employer') {
2226 if ($wildcard) {
2227 $op = 'LIKE';
2228 $value = self::getWildCardedValue($wildcard, $op, $value);
2229 }
2230 $ceWhereClause = self::buildClause("contact_a.organization_name", $op,
2231 $value
2232 );
2233 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2234 $this->_where[$grouping][] = $ceWhereClause;
2235 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2236 }
2237 elseif ($name === 'email_greeting') {
2238 $filterCondition = array('greeting_type' => 'email_greeting');
2239 $this->optionValueQuery(
2240 $name, $op, $value, $grouping,
2241 CRM_Core_PseudoConstant::greeting($filterCondition),
2242 $field,
2243 ts('Email Greeting')
2244 );
2245 }
2246 elseif ($name === 'postal_greeting') {
2247 $filterCondition = array('greeting_type' => 'postal_greeting');
2248 $this->optionValueQuery(
2249 $name, $op, $value, $grouping,
2250 CRM_Core_PseudoConstant::greeting($filterCondition),
2251 $field,
2252 ts('Postal Greeting')
2253 );
2254 }
2255 elseif ($name === 'addressee') {
2256 $filterCondition = array('greeting_type' => 'addressee');
2257 $this->optionValueQuery(
2258 $name, $op, $value, $grouping,
2259 CRM_Core_PseudoConstant::greeting($filterCondition),
2260 $field,
2261 ts('Addressee')
2262 );
2263 }
2264 elseif (substr($name, 0, 4) === 'url-') {
2265 $tName = 'civicrm_website';
2266 $this->_whereTables[$tName] = $this->_tables[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2267 $value = $strtolower(CRM_Core_DAO::escapeString($value));
2268 if ($wildcard) {
2269 $op = 'LIKE';
2270 $value = self::getWildCardedValue($wildcard, $op, $value);
2271 }
2272
2273 $this->_where[$grouping][] = $d = self::buildClause('civicrm_website.url', $op, $value);
2274 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2275 }
2276 elseif ($name === 'contact_is_deleted') {
2277 $this->setQillAndWhere('is_deleted', $op, $value, $grouping, $field);
2278 }
2279 elseif (!empty($field['where'])) {
2280 $type = NULL;
2281 if (!empty($field['type'])) {
2282 $type = CRM_Utils_Type::typeToString($field['type']);
2283 }
2284
2285 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2286
2287 if (isset($locType[1]) &&
2288 is_numeric($locType[1])
2289 ) {
2290 $setTables = FALSE;
2291
2292 //get the location name
2293 list($tName, $fldName) = self::getLocationTableName($field['where'], $locType);
2294 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
2295 $fieldName = "LOWER(`$tName`.$fldName)";
2296
2297 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2298 $this->_tables[$tName] = $this->_whereTables[$tName] = 1;
2299
2300 }
2301 else {
2302 if ($tableName == 'civicrm_contact') {
2303 $fieldName = "contact_a.{$fieldName}";
2304 }
2305 else {
2306 if ($op != 'IN' && !is_numeric($value) && !is_array($value)) {
2307 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
2308 $fieldName = "LOWER({$field['where']})";
2309 }
2310 else {
2311 $fieldName = "{$field['where']}";
2312 }
2313 }
2314 }
2315
2316 list($qillop, $qillVal) = self::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2317 $this->_qill[$grouping][] = ts("%1 %2 %3", array(
2318 1 => $field['title'],
2319 2 => $qillop,
2320 3 => (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) ? $qillVal : "'$qillVal'"));
2321
2322 if (is_array($value)) {
2323 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2324 // for api style operators for functions that hit this point without worrying about regression
2325 // (the previous comments indicated the condition for hitting this point were unknown
2326 // per CRM-14743 we are adding modified_date & created_date operator support
2327 $operations = array_keys($value);
2328 foreach ($operations as $operator) {
2329 if (!in_array($operator, CRM_Core_DAO::acceptedSQLOperators())) {
2330 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2331 //so this condition will satisfy the search for now
2332 if (strpos($op, 'IN') !== FALSE) {
2333 $value = array($op => $value);
2334 }
2335 // we don't know when this might happen
2336 else {
2337 CRM_Core_Error::fatal(ts("%1 is not a valid operator", array(1 => $operator)));
2338 }
2339 }
2340 }
2341 $this->_where[$grouping][] = CRM_Core_DAO::createSQLFilter($fieldName, $value, $type);
2342 }
2343 else {
2344 if (!strpos($op, 'IN')) {
2345 $value = $strtolower($value);
2346 }
2347 if ($wildcard) {
2348 $op = 'LIKE';
2349 $value = self::getWildCardedValue($wildcard, $op, $value);
2350 }
2351
2352 $this->_where[$grouping][] = self::buildClause($fieldName, $op, $value, $type);
2353 }
2354 }
2355
2356 if ($setTables && isset($field['where'])) {
2357 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2358 if (isset($tableName)) {
2359 $this->_tables[$tableName] = 1;
2360 $this->_whereTables[$tableName] = 1;
2361 }
2362 }
2363 }
2364
2365 /**
2366 * @param $where
2367 * @param $locType
2368 *
2369 * @return array
2370 * @throws Exception
2371 */
2372 public static function getLocationTableName(&$where, &$locType) {
2373 if (isset($locType[1]) && is_numeric($locType[1])) {
2374 list($tbName, $fldName) = explode(".", $where);
2375
2376 //get the location name
2377 $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
2378 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2379 if (in_array($locType[0], $specialFields)) {
2380 //hack to fix / special handing for phone_ext
2381 if ($locType[0] == 'phone_ext') {
2382 $locType[0] = 'phone';
2383 }
2384 if (isset($locType[2]) && $locType[2]) {
2385 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2386 }
2387 else {
2388 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2389 }
2390 }
2391 elseif (in_array($locType[0],
2392 array(
2393 'address_name',
2394 'street_address',
2395 'street_name',
2396 'street_number_suffix',
2397 'street_unit',
2398 'supplemental_address_1',
2399 'supplemental_address_2',
2400 'supplemental_address_3',
2401 'city',
2402 'postal_code',
2403 'postal_code_suffix',
2404 'geo_code_1',
2405 'geo_code_2',
2406 'master_id',
2407 )
2408 )) {
2409 //fix for search by profile with address fields.
2410 $tName = "{$locationType[$locType[1]]}-address";
2411 }
2412 elseif (in_array($locType[0],
2413 array(
2414 'on_hold',
2415 'signature_html',
2416 'signature_text',
2417 'is_bulkmail',
2418 )
2419 )) {
2420 $tName = "{$locationType[$locType[1]]}-email";
2421 }
2422 elseif ($locType[0] == 'provider_id') {
2423 $tName = "{$locationType[$locType[1]]}-im";
2424 }
2425 elseif ($locType[0] == 'openid') {
2426 $tName = "{$locationType[$locType[1]]}-openid";
2427 }
2428 else {
2429 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2430 }
2431 $tName = str_replace(' ', '_', $tName);
2432 return array($tName, $fldName);
2433 }
2434 CRM_Core_Error::fatal();
2435 }
2436
2437 /**
2438 * Given a result dao, extract the values and return that array
2439 *
2440 * @param CRM_Core_DAO $dao
2441 *
2442 * @return array
2443 * values for this query
2444 */
2445 public function store($dao) {
2446 $value = array();
2447
2448 foreach ($this->_element as $key => $dontCare) {
2449 if (property_exists($dao, $key)) {
2450 if (strpos($key, '-') !== FALSE) {
2451 $values = explode('-', $key);
2452 $lastElement = array_pop($values);
2453 $current = &$value;
2454 $cnt = count($values);
2455 $count = 1;
2456 foreach ($values as $v) {
2457 if (!array_key_exists($v, $current)) {
2458 $current[$v] = array();
2459 }
2460 //bad hack for im_provider
2461 if ($lastElement == 'provider_id') {
2462 if ($count < $cnt) {
2463 $current = &$current[$v];
2464 }
2465 else {
2466 $lastElement = "{$v}_{$lastElement}";
2467 }
2468 }
2469 else {
2470 $current = &$current[$v];
2471 }
2472 $count++;
2473 }
2474
2475 $current[$lastElement] = $dao->$key;
2476 }
2477 else {
2478 $value[$key] = $dao->$key;
2479 }
2480 }
2481 }
2482 return $value;
2483 }
2484
2485 /**
2486 * Getter for tables array.
2487 *
2488 * @return array
2489 */
2490 public function tables() {
2491 return $this->_tables;
2492 }
2493
2494 /**
2495 * Sometimes used to create the from clause, but, not reliably, set
2496 * this AND set tables.
2497 *
2498 * It's unclear the intent - there is a 'simpleFrom' clause which
2499 * takes whereTables into account & a fromClause which doesn't.
2500 *
2501 * logic may have eroded?
2502 *
2503 * @return array
2504 */
2505 public function whereTables() {
2506 return $this->_whereTables;
2507 }
2508
2509 /**
2510 * Generate the where clause (used in match contacts and permissions)
2511 *
2512 * @param array $params
2513 * @param array $fields
2514 * @param array $tables
2515 * @param $whereTables
2516 * @param bool $strict
2517 *
2518 * @return string
2519 */
2520 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2521 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2522 FALSE, $strict
2523 );
2524
2525 $tables = array_merge($query->tables(), $tables);
2526 $whereTables = array_merge($query->whereTables(), $whereTables);
2527
2528 return $query->_whereClause;
2529 }
2530
2531 /**
2532 * Create the from clause.
2533 *
2534 * @param array $tables
2535 * Tables that need to be included in this from clause. If null,
2536 * return mimimal from clause (i.e. civicrm_contact).
2537 * @param array $inner
2538 * Tables that should be inner-joined.
2539 * @param array $right
2540 * Tables that should be right-joined.
2541 * @param bool $primaryLocation
2542 * Search on primary location. See note below.
2543 * @param int $mode
2544 * Determines search mode based on bitwise MODE_* constants.
2545 * @param string|NULL $apiEntity
2546 * Determines search mode based on entity by string.
2547 *
2548 * The $primaryLocation flag only seems to be used when
2549 * locationType() has been called. This may be a search option
2550 * exposed, or perhaps it's a "search all details" approach which
2551 * predates decoupling of location types and primary fields?
2552 *
2553 * @see https://issues.civicrm.org/jira/browse/CRM-19967
2554 *
2555 * @return string
2556 * the from clause
2557 */
2558 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1, $apiEntity = NULL) {
2559
2560 $from = ' FROM civicrm_contact contact_a';
2561 if (empty($tables)) {
2562 return $from;
2563 }
2564
2565 if (!empty($tables['civicrm_worldregion'])) {
2566 $tables = array_merge(array('civicrm_country' => 1), $tables);
2567 }
2568
2569 if ((!empty($tables['civicrm_state_province']) || !empty($tables['civicrm_country']) ||
2570 CRM_Utils_Array::value('civicrm_county', $tables)
2571 ) && empty($tables['civicrm_address'])
2572 ) {
2573 $tables = array_merge(array('civicrm_address' => 1),
2574 $tables
2575 );
2576 }
2577
2578 // add group_contact and group table is subscription history is present
2579 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2580 $tables = array_merge(array(
2581 'civicrm_group' => 1,
2582 'civicrm_group_contact' => 1,
2583 ),
2584 $tables
2585 );
2586 }
2587
2588 // to handle table dependencies of components
2589 CRM_Core_Component::tableNames($tables);
2590 // to handle table dependencies of hook injected tables
2591 CRM_Contact_BAO_Query_Hook::singleton()->setTableDependency($tables);
2592
2593 //format the table list according to the weight
2594 $info = CRM_Core_TableHierarchy::info();
2595
2596 foreach ($tables as $key => $value) {
2597 $k = 99;
2598 if (strpos($key, '-') !== FALSE) {
2599 $keyArray = explode('-', $key);
2600 $k = CRM_Utils_Array::value('civicrm_' . $keyArray[1], $info, 99);
2601 }
2602 elseif (strpos($key, '_') !== FALSE) {
2603 $keyArray = explode('_', $key);
2604 if (is_numeric(array_pop($keyArray))) {
2605 $k = CRM_Utils_Array::value(implode('_', $keyArray), $info, 99);
2606 }
2607 else {
2608 $k = CRM_Utils_Array::value($key, $info, 99);
2609 }
2610 }
2611 else {
2612 $k = CRM_Utils_Array::value($key, $info, 99);
2613 }
2614 $tempTable[$k . ".$key"] = $key;
2615 }
2616 ksort($tempTable);
2617 $newTables = array();
2618 foreach ($tempTable as $key) {
2619 $newTables[$key] = $tables[$key];
2620 }
2621
2622 $tables = $newTables;
2623
2624 foreach ($tables as $name => $value) {
2625 if (!$value) {
2626 continue;
2627 }
2628
2629 if (!empty($inner[$name])) {
2630 $side = 'INNER';
2631 }
2632 elseif (!empty($right[$name])) {
2633 $side = 'RIGHT';
2634 }
2635 else {
2636 $side = 'LEFT';
2637 }
2638
2639 if ($value != 1) {
2640 // if there is already a join statement in value, use value itself
2641 if (strpos($value, 'JOIN')) {
2642 $from .= " $value ";
2643 }
2644 else {
2645 $from .= " $side JOIN $name ON ( $value ) ";
2646 }
2647 continue;
2648 }
2649
2650 $limitToPrimaryClause = $primaryLocation ? "AND {$name}.is_primary = 1" : '';
2651
2652 switch ($name) {
2653 case 'civicrm_address':
2654 //CRM-14263 further handling of address joins further down...
2655 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id {$limitToPrimaryClause} )";
2656 continue;
2657
2658 case 'civicrm_phone':
2659 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id {$limitToPrimaryClause}) ";
2660 continue;
2661
2662 case 'civicrm_email':
2663 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id {$limitToPrimaryClause})";
2664 continue;
2665
2666 case 'civicrm_im':
2667 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id {$limitToPrimaryClause}) ";
2668 continue;
2669
2670 case 'im_provider':
2671 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2672 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2673 $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)";
2674 continue;
2675
2676 case 'civicrm_openid':
2677 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id {$limitToPrimaryClause} )";
2678 continue;
2679
2680 case 'civicrm_worldregion':
2681 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2682 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2683 continue;
2684
2685 case 'civicrm_location_type':
2686 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2687 continue;
2688
2689 case 'civicrm_group':
2690 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2691 continue;
2692
2693 case 'civicrm_group_contact':
2694 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2695 continue;
2696
2697 case 'civicrm_group_contact_cache':
2698 $from .= " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
2699 continue;
2700
2701 case 'civicrm_activity':
2702 case 'civicrm_activity_tag':
2703 case 'activity_type':
2704 case 'activity_status':
2705 case 'parent_id':
2706 case 'civicrm_activity_contact':
2707 case 'source_contact':
2708 case 'activity_priority':
2709 $from .= CRM_Activity_BAO_Query::from($name, $mode, $side);
2710 continue;
2711
2712 case 'civicrm_entity_tag':
2713 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2714 civicrm_entity_tag.entity_id = contact_a.id ) ";
2715 continue;
2716
2717 case 'civicrm_note':
2718 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2719 contact_a.id = civicrm_note.entity_id ) ";
2720 continue;
2721
2722 case 'civicrm_subscription_history':
2723 $from .= " $side JOIN civicrm_subscription_history
2724 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2725 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2726 continue;
2727
2728 case 'civicrm_relationship':
2729 if (self::$_relType == 'reciprocal') {
2730 if (self::$_relationshipTempTable) {
2731 // we have a temptable to join on
2732 $tbl = self::$_relationshipTempTable;
2733 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2734 }
2735 else {
2736 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2737 $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)";
2738 }
2739 }
2740 elseif (self::$_relType == 'b') {
2741 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2742 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2743 }
2744 else {
2745 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2746 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2747 }
2748 continue;
2749
2750 case 'civicrm_log':
2751 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2752 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2753 continue;
2754
2755 case 'civicrm_tag':
2756 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2757 continue;
2758
2759 case 'civicrm_grant':
2760 $from .= CRM_Grant_BAO_Query::from($name, $mode, $side);
2761 continue;
2762
2763 case 'civicrm_campaign':
2764 //Move to default case if not in either mode.
2765 if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
2766 $from .= CRM_Contribute_BAO_Query::from($name, $mode, $side);
2767 continue;
2768 }
2769 elseif ($mode & CRM_Contact_BAO_Query::MODE_MAILING) {
2770 $from .= CRM_Mailing_BAO_Query::from($name, $mode, $side);
2771 continue;
2772 }
2773 elseif ($mode & CRM_Contact_BAO_Query::MODE_CAMPAIGN) {
2774 $from .= CRM_Campaign_BAO_Query::from($name, $mode, $side);
2775 continue;
2776 }
2777
2778 case 'civicrm_website':
2779 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2780 continue;
2781
2782 default:
2783 $locationTypeName = '';
2784 if (strpos($name, '-address') != 0) {
2785 $locationTypeName = 'address';
2786 }
2787 elseif (strpos($name, '-phone') != 0) {
2788 $locationTypeName = 'phone';
2789 }
2790 elseif (strpos($name, '-email') != 0) {
2791 $locationTypeName = 'email';
2792 }
2793 elseif (strpos($name, '-im') != 0) {
2794 $locationTypeName = 'im';
2795 }
2796 elseif (strpos($name, '-openid') != 0) {
2797 $locationTypeName = 'openid';
2798 }
2799
2800 if ($locationTypeName) {
2801 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2802 $parts = explode('-', $name);
2803 $locationTypes = CRM_Core_BAO_Address::buildOptions('location_type_id', 'get');
2804 foreach ($locationTypes as $locationTypeID => $locationType) {
2805 if ($parts[0] == str_replace(' ', '_', $locationType)) {
2806 $locationID = $locationTypeID;
2807 }
2808 }
2809 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2810 }
2811 else {
2812 $from .= CRM_Core_Component::from($name, $mode, $side);
2813 }
2814 $from .= CRM_Contact_BAO_Query_Hook::singleton()->buildSearchfrom($name, $mode, $side);
2815
2816 continue;
2817 }
2818 }
2819 return $from;
2820 }
2821
2822 /**
2823 * WHERE / QILL clause for deleted_contacts
2824 *
2825 * @param array $values
2826 */
2827 public function deletedContacts($values) {
2828 list($_, $_, $value, $grouping, $_) = $values;
2829 if ($value) {
2830 // *prepend* to the relevant grouping as this is quite an important factor
2831 array_unshift($this->_qill[$grouping], ts('Search in Trash'));
2832 }
2833 }
2834
2835 /**
2836 * Where / qill clause for contact_type
2837 *
2838 * @param $values
2839 */
2840 public function contactType(&$values) {
2841 list($name, $op, $value, $grouping, $wildcard) = $values;
2842
2843 $subTypes = array();
2844 $clause = array();
2845
2846 // account for search builder mapping multiple values
2847 if (!is_array($value)) {
2848 $values = self::parseSearchBuilderString($value, 'String');
2849 if (is_array($values)) {
2850 $value = array_flip($values);
2851 }
2852 }
2853
2854 if (is_array($value)) {
2855 foreach ($value as $k => $v) {
2856 // fix for CRM-771
2857 if ($k) {
2858 $subType = NULL;
2859 $contactType = $k;
2860 if (strpos($k, CRM_Core_DAO::VALUE_SEPARATOR)) {
2861 list($contactType, $subType) = explode(CRM_Core_DAO::VALUE_SEPARATOR, $k, 2);
2862 }
2863
2864 if (!empty($subType)) {
2865 $subTypes[$subType] = 1;
2866 }
2867 $clause[$contactType] = "'" . CRM_Utils_Type::escape($contactType, 'String') . "'";
2868 }
2869 }
2870 }
2871 else {
2872 $contactTypeANDSubType = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value, 2);
2873 $contactType = $contactTypeANDSubType[0];
2874 $subType = CRM_Utils_Array::value(1, $contactTypeANDSubType);
2875 if (!empty($subType)) {
2876 $subTypes[$subType] = 1;
2877 }
2878 $clause[$contactType] = "'" . CRM_Utils_Type::escape($contactType, 'String') . "'";
2879 }
2880
2881 // fix for CRM-771
2882 if (!empty($clause)) {
2883 $quill = $clause;
2884 if ($op == 'IN' || $op == 'NOT IN') {
2885 $this->_where[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2886 }
2887 else {
2888 $type = array_pop($clause);
2889 $this->_where[$grouping][] = self::buildClause("contact_a.contact_type", $op, $contactType);
2890 }
2891
2892 $this->_qill[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2893
2894 if (!empty($subTypes)) {
2895 $this->includeContactSubTypes($subTypes, $grouping);
2896 }
2897 }
2898 }
2899
2900 /**
2901 * Where / qill clause for contact_sub_type.
2902 *
2903 * @param array $values
2904 */
2905 public function contactSubType(&$values) {
2906 list($name, $op, $value, $grouping, $wildcard) = $values;
2907 $this->includeContactSubTypes($value, $grouping, $op);
2908 }
2909
2910 /**
2911 * @param $value
2912 * @param $grouping
2913 * @param string $op
2914 */
2915 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2916
2917 if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
2918 $op = key($value);
2919 $value = $value[$op];
2920 }
2921
2922 $clause = array();
2923 $alias = "contact_a.contact_sub_type";
2924 $qillOperators = CRM_Core_SelectValues::getSearchBuilderOperators();
2925
2926 $op = str_replace('IN', 'LIKE', $op);
2927 $op = str_replace('=', 'LIKE', $op);
2928 $op = str_replace('!', 'NOT ', $op);
2929
2930 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
2931 $this->_where[$grouping][] = self::buildClause($alias, $op, $value, 'String');
2932 }
2933 elseif (is_array($value)) {
2934 foreach ($value as $k => $v) {
2935 $clause[$k] = "($alias $op '%" . CRM_Core_DAO::VALUE_SEPARATOR . CRM_Utils_Type::escape($v, 'String') . CRM_Core_DAO::VALUE_SEPARATOR . "%')";
2936 }
2937 }
2938 else {
2939 $clause[$value] = "($alias $op '%" . CRM_Core_DAO::VALUE_SEPARATOR . CRM_Utils_Type::escape($value, 'String') . CRM_Core_DAO::VALUE_SEPARATOR . "%')";
2940 }
2941
2942 if (!empty($clause)) {
2943 $this->_where[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2944 }
2945 $this->_qill[$grouping][] = ts('Contact Subtype %1 ', array(1 => $qillOperators[$op])) . implode(' ' . ts('or') . ' ', array_keys($clause));
2946 }
2947
2948 /**
2949 * Where / qill clause for groups.
2950 *
2951 * @param $values
2952 */
2953 public function group($values) {
2954 list($name, $op, $value, $grouping, $wildcard) = $values;
2955
2956 // If the $value is in OK (operator as key) array format we need to extract the key as operator and value first
2957 if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
2958 $op = key($value);
2959 $value = $value[$op];
2960 }
2961
2962 // Replace pseudo operators from search builder
2963 $op = str_replace('EMPTY', 'NULL', $op);
2964
2965 if (strpos($op, 'NULL')) {
2966 $value = NULL;
2967 }
2968
2969 if (is_array($value) && count($value) > 1) {
2970 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
2971 CRM_Core_Error::fatal(ts("%1 is not a valid operator", array(1 => $op)));
2972 }
2973 $this->_useDistinct = TRUE;
2974 }
2975
2976 if (isset($value)) {
2977 $value = CRM_Utils_Array::value($op, $value, $value);
2978 }
2979
2980 if ($name == 'group_type') {
2981 $value = array_keys($this->getGroupsFromTypeCriteria($value));
2982 }
2983
2984 $regularGroupIDs = $smartGroupIDs = array();
2985 foreach ((array) $value as $id) {
2986 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
2987 $smartGroupIDs[] = $id;
2988 }
2989 else {
2990 $regularGroupIDs[] = $id;
2991 }
2992 }
2993
2994 $isNotOp = ($op == 'NOT IN' || $op == '!=');
2995
2996 $statii = array();
2997 $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
2998 if ($gcsValues &&
2999 is_array($gcsValues[2])
3000 ) {
3001 foreach ($gcsValues[2] as $k => $v) {
3002 if ($v) {
3003 $statii[] = "'" . CRM_Utils_Type::escape($k, 'String') . "'";
3004 }
3005 }
3006 }
3007 else {
3008 $statii[] = "'Added'";
3009 }
3010 $groupClause = array();
3011 if (count($regularGroupIDs) || empty($value)) {
3012 // include child groups IDs if any
3013 $childGroupIds = (array) CRM_Contact_BAO_Group::getChildGroupIds($regularGroupIDs);
3014 foreach ($childGroupIds as $key => $id) {
3015 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
3016 $smartGroupIDs[] = $id;
3017 unset($childGroupIds[$key]);
3018 }
3019 }
3020 if (count($childGroupIds)) {
3021 $regularGroupIDs = array_merge($regularGroupIDs, $childGroupIds);
3022 }
3023
3024 // if $regularGroupIDs is populated with regular child group IDs
3025 // then change the mysql operator to desired
3026 if (count($regularGroupIDs) > 1) {
3027 $op = strpos($op, 'IN') ? $op : ($op == '!=') ? 'NOT IN' : 'IN';
3028 }
3029 $groupIds = implode(',', (array) $regularGroupIDs);
3030 $gcTable = "`civicrm_group_contact-{$groupIds}`";
3031 $joinClause = array("contact_a.id = {$gcTable}.contact_id");
3032
3033 if (strpos($op, 'IN') !== FALSE) {
3034 $clause = "{$gcTable}.group_id $op ( $groupIds ) ";
3035 }
3036 elseif ($op == '!=') {
3037 $clause = "{$gcTable}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact cgc WHERE cgc.group_id = $groupIds )";
3038 }
3039 else {
3040 $clause = "{$gcTable}.group_id $op $groupIds ";
3041 }
3042 $groupClause[] = "( {$clause} )";
3043
3044 if ($statii) {
3045 $joinClause[] = "{$gcTable}.status IN (" . implode(', ', $statii) . ")";
3046 }
3047 $this->_tables[$gcTable] = $this->_whereTables[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3048 }
3049
3050 //CRM-19589: contact(s) removed from a Smart Group, resides in civicrm_group_contact table
3051 if (count($smartGroupIDs)) {
3052 $groupClause[] = " ( " . $this->addGroupContactCache($smartGroupIDs, NULL, "contact_a", $op) . " ) ";
3053 }
3054
3055 $and = ($op == 'IS NULL') ? ' AND ' : ' OR ';
3056 $this->_where[$grouping][] = ' ( ' . implode($and, $groupClause) . ' ) ';
3057
3058 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
3059 $this->_qill[$grouping][] = ts("Group(s) %1 %2", array(1 => $qillop, 2 => $qillVal));
3060 if (strpos($op, 'NULL') === FALSE) {
3061 $this->_qill[$grouping][] = ts("Group Status %1", array(1 => implode(' ' . ts('or') . ' ', $statii)));
3062 }
3063 }
3064
3065 /**
3066 * Function translates selection of group type into a list of groups.
3067 * @param $value
3068 *
3069 * @return array
3070 */
3071 public function getGroupsFromTypeCriteria($value) {
3072 $groupIds = array();
3073 foreach ((array) $value as $groupTypeValue) {
3074 $groupList = CRM_Core_PseudoConstant::group($groupTypeValue);
3075 $groupIds = ($groupIds + $groupList);
3076 }
3077 return $groupIds;
3078 }
3079
3080 /**
3081 * @param array $groups
3082 * @param string $tableAlias
3083 * @param string $joinTable
3084 * @param string $op
3085 *
3086 * @return null|string
3087 */
3088 public function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a", $op) {
3089 $isNullOp = (strpos($op, 'NULL') !== FALSE);
3090 $groupsIds = $groups;
3091 if (!$isNullOp && !$groups) {
3092 return NULL;
3093 }
3094 elseif (strpos($op, 'IN') !== FALSE) {
3095 $groups = array($op => $groups);
3096 }
3097 elseif (is_array($groups) && count($groups)) {
3098 $groups = array('IN' => $groups);
3099 }
3100
3101 // Find all the groups that are part of a saved search.
3102 $smartGroupClause = self::buildClause("id", $op, $groups, 'Int');
3103 $sql = "
3104 SELECT id, cache_date, saved_search_id, children
3105 FROM civicrm_group
3106 WHERE $smartGroupClause
3107 AND ( saved_search_id != 0
3108 OR saved_search_id IS NOT NULL
3109 OR children IS NOT NULL )
3110 ";
3111
3112 $group = CRM_Core_DAO::executeQuery($sql);
3113
3114 while ($group->fetch()) {
3115 $this->_useDistinct = TRUE;
3116 if (!$this->_smartGroupCache || $group->cache_date == NULL) {
3117 CRM_Contact_BAO_GroupContactCache::load($group);
3118 }
3119 }
3120 if ($group->N == 0) {
3121 return NULL;
3122 }
3123
3124 if (!$tableAlias) {
3125 $tableAlias = "`civicrm_group_contact_cache_";
3126 $tableAlias .= ($isNullOp) ? "a`" : implode(',', (array) $groupsIds) . "`";
3127 }
3128
3129 $this->_tables[$tableAlias] = $this->_whereTables[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.id = {$tableAlias}.contact_id ";
3130 return self::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
3131 }
3132
3133 /**
3134 * Where / qill clause for cms users
3135 *
3136 * @param $values
3137 */
3138 public function ufUser(&$values) {
3139 list($name, $op, $value, $grouping, $wildcard) = $values;
3140
3141 if ($value == 1) {
3142 $this->_tables['civicrm_uf_match'] = $this->_whereTables['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3143
3144 $this->_qill[$grouping][] = ts('CMS User');
3145 }
3146 elseif ($value == 0) {
3147 $this->_tables['civicrm_uf_match'] = $this->_whereTables['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3148
3149 $this->_where[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3150 $this->_qill[$grouping][] = ts('Not a CMS User');
3151 }
3152 }
3153
3154 /**
3155 * All tag search specific.
3156 *
3157 * @param array $values
3158 */
3159 public function tagSearch(&$values) {
3160 list($name, $op, $value, $grouping, $wildcard) = $values;
3161
3162 $op = "LIKE";
3163 $value = "%{$value}%";
3164
3165 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3166 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3167
3168 $etTable = "`civicrm_entity_tag-" . $value . "`";
3169 $tTable = "`civicrm_tag-" . $value . "`";
3170
3171 if ($useAllTagTypes[2]) {
3172 $this->_tables[$etTable] = $this->_whereTables[$etTable]
3173 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3174 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3175
3176 // search tag in cases
3177 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3178 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
3179 $this->_tables[$etCaseTable] = $this->_whereTables[$etCaseTable]
3180 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3181 LEFT JOIN civicrm_case
3182 ON (civicrm_case_contact.case_id = civicrm_case.id
3183 AND civicrm_case.is_deleted = 0 )
3184 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3185 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3186 // search tag in activities
3187 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3188 $tActTable = "`civicrm_act_tag-" . $value . "`";
3189 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
3190 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
3191
3192 $this->_tables[$etActTable] = $this->_whereTables[$etActTable]
3193 = " LEFT JOIN civicrm_activity_contact
3194 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3195 LEFT JOIN civicrm_activity
3196 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3197 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3198 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3199 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3200
3201 $this->_where[$grouping][] = "({$tTable}.name $op '" . $value . "' OR {$tCaseTable}.name $op '" . $value . "' OR {$tActTable}.name $op '" . $value . "')";
3202 $this->_qill[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
3203 }
3204 else {
3205 $etTable = "`civicrm_entity_tag-" . $value . "`";
3206 $tTable = "`civicrm_tag-" . $value . "`";
3207 $this->_tables[$etTable] = $this->_whereTables[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3208 {$etTable}.entity_table = 'civicrm_contact' )
3209 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3210
3211 $this->_where[$grouping][] = self::buildClause("{$tTable}.name", $op, $value, 'String');
3212 $this->_qill[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
3213 }
3214 }
3215
3216 /**
3217 * Where / qill clause for tag.
3218 *
3219 * @param array $values
3220 */
3221 public function tag(&$values) {
3222 list($name, $op, $value, $grouping, $wildcard) = $values;
3223
3224 list($qillop, $qillVal) = self::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, array('onlyActive' => FALSE));
3225 // API/Search Builder format array(operator => array(values))
3226 if (is_array($value)) {
3227 if (in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
3228 $op = key($value);
3229 $value = $value[$op];
3230 }
3231 if (count($value) > 1) {
3232 $this->_useDistinct = TRUE;
3233 }
3234 $value = implode(',', (array) $value);
3235 }
3236
3237 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3238 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3239
3240 $etTable = "`civicrm_entity_tag-" . $value . "`";
3241
3242 if ($useAllTagTypes[2]) {
3243 $this->_tables[$etTable] = $this->_whereTables[$etTable]
3244 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3245
3246 // search tag in cases
3247 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3248 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
3249 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
3250
3251 $this->_tables[$etCaseTable] = $this->_whereTables[$etCaseTable]
3252 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3253 LEFT JOIN civicrm_case
3254 ON (civicrm_case_contact.case_id = civicrm_case.id
3255 AND civicrm_case.is_deleted = 0 )
3256 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3257 // search tag in activities
3258 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3259 $this->_tables[$etActTable] = $this->_whereTables[$etActTable]
3260 = " LEFT JOIN civicrm_activity_contact
3261 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3262 LEFT JOIN civicrm_activity
3263 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3264 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3265 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3266
3267 // CRM-10338
3268 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3269 $this->_where[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3270 }
3271 else {
3272 $this->_where[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3273 }
3274 }
3275 else {
3276 $this->_tables[$etTable] = $this->_whereTables[$etTable]
3277 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3278
3279 // CRM-10338
3280 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3281 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3282 $op = str_replace('EMPTY', 'NULL', $op);
3283 $this->_where[$grouping][] = "{$etTable}.tag_id $op";
3284 }
3285 // CRM-16941: for tag tried with != operator we don't show contact who don't have given $value AND also in other tag
3286 elseif ($op == '!=') {
3287 $this->_where[$grouping][] = "{$etTable}.entity_id NOT IN (SELECT entity_id FROM civicrm_entity_tag cet WHERE cet.entity_table = 'civicrm_contact' AND " . self::buildClause("cet.tag_id", '=', $value, 'Int') . ")";
3288 }
3289 elseif ($op == '=' || strstr($op, 'IN')) {
3290 $op = ($op == '=') ? 'IN' : $op;
3291 $this->_where[$grouping][] = "{$etTable}.tag_id $op ( $value )";
3292 }
3293 }
3294 $this->_qill[$grouping][] = ts('Tagged %1 %2', array(1 => $qillop, 2 => $qillVal));
3295 }
3296
3297 /**
3298 * Where/qill clause for notes
3299 *
3300 * @param array $values
3301 */
3302 public function notes(&$values) {
3303 list($name, $op, $value, $grouping, $wildcard) = $values;
3304
3305 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3306 $noteOption = CRM_Utils_Array::value('2', $noteOptionValues, '6');
3307 $noteOption = ($name == 'note_body') ? 2 : (($name == 'note_subject') ? 3 : $noteOption);
3308
3309 $this->_useDistinct = TRUE;
3310
3311 $this->_tables['civicrm_note'] = $this->_whereTables['civicrm_note']
3312 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3313
3314 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
3315 $n = trim($value);
3316 $value = $strtolower(CRM_Core_DAO::escapeString($n));
3317 if ($wildcard) {
3318 if (strpos($value, '%') === FALSE) {
3319 $value = "%$value%";
3320 }
3321 $op = 'LIKE';
3322 }
3323 elseif ($op == 'IS NULL' || $op == 'IS NOT NULL') {
3324 $value = NULL;
3325 }
3326
3327 $label = NULL;
3328 $clauses = array();
3329 if ($noteOption % 2 == 0) {
3330 $clauses[] = self::buildClause('civicrm_note.note', $op, $value, 'String');
3331 $label = ts('Note: Body Only');
3332 }
3333 if ($noteOption % 3 == 0) {
3334 $clauses[] = self::buildClause('civicrm_note.subject', $op, $value, 'String');
3335 $label = $label ? ts('Note: Body and Subject') : ts('Note: Subject Only');
3336 }
3337 $this->_where[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3338 list($qillOp, $qillVal) = self::buildQillForFieldValue(NULL, $name, $n, $op);
3339 $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillOp, 3 => $qillVal));
3340 }
3341
3342 /**
3343 * @param string $name
3344 * @param $op
3345 * @param $grouping
3346 *
3347 * @return bool
3348 */
3349 public function nameNullOrEmptyOp($name, $op, $grouping) {
3350 switch ($op) {
3351 case 'IS NULL':
3352 case 'IS NOT NULL':
3353 $this->_where[$grouping][] = "contact_a.$name $op";
3354 $this->_qill[$grouping][] = ts('Name') . ' ' . $op;
3355 return TRUE;
3356
3357 case 'IS EMPTY':
3358 $this->_where[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3359 $this->_qill[$grouping][] = ts('Name') . ' ' . $op;
3360 return TRUE;
3361
3362 case 'IS NOT EMPTY':
3363 $this->_where[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3364 $this->_qill[$grouping][] = ts('Name') . ' ' . $op;
3365 return TRUE;
3366
3367 default:
3368 return FALSE;
3369 }
3370 }
3371
3372 /**
3373 * Where / qill clause for sort_name
3374 *
3375 * @param array $values
3376 */
3377 public function sortName(&$values) {
3378 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3379
3380 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3381 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3382 return;
3383 }
3384
3385 $input = $value = trim($value);
3386
3387 if (!strlen($value)) {
3388 return;
3389 }
3390
3391 $config = CRM_Core_Config::singleton();
3392
3393 $sub = array();
3394
3395 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3396 $subGlue = ' OR ';
3397
3398 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
3399
3400 $firstChar = substr($value, 0, 1);
3401 $lastChar = substr($value, -1, 1);
3402 $quotes = array("'", '"');
3403 // If string is quoted, strip quotes and otherwise don't alter it
3404 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3405 $value = trim($value, implode('', $quotes));
3406 }
3407 // Replace spaces with wildcards for a LIKE operation
3408 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3409 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3410 $value = str_replace(' ', '%', $value);
3411 }
3412 $value = $strtolower(CRM_Core_DAO::escapeString(trim($value)));
3413 if (strlen($value)) {
3414 $fieldsub = array();
3415 $value = "'" . self::getWildCardedValue($wildcard, $op, $value) . "'";
3416 if ($fieldName == 'sort_name') {
3417 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3418 $wc = self::caseImportant($op) ? "LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3419 }
3420 else {
3421 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3422 $wc = self::caseImportant($op) ? "LOWER(contact_a.display_name)" : "contact_a.display_name";
3423 }
3424 $fieldsub[] = " ( $wc $op $value )";
3425 if ($config->includeNickNameInName) {
3426 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3427 $wc = self::caseImportant($op) ? "LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3428 $fieldsub[] = " ( $wc $op $value )";
3429 }
3430 if ($config->includeEmailInName) {
3431 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3432 }
3433 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3434 }
3435
3436 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3437
3438 $this->_where[$grouping][] = $sub;
3439 if ($config->includeEmailInName) {
3440 $this->_tables['civicrm_email'] = $this->_whereTables['civicrm_email'] = 1;
3441 $this->_qill[$grouping][] = ts('Name or Email') . " $op - '$input'";
3442 }
3443 else {
3444 $this->_qill[$grouping][] = ts('Name') . " $op - '$input'";
3445 }
3446 }
3447
3448 /**
3449 * Where/qill clause for greeting fields.
3450 *
3451 * @param array $values
3452 */
3453 public function greetings(&$values) {
3454 list($name, $op, $value, $grouping, $wildcard) = $values;
3455 $name .= '_display';
3456
3457 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $name, $value, $op);
3458 $this->_qill[$grouping][] = ts('Greeting %1 %2', array(1 => $qillop, 2 => $qillVal));
3459 $this->_where[$grouping][] = self::buildClause("contact_a.{$name}", $op, $value, 'String');
3460 }
3461
3462 /**
3463 * Where / qill clause for email
3464 *
3465 * @param array $values
3466 * @param string $apiEntity
3467 */
3468 protected function email(&$values, $apiEntity) {
3469 list($name, $op, $value, $grouping, $wildcard) = $values;
3470 $this->_tables['civicrm_email'] = $this->_whereTables['civicrm_email'] = 1;
3471
3472 // CRM-18147: for Contact's GET API, email fieldname got appended with its entity as in {$apiEntiy}_{$name}
3473 // so following code is use build whereClause for contact's primart email id
3474 if (!empty($apiEntity)) {
3475 $dataType = 'String';
3476 if ($name == 'email_id') {
3477 $dataType = 'Integer';
3478 $name = 'id';
3479 }
3480
3481 $this->_where[$grouping][] = self::buildClause('civicrm_email.is_primary', '=', 1, 'Integer');
3482 $this->_where[$grouping][] = self::buildClause("civicrm_email.$name", $op, $value, $dataType);
3483 return;
3484 }
3485
3486 $n = strtolower(trim($value));
3487 if ($n) {
3488 if (substr($n, 0, 1) == '"' &&
3489 substr($n, -1, 1) == '"'
3490 ) {
3491 $n = substr($n, 1, -1);
3492 $value = CRM_Core_DAO::escapeString($n);
3493 $op = '=';
3494 }
3495 else {
3496 $value = self::getWildCardedValue($wildcard, $op, $n);
3497 }
3498 $this->_qill[$grouping][] = ts('Email') . " $op '$n'";
3499 $this->_where[$grouping][] = self::buildClause('civicrm_email.email', $op, $value, 'String');
3500 }
3501 else {
3502 $this->_qill[$grouping][] = ts('Email') . " $op ";
3503 $this->_where[$grouping][] = self::buildClause('civicrm_email.email', $op, NULL, 'String');
3504 }
3505 }
3506
3507 /**
3508 * Where / qill clause for phone number
3509 *
3510 * @param array $values
3511 */
3512 public function phone_numeric(&$values) {
3513 list($name, $op, $value, $grouping, $wildcard) = $values;
3514 // Strip non-numeric characters; allow wildcards
3515 $number = preg_replace('/[^\d%]/', '', $value);
3516 if ($number) {
3517 if (strpos($number, '%') === FALSE) {
3518 $number = "%$number%";
3519 }
3520
3521 $this->_qill[$grouping][] = ts('Phone number contains') . " $number";
3522 $this->_where[$grouping][] = self::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3523 $this->_tables['civicrm_phone'] = $this->_whereTables['civicrm_phone'] = 1;
3524 }
3525 }
3526
3527 /**
3528 * Where / qill clause for phone type/location
3529 *
3530 * @param array $values
3531 */
3532 public function phone_option_group($values) {
3533 list($name, $op, $value, $grouping, $wildcard) = $values;
3534 $option = ($name == 'phone_phone_type_id' ? 'phone_type_id' : 'location_type_id');
3535 $options = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', $option);
3536 $optionName = $options[$value];
3537 $this->_qill[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ? ts('type') : ('location')) . " $op $optionName";
3538 $this->_where[$grouping][] = self::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3539 $this->_tables['civicrm_phone'] = $this->_whereTables['civicrm_phone'] = 1;
3540 }
3541
3542 /**
3543 * Where / qill clause for street_address.
3544 *
3545 * @param array $values
3546 */
3547 public function street_address(&$values) {
3548 list($name, $op, $value, $grouping, $wildcard) = $values;
3549
3550 if (!$op) {
3551 $op = 'LIKE';
3552 }
3553
3554 $n = trim($value);
3555
3556 if ($n) {
3557 $value = strtolower($n);
3558 if (strpos($value, '%') === FALSE) {
3559 // only add wild card if not there
3560 $value = "%{$value}%";
3561 }
3562 $op = 'LIKE';
3563 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3564 $this->_where[$grouping][] = self::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3565 $this->_qill[$grouping][] = ts('Street') . " $op '$n'";
3566 }
3567 else {
3568 $this->_where[$grouping][] = self::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3569 $this->_qill[$grouping][] = ts('Street') . " $op ";
3570 }
3571
3572 $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1;
3573 }
3574
3575 /**
3576 * Where / qill clause for street_unit.
3577 *
3578 * @param array $values
3579 */
3580 public function street_number(&$values) {
3581 list($name, $op, $value, $grouping, $wildcard) = $values;
3582
3583 if (!$op) {
3584 $op = '=';
3585 }
3586
3587 $n = trim($value);
3588
3589 if (strtolower($n) == 'odd') {
3590 $this->_where[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3591 $this->_qill[$grouping][] = ts('Street Number is odd');
3592 }
3593 elseif (strtolower($n) == 'even') {
3594 $this->_where[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3595 $this->_qill[$grouping][] = ts('Street Number is even');
3596 }
3597 else {
3598 $value = strtolower($n);
3599
3600 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
3601 $this->_where[$grouping][] = self::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3602 $this->_qill[$grouping][] = ts('Street Number') . " $op '$n'";
3603 }
3604
3605 $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1;
3606 }
3607
3608 /**
3609 * Where / qill clause for sorting by character.
3610 *
3611 * @param array $values
3612 */
3613 public function sortByCharacter(&$values) {
3614 list($name, $op, $value, $grouping, $wildcard) = $values;
3615
3616 $name = trim($value);
3617 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO::escapeWildCardString($name)) . "%'";
3618 $this->_where[$grouping][] = $cond;
3619 $this->_qill[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3620 }
3621
3622 /**
3623 * Where / qill clause for including contact ids.
3624 */
3625 public function includeContactIDs() {
3626 if (!$this->_includeContactIds || empty($this->_params)) {
3627 return;
3628 }
3629
3630 $contactIds = array();
3631 foreach ($this->_params as $id => $values) {
3632 if (substr($values[0], 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
3633 $contactIds[] = substr($values[0], CRM_Core_Form::CB_PREFIX_LEN);
3634 }
3635 }
3636 CRM_Utils_Type::validateAll($contactIds, 'Positive');
3637 if (!empty($contactIds)) {
3638 $this->_where[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3639 }
3640 }
3641
3642 /**
3643 * Where / qill clause for postal code.
3644 *
3645 * @param array $values
3646 */
3647 public function postalCode(&$values) {
3648 // skip if the fields dont have anything to do with postal_code
3649 if (empty($this->_fields['postal_code'])) {
3650 return;
3651 }
3652
3653 list($name, $op, $value, $grouping, $wildcard) = $values;
3654
3655 // Handle numeric postal code range searches properly by casting the column as numeric
3656 if (is_numeric($value)) {
3657 $field = "IF (civicrm_address.postal_code REGEXP '^[0-9]{1,10}$', CAST(civicrm_address.postal_code AS UNSIGNED), 0)";
3658 $val = CRM_Utils_Type::escape($value, 'Integer');
3659 }
3660 else {
3661 $field = 'civicrm_address.postal_code';
3662 // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string.
3663 if (!is_array($value)) {
3664 $val = CRM_Utils_Type::escape($value, 'String');
3665 }
3666 else {
3667 // Do we need to escape values here? I would expect buildClause does.
3668 $val = $value;
3669 }
3670 }
3671
3672 $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1;
3673
3674 if ($name == 'postal_code') {
3675 $this->_where[$grouping][] = self::buildClause($field, $op, $val, 'String');
3676 $this->_qill[$grouping][] = ts('Postal code') . " {$op} {$value}";
3677 }
3678 elseif ($name == 'postal_code_low') {
3679 $this->_where[$grouping][] = " ( $field >= '$val' ) ";
3680 $this->_qill[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3681 }
3682 elseif ($name == 'postal_code_high') {
3683 $this->_where[$grouping][] = " ( $field <= '$val' ) ";
3684 $this->_qill[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3685 }
3686 }
3687
3688 /**
3689 * Where / qill clause for location type.
3690 *
3691 * @param array $values
3692 * @param null $status
3693 *
3694 * @return string
3695 */
3696 public function locationType(&$values, $status = NULL) {
3697 list($name, $op, $value, $grouping, $wildcard) = $values;
3698
3699 if (is_array($value)) {
3700 $this->_where[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3701 $this->_tables['civicrm_address'] = 1;
3702 $this->_whereTables['civicrm_address'] = 1;
3703
3704 $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
3705 $names = array();
3706 foreach ($value as $id) {
3707 $names[] = $locationType[$id];
3708 }
3709
3710 $this->_primaryLocation = FALSE;
3711
3712 if (!$status) {
3713 $this->_qill[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3714 }
3715 else {
3716 return implode(' ' . ts('or') . ' ', $names);
3717 }
3718 }
3719 }
3720
3721 /**
3722 * @param $values
3723 * @param bool $fromStateProvince
3724 *
3725 * @return array|NULL
3726 */
3727 public function country(&$values, $fromStateProvince = TRUE) {
3728 list($name, $op, $value, $grouping, $wildcard) = $values;
3729
3730 if (!$fromStateProvince) {
3731 $stateValues = $this->getWhereValues('state_province', $grouping);
3732 if (!empty($stateValues)) {
3733 // return back to caller if there are state province values
3734 // since that handles this case
3735 return NULL;
3736 }
3737 }
3738
3739 $countryClause = $countryQill = NULL;
3740 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) || ($values && !empty($value))) {
3741 $this->_tables['civicrm_address'] = 1;
3742 $this->_whereTables['civicrm_address'] = 1;
3743
3744 $countryClause = self::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
3745 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, 'country_id', $value, $op);
3746 $countryQill = ts("%1 %2 %3", array(1 => 'Country', 2 => $qillop, 3 => $qillVal));
3747
3748 if (!$fromStateProvince) {
3749 $this->_where[$grouping][] = $countryClause;
3750 $this->_qill[$grouping][] = $countryQill;
3751 }
3752 }
3753
3754 if ($fromStateProvince) {
3755 if (!empty($countryClause)) {
3756 return array(
3757 $countryClause,
3758 " ...AND... " . $countryQill,
3759 );
3760 }
3761 else {
3762 return array(NULL, NULL);
3763 }
3764 }
3765 }
3766
3767 /**
3768 * Where / qill clause for county (if present).
3769 *
3770 * @param array $values
3771 * @param null $status
3772 *
3773 * @return string
3774 */
3775 public function county(&$values, $status = NULL) {
3776 list($name, $op, $value, $grouping, $wildcard) = $values;
3777
3778 if (!is_array($value)) {
3779 // force the county to be an array
3780 $value = array($value);
3781 }
3782
3783 // check if the values are ids OR names of the counties
3784 $inputFormat = 'id';
3785 foreach ($value as $v) {
3786 if (!is_numeric($v)) {
3787 $inputFormat = 'name';
3788 break;
3789 }
3790 }
3791 $names = array();
3792 if ($op == '=') {
3793 $op = 'IN';
3794 }
3795 elseif ($op == '!=') {
3796 $op = 'NOT IN';
3797 }
3798 else {
3799 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3800 $op = str_replace('EMPTY', 'NULL', $op);
3801 }
3802
3803 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3804 $clause = "civicrm_address.county_id $op";
3805 }
3806 elseif ($inputFormat == 'id') {
3807 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3808
3809 $county = CRM_Core_PseudoConstant::county();
3810 foreach ($value as $id) {
3811 $names[] = CRM_Utils_Array::value($id, $county);
3812 }
3813 }
3814 else {
3815 $inputClause = array();
3816 $county = CRM_Core_PseudoConstant::county();
3817 foreach ($value as $name) {
3818 $name = trim($name);
3819 $inputClause[] = CRM_Utils_Array::key($name, $county);
3820 }
3821 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3822 $names = $value;
3823 }
3824 $this->_tables['civicrm_address'] = 1;
3825 $this->_whereTables['civicrm_address'] = 1;
3826
3827 $this->_where[$grouping][] = $clause;
3828 if (!$status) {
3829 $this->_qill[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3830 }
3831 else {
3832 return implode(' ' . ts('or') . ' ', $names);
3833 }
3834 }
3835
3836 /**
3837 * Where / qill clause for state/province AND country (if present).
3838 *
3839 * @param array $values
3840 * @param null $status
3841 *
3842 * @return string
3843 */
3844 public function stateProvince(&$values, $status = NULL) {
3845 list($name, $op, $value, $grouping, $wildcard) = $values;
3846
3847 $stateClause = self::buildClause('civicrm_address.state_province_id', $op, $value, 'Positive');
3848 $this->_tables['civicrm_address'] = 1;
3849 $this->_whereTables['civicrm_address'] = 1;
3850
3851 $countryValues = $this->getWhereValues('country', $grouping);
3852 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3853 if ($countryClause) {
3854 $clause = "( $stateClause AND $countryClause )";
3855 }
3856 else {
3857 $clause = $stateClause;
3858 }
3859
3860 $this->_where[$grouping][] = $clause;
3861 list($qillop, $qillVal) = self::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
3862 if (!$status) {
3863 $this->_qill[$grouping][] = ts("State/Province %1 %2 %3", array(1 => $qillop, 2 => $qillVal, 3 => $countryQill));
3864 }
3865 else {
3866 return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill;
3867 }
3868 }
3869
3870 /**
3871 * Where / qill clause for change log.
3872 *
3873 * @param array $values
3874 */
3875 public function changeLog(&$values) {
3876 list($name, $op, $value, $grouping, $wildcard) = $values;
3877
3878 $targetName = $this->getWhereValues('changed_by', $grouping);
3879 if (!$targetName) {
3880 return;
3881 }
3882
3883 $name = trim($targetName[2]);
3884 $name = strtolower(CRM_Core_DAO::escapeString($name));
3885 $name = $targetName[4] ? "%$name%" : $name;
3886 $this->_where[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3887 $this->_tables['civicrm_log'] = $this->_whereTables['civicrm_log'] = 1;
3888 $this->_qill[$grouping][] = ts('Modified By') . " $name";
3889 }
3890
3891 /**
3892 * @param $values
3893 */
3894 public function modifiedDates($values) {
3895 $this->_useDistinct = TRUE;
3896
3897 // CRM-11281, default to added date if not set
3898 $fieldTitle = ts('Added Date');
3899 $fieldName = 'created_date';
3900 foreach (array_keys($this->_params) as $id) {
3901 if ($this->_params[$id][0] == 'log_date') {
3902 if ($this->_params[$id][2] == 2) {
3903 $fieldTitle = ts('Modified Date');
3904 $fieldName = 'modified_date';
3905 }
3906 }
3907 }
3908
3909 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3910
3911 self::$_openedPanes[ts('Change Log')] = TRUE;
3912 }
3913
3914 /**
3915 * @param $values
3916 */
3917 public function demographics(&$values) {
3918 list($name, $op, $value, $grouping, $wildcard) = $values;
3919
3920 if (($name == 'age_low') || ($name == 'age_high')) {
3921 $this->ageRangeQueryBuilder($values,
3922 'contact_a', 'age', 'birth_date', ts('Age')
3923 );
3924 }
3925 elseif (($name == 'birth_date_low') || ($name == 'birth_date_high')) {
3926
3927 $this->dateQueryBuilder($values,
3928 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3929 );
3930 }
3931 elseif (($name == 'deceased_date_low') || ($name == 'deceased_date_high')) {
3932
3933 $this->dateQueryBuilder($values,
3934 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3935 );
3936 }
3937
3938 self::$_openedPanes[ts('Demographics')] = TRUE;
3939 }
3940
3941 /**
3942 * @param $values
3943 */
3944 public function privacy(&$values) {
3945 list($name, $op, $value, $grouping, $wildcard) = $values;
3946 //fixed for profile search listing CRM-4633
3947 if (strpbrk($value, "[")) {
3948 $value = "'{$value}'";
3949 $op = "!{$op}";
3950 $this->_where[$grouping][] = "contact_a.{$name} $op $value";
3951 }
3952 else {
3953 $this->_where[$grouping][] = "contact_a.{$name} $op $value";
3954 }
3955 $field = CRM_Utils_Array::value($name, $this->_fields);
3956 $op = CRM_Utils_Array::value($op, CRM_Core_SelectValues::getSearchBuilderOperators(), $op);
3957 $title = $field ? $field['title'] : $name;
3958 $this->_qill[$grouping][] = "$title $op $value";
3959 }
3960
3961 /**
3962 * @param $values
3963 */
3964 public function privacyOptions($values) {
3965 list($name, $op, $value, $grouping, $wildcard) = $values;
3966
3967 if (empty($value) || !is_array($value)) {
3968 return;
3969 }
3970
3971 // get the operator and toggle values
3972 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3973 $operator = 'OR';
3974 if ($opValues &&
3975 strtolower($opValues[2] == 'AND')
3976 ) {
3977 $operator = 'AND';
3978 }
3979
3980 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3981 $compareOP = '!';
3982 if ($toggleValues &&
3983 $toggleValues[2] == 2
3984 ) {
3985 $compareOP = '';
3986 }
3987
3988 $clauses = array();
3989 $qill = array();
3990 foreach ($value as $dontCare => $pOption) {
3991 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
3992 $field = CRM_Utils_Array::value($pOption, $this->_fields);
3993 $title = $field ? $field['title'] : $pOption;
3994 $qill[] = " $title = 1 ";
3995 }
3996
3997 $this->_where[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
3998 $this->_qill[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
3999 }
4000
4001 /**
4002 * @param $values
4003 */
4004 public function preferredCommunication(&$values) {
4005 list($name, $op, $value, $grouping, $wildcard) = $values;
4006
4007 if (!is_array($value)) {
4008 $value = str_replace(array('(', ')'), '', explode(",", $value));
4009 }
4010 elseif (in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
4011 $op = key($value);
4012 $value = $value[$op];
4013 }
4014 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contact_DAO_Contact', $name, $value, $op);
4015
4016 if (self::caseImportant($op)) {
4017 $value = implode("[[:cntrl:]]|[[:cntrl:]]", (array) $value);
4018 $op = (strstr($op, '!') || strstr($op, 'NOT')) ? 'NOT RLIKE' : 'RLIKE';
4019 $value = "[[:cntrl:]]" . $value . "[[:cntrl:]]";
4020 }
4021
4022 $this->_where[$grouping][] = self::buildClause("contact_a.preferred_communication_method", $op, $value);
4023 $this->_qill[$grouping][] = ts('Preferred Communication Method %1 %2', array(1 => $qillop, 2 => $qillVal));
4024 }
4025
4026 /**
4027 * Where / qill clause for relationship.
4028 *
4029 * @param array $values
4030 */
4031 public function relationship(&$values) {
4032 list($name, $op, $value, $grouping, $wildcard) = $values;
4033 if ($this->_relationshipValuesAdded) {
4034 return;
4035 }
4036 // also get values array for relation_target_name
4037 // for relationship search we always do wildcard
4038 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4039 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4040 $relStatus = $this->getWhereValues('relation_status', $grouping);
4041 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4042 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4043
4044 $nameClause = $name = NULL;
4045 if ($targetName) {
4046 $name = trim($targetName[2]);
4047 if (substr($name, 0, 1) == '"' &&
4048 substr($name, -1, 1) == '"'
4049 ) {
4050 $name = substr($name, 1, -1);
4051 $name = strtolower(CRM_Core_DAO::escapeString($name));
4052 $nameClause = "= '$name'";
4053 }
4054 else {
4055 $name = strtolower(CRM_Core_DAO::escapeString($name));
4056 $nameClause = "LIKE '%{$name}%'";
4057 }
4058 }
4059
4060 $rTypeValues = $relTypes = $relTypesIds = array();
4061 if (!empty($relationType)) {
4062 $relationType[2] = (array) $relationType[2];
4063 foreach ($relationType[2] as $relType) {
4064 $rel = explode('_', $relType);
4065 self::$_relType .= $rel[1];
4066 $params = array('id' => $rel[0]);
4067 $typeValues = array();
4068 $rTypeValue = CRM_Contact_BAO_RelationshipType::retrieve($params, $typeValues);
4069 if (!empty($rTypeValue)) {
4070 $rTypeValues[] = $rTypeValue;
4071 $relTypesIds[] = $rel[0];
4072 $relTypes[] = $relType;
4073 }
4074 }
4075 }
4076 if (!empty($rTypeValues)) {
4077 foreach ($rTypeValues as $rTypeValue) {
4078 $rTypeValue = (array) $rTypeValue;
4079 if ($rTypeValue['name_a_b'] == $rTypeValue['name_b_a']) {
4080 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4081 //@todo unless we are dealing with a target group
4082 self::$_relType = 'reciprocal';
4083 }
4084 }
4085 }
4086 // if we are creating a temp table we build our own where for the relationship table
4087 $relationshipTempTable = NULL;
4088 if (self::$_relType == 'reciprocal' && empty($targetGroup)) {
4089 $where = array();
4090 self::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO::createTempTableName('civicrm_rel');
4091 if ($nameClause) {
4092 $where[$grouping][] = " sort_name $nameClause ";
4093 }
4094 }
4095 else {
4096 $where = &$this->_where;
4097 if ($nameClause) {
4098 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4099 }
4100 }
4101 $allRelationshipType = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE);
4102 if ($nameClause || !$targetGroup) {
4103 if (!empty($relationType)) {
4104 $relQill = '';
4105 foreach ($relTypes as $rel) {
4106 if (!empty($relQill)) {
4107 $relQill .= ' OR ';
4108 }
4109 $relQill .= $allRelationshipType[$rel];
4110 }
4111 $this->_qill[$grouping][] = 'Relationship Type(s) ' . $relQill . " $name";
4112 }
4113 else {
4114 $this->_qill[$grouping][] = $name;
4115 }
4116 }
4117
4118 //check to see if the target contact is in specified group
4119 if ($targetGroup) {
4120 //add contacts from static groups
4121 $this->_tables['civicrm_relationship_group_contact'] = $this->_whereTables['civicrm_relationship_group_contact']
4122 = " 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'";
4123 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4124 implode(",", $targetGroup[2]) . ") ) ";
4125
4126 //add contacts from saved searches
4127 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b", $op);
4128
4129 //set the group where clause
4130 if ($ssWhere) {
4131 $groupWhere[] = "( " . $ssWhere . " )";
4132 }
4133 $this->_where[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4134
4135 //Get the names of the target groups for the qill
4136 $groupNames = CRM_Core_PseudoConstant::group();
4137 $qillNames = array();
4138 foreach ($targetGroup[2] as $groupId) {
4139 if (array_key_exists($groupId, $groupNames)) {
4140 $qillNames[] = $groupNames[$groupId];
4141 }
4142 }
4143 if (!empty($relationType)) {
4144 $relQill = '';
4145 foreach ($relTypes as $rel) {
4146 if (!empty($relQill)) {
4147 $relQill .= ' OR ';
4148 }
4149 $relQill .= $allRelationshipType[$rel];
4150 }
4151 $this->_qill[$grouping][] = 'Relationship Type(s) ' . $relQill . " ( " . implode(", ", $qillNames) . " )";
4152 }
4153 else {
4154 $this->_qill[$grouping][] = implode(", ", $qillNames);
4155 }
4156 }
4157
4158 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4159 $today = date('Ymd');
4160 //check for active, inactive and all relation status
4161 if ($relStatus[2] == 0) {
4162 $where[$grouping][] = "(
4163 civicrm_relationship.is_active = 1 AND
4164 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4165 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4166 )";
4167 $this->_qill[$grouping][] = ts('Relationship - Active and Current');
4168 }
4169 elseif ($relStatus[2] == 1) {
4170 $where[$grouping][] = "(
4171 civicrm_relationship.is_active = 0 OR
4172 civicrm_relationship.end_date < {$today} OR
4173 civicrm_relationship.start_date > {$today}
4174 )";
4175 $this->_qill[$grouping][] = ts('Relationship - Inactive or not Current');
4176 }
4177
4178 $onlyDeleted = 0;
4179 if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params)) {
4180 $onlyDeleted = 1;
4181 }
4182 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4183
4184 //check for permissioned, non-permissioned and all permissioned relations
4185 if ($relPermission[2] == 1) {
4186 $where[$grouping][] = "(
4187 civicrm_relationship.is_permission_a_b = 1
4188 )";
4189 $this->_qill[$grouping][] = ts('Relationship - Permissioned');
4190 }
4191 elseif ($relPermission[2] == 2) {
4192 //non-allowed permission relationship.
4193 $where[$grouping][] = "(
4194 civicrm_relationship.is_permission_a_b = 0
4195 )";
4196 $this->_qill[$grouping][] = ts('Relationship - Non-permissioned');
4197 }
4198
4199 $this->addRelationshipDateClauses($grouping, $where);
4200 $this->addRelationshipActivePeriodClauses($grouping, $where);
4201 if (!empty($relTypes)) {
4202 $where[$grouping][] = 'civicrm_relationship.relationship_type_id IN (' . implode(',', $relTypesIds) . ')';
4203 }
4204 $this->_tables['civicrm_relationship'] = $this->_whereTables['civicrm_relationship'] = 1;
4205 $this->_useDistinct = TRUE;
4206 $this->_relationshipValuesAdded = TRUE;
4207 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4208 // join on that,
4209 // @todo creating a temp table could be expanded to group filter
4210 // as even creating a temp table of all relationships is much much more efficient than
4211 // an OR in the join
4212 if ($relationshipTempTable) {
4213 $whereClause = '';
4214 if (!empty($where[$grouping])) {
4215 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4216 $whereClause = str_replace('contact_b', 'c', $whereClause);
4217 }
4218 $sql = "
4219 CREATE TEMPORARY TABLE {$relationshipTempTable}
4220 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4221 FROM civicrm_relationship
4222 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4223 $whereClause )
4224 UNION
4225 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4226 FROM civicrm_relationship
4227 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4228 $whereClause )
4229 ";
4230 CRM_Core_DAO::executeQuery($sql);
4231 }
4232 }
4233
4234 /**
4235 * Add start & end date criteria in
4236 * @param string $grouping
4237 * @param array $where
4238 * = array to add where clauses to, in case you are generating a temp table.
4239 * not the main query.
4240 */
4241 public function addRelationshipDateClauses($grouping, &$where) {
4242 $dateValues = array();
4243 $dateTypes = array(
4244 'start_date',
4245 'end_date',
4246 );
4247
4248 foreach ($dateTypes as $dateField) {
4249 $dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping);
4250 $dateValueHigh = $this->getWhereValues('relation_' . $dateField . '_high', $grouping);
4251 if (!empty($dateValueLow)) {
4252 $date = date('Ymd', strtotime($dateValueLow[2]));
4253 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4254 $this->_qill[$grouping][] = ($dateField == 'end_date' ? ts('Relationship Ended on or After') : ts('Relationship Recorded Start Date On or After')) . " " . CRM_Utils_Date::customFormat($date);
4255 }
4256 if (!empty($dateValueHigh)) {
4257 $date = date('Ymd', strtotime($dateValueHigh[2]));
4258 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4259 $this->_qill[$grouping][] = ($dateField == 'end_date' ? ts('Relationship Ended on or Before') : ts('Relationship Recorded Start Date On or Before')) . " " . CRM_Utils_Date::customFormat($date);
4260 }
4261 }
4262 }
4263
4264 /**
4265 * Add start & end active period criteria in
4266 * @param string $grouping
4267 * @param array $where
4268 * = array to add where clauses to, in case you are generating a temp table.
4269 * not the main query.
4270 */
4271 public function addRelationshipActivePeriodClauses($grouping, &$where) {
4272 $dateValues = array();
4273 $dateField = 'active_period_date';
4274
4275 $dateValueLow = $this->getWhereValues('relation_active_period_date_low', $grouping);
4276 $dateValueHigh = $this->getWhereValues('relation_active_period_date_high', $grouping);
4277 $dateValueLowFormated = $dateValueHighFormated = NULL;
4278 if (!empty($dateValueLow) && !empty($dateValueHigh)) {
4279 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4280 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4281 $this->_qill[$grouping][] = (ts('Relationship was active between')) . " " . CRM_Utils_Date::customFormat($dateValueLowFormated) . " and " . CRM_Utils_Date::customFormat($dateValueHighFormated);
4282 }
4283 elseif (!empty($dateValueLow)) {
4284 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4285 $this->_qill[$grouping][] = (ts('Relationship was active after')) . " " . CRM_Utils_Date::customFormat($dateValueLowFormated);
4286 }
4287 elseif (!empty($dateValueHigh)) {
4288 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4289 $this->_qill[$grouping][] = (ts('Relationship was active before')) . " " . CRM_Utils_Date::customFormat($dateValueHighFormated);
4290 }
4291
4292 if ($activePeriodClauses = self::getRelationshipActivePeriodClauses($dateValueLowFormated, $dateValueHighFormated, TRUE)) {
4293 $where[$grouping][] = $activePeriodClauses;
4294 }
4295 }
4296
4297 /**
4298 * Get start & end active period criteria
4299 */
4300 public static function getRelationshipActivePeriodClauses($from, $to, $forceTableName) {
4301 $tableName = $forceTableName ? 'civicrm_relationship.' : '';
4302 if (!is_null($from) && !is_null($to)) {
4303 return '(((' . $tableName . 'start_date >= ' . $from . ' AND ' . $tableName . 'start_date <= ' . $to . ') OR
4304 (' . $tableName . 'end_date >= ' . $from . ' AND ' . $tableName . 'end_date <= ' . $to . ') OR
4305 (' . $tableName . 'start_date <= ' . $from . ' AND ' . $tableName . 'end_date >= ' . $to . ' )) OR
4306 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4307 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . ') OR
4308 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4309 }
4310 elseif (!is_null($from)) {
4311 return '((' . $tableName . 'start_date >= ' . $from . ') OR
4312 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4313 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . '))';
4314 }
4315 elseif (!is_null($to)) {
4316 return '((' . $tableName . 'start_date <= ' . $to . ') OR
4317 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4318 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4319 }
4320 }
4321
4322 /**
4323 * Default set of return properties.
4324 *
4325 * @param int $mode
4326 *
4327 * @return array
4328 * derault return properties
4329 */
4330 public static function &defaultReturnProperties($mode = 1) {
4331 if (!isset(self::$_defaultReturnProperties)) {
4332 self::$_defaultReturnProperties = array();
4333 }
4334
4335 if (!isset(self::$_defaultReturnProperties[$mode])) {
4336 // add activity return properties
4337 if ($mode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
4338 self::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query::defaultReturnProperties($mode, FALSE);
4339 }
4340 else {
4341 self::$_defaultReturnProperties[$mode] = CRM_Core_Component::defaultReturnProperties($mode, FALSE);
4342 }
4343
4344 if (empty(self::$_defaultReturnProperties[$mode])) {
4345 self::$_defaultReturnProperties[$mode] = array(
4346 'home_URL' => 1,
4347 'image_URL' => 1,
4348 'legal_identifier' => 1,
4349 'external_identifier' => 1,
4350 'contact_type' => 1,
4351 'contact_sub_type' => 1,
4352 'sort_name' => 1,
4353 'display_name' => 1,
4354 'preferred_mail_format' => 1,
4355 'nick_name' => 1,
4356 'first_name' => 1,
4357 'middle_name' => 1,
4358 'last_name' => 1,
4359 'prefix_id' => 1,
4360 'suffix_id' => 1,
4361 'formal_title' => 1,
4362 'communication_style_id' => 1,
4363 'birth_date' => 1,
4364 'gender_id' => 1,
4365 'street_address' => 1,
4366 'supplemental_address_1' => 1,
4367 'supplemental_address_2' => 1,
4368 'supplemental_address_3' => 1,
4369 'city' => 1,
4370 'postal_code' => 1,
4371 'postal_code_suffix' => 1,
4372 'state_province' => 1,
4373 'country' => 1,
4374 'world_region' => 1,
4375 'geo_code_1' => 1,
4376 'geo_code_2' => 1,
4377 'email' => 1,
4378 'on_hold' => 1,
4379 'phone' => 1,
4380 'im' => 1,
4381 'household_name' => 1,
4382 'organization_name' => 1,
4383 'deceased_date' => 1,
4384 'is_deceased' => 1,
4385 'job_title' => 1,
4386 'legal_name' => 1,
4387 'sic_code' => 1,
4388 'current_employer' => 1,
4389 // FIXME: should we use defaultHierReturnProperties() for the below?
4390 'do_not_email' => 1,
4391 'do_not_mail' => 1,
4392 'do_not_sms' => 1,
4393 'do_not_phone' => 1,
4394 'do_not_trade' => 1,
4395 'is_opt_out' => 1,
4396 'contact_is_deleted' => 1,
4397 'preferred_communication_method' => 1,
4398 'preferred_language' => 1,
4399 );
4400 }
4401 }
4402 return self::$_defaultReturnProperties[$mode];
4403 }
4404
4405 /**
4406 * Get primary condition for a sql clause.
4407 *
4408 * @param int $value
4409 *
4410 * @return string|NULL
4411 */
4412 public static function getPrimaryCondition($value) {
4413 if (is_numeric($value)) {
4414 $value = (int ) $value;
4415 return ($value == 1) ? 'is_primary = 1' : 'is_primary = 0';
4416 }
4417 return NULL;
4418 }
4419
4420 /**
4421 * Wrapper for a simple search query.
4422 *
4423 * @param array $params
4424 * @param array $returnProperties
4425 * @param bool $count
4426 *
4427 * @return string
4428 */
4429 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4430 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4431 list($select, $from, $where, $having) = $query->query();
4432 $groupBy = ($query->_useGroupBy) ? 'GROUP BY contact_a.id' : '';
4433
4434 $query = "$select $from $where $groupBy $having";
4435 return $query;
4436 }
4437
4438 /**
4439 * These are stub comments as this function needs more explanation - particularly in terms of how it
4440 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4441 *
4442 * This function was originally written as a wrapper for the api query but is called from multiple places
4443 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4444 * but it is unclear as to whehter that is historical or there is a reason
4445 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4446 *
4447 * @param array $params
4448 * @param array $returnProperties
4449 * @param null $fields
4450 * @param string $sort
4451 * @param int $offset
4452 * @param int $row_count
4453 * @param bool $smartGroupCache
4454 * ?? update smart group cache?.
4455 * @param bool $count
4456 * Return count obnly.
4457 * @param bool $skipPermissions
4458 * Should permissions be ignored or should the logged in user's permissions be applied.
4459 * @param int $mode
4460 * This basically correlates to the component.
4461 * @param string $apiEntity
4462 * The api entity being called.
4463 * This sort-of duplicates $mode in a confusing way. Probably not by design.
4464 *
4465 * @param bool|null $primaryLocationOnly
4466 * @return array
4467 */
4468 public static function apiQuery(
4469 $params = NULL,
4470 $returnProperties = NULL,
4471 $fields = NULL,
4472 $sort = NULL,
4473 $offset = 0,
4474 $row_count = 25,
4475 $smartGroupCache = TRUE,
4476 $count = FALSE,
4477 $skipPermissions = TRUE,
4478 $mode = CRM_Contact_BAO_Query::MODE_CONTACTS,
4479 $apiEntity = NULL,
4480 $primaryLocationOnly = NULL
4481 ) {
4482
4483 $query = new CRM_Contact_BAO_Query(
4484 $params, $returnProperties,
4485 NULL, TRUE, FALSE, $mode,
4486 $skipPermissions,
4487 TRUE, $smartGroupCache,
4488 NULL, 'AND',
4489 $apiEntity, $primaryLocationOnly
4490 );
4491
4492 //this should add a check for view deleted if permissions are enabled
4493 if ($skipPermissions) {
4494 $query->_skipDeleteClause = TRUE;
4495 }
4496 $query->generatePermissionClause(FALSE, $count);
4497
4498 // note : this modifies _fromClause and _simpleFromClause
4499 $query->includePseudoFieldsJoin($sort);
4500
4501 list($select, $from, $where, $having) = $query->query($count);
4502
4503 $options = $query->_options;
4504 if (!empty($query->_permissionWhereClause)) {
4505 if (empty($where)) {
4506 $where = "WHERE $query->_permissionWhereClause";
4507 }
4508 else {
4509 $where = "$where AND $query->_permissionWhereClause";
4510 }
4511 }
4512
4513 $sql = "$select $from $where $having";
4514
4515 // add group by only when API action is not getcount
4516 // otherwise query fetches incorrect count
4517 if ($query->_useGroupBy && !$count) {
4518 $sql .= self::getGroupByFromSelectColumns($query->_select, 'contact_a.id');
4519 }
4520 if (!empty($sort)) {
4521 $sort = CRM_Utils_Type::escape($sort, 'String');
4522 $sql .= " ORDER BY $sort ";
4523 }
4524 if ($row_count > 0 && $offset >= 0) {
4525 $offset = CRM_Utils_Type::escape($offset, 'Int');
4526 $row_count = CRM_Utils_Type::escape($row_count, 'Int');
4527 $sql .= " LIMIT $offset, $row_count ";
4528 }
4529
4530 $dao = CRM_Core_DAO::executeQuery($sql);
4531
4532 // @todo derive this from the component class rather than hard-code two options.
4533 $entityIDField = ($mode == CRM_Contact_BAO_Query::MODE_CONTRIBUTE) ? 'contribution_id' : 'contact_id';
4534
4535 $values = array();
4536 while ($dao->fetch()) {
4537 if ($count) {
4538 $noRows = $dao->rowCount;
4539 $dao->free();
4540 return array($noRows, NULL);
4541 }
4542 $val = $query->store($dao);
4543 $convertedVals = $query->convertToPseudoNames($dao, TRUE, TRUE);
4544
4545 if (!empty($convertedVals)) {
4546 $val = array_replace_recursive($val, $convertedVals);
4547 }
4548 $values[$dao->$entityIDField] = $val;
4549 }
4550 $dao->free();
4551 return array($values, $options);
4552 }
4553
4554 /**
4555 * Get the actual custom field name by stripping off the appended string.
4556 *
4557 * The string could be _relative, _from, or _to
4558 *
4559 * @todo use metadata rather than convention to do this.
4560 *
4561 * @param string $parameterName
4562 * The name of the parameter submitted to the form.
4563 * e.g
4564 * custom_3_relative
4565 * custom_3_from
4566 *
4567 * @return string
4568 */
4569 public static function getCustomFieldName($parameterName) {
4570 if (substr($parameterName, -5, 5) == '_from') {
4571 return substr($parameterName, 0, strpos($parameterName, '_from'));
4572 }
4573 if (substr($parameterName, -9, 9) == '_relative') {
4574 return substr($parameterName, 0, strpos($parameterName, '_relative'));
4575 }
4576 if (substr($parameterName, -3, 3) == '_to') {
4577 return substr($parameterName, 0, strpos($parameterName, '_to'));
4578 }
4579 }
4580
4581 /**
4582 * Convert submitted values for relative custom fields to query object format.
4583 *
4584 * The query will support the sqlOperator format so convert to that format.
4585 *
4586 * @param array $formValues
4587 * Submitted values.
4588 * @param array $params
4589 * Converted parameters for the query object.
4590 * @param string $values
4591 * Submitted value.
4592 * @param string $fieldName
4593 * Submitted field name. (Matches form field not DB field.)
4594 */
4595 protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) {
4596 if (empty($values)) {
4597 // e.g we might have relative set & from & to empty. The form flow is a bit funky &
4598 // this function gets called again after they fields have been converted which can get ugly.
4599 return;
4600 }
4601 $customFieldName = self::getCustomFieldName($fieldName);
4602
4603 if (substr($fieldName, -9, 9) == '_relative') {
4604 list($from, $to) = CRM_Utils_Date::getFromTo($values, NULL, NULL);
4605 }
4606 else {
4607 if ($fieldName == $customFieldName . '_to' && CRM_Utils_Array::value($customFieldName . '_from', $formValues)) {
4608 // Both to & from are set. We only need to acton one, choosing from.
4609 return;
4610 }
4611
4612 $from = CRM_Utils_Array::value($customFieldName . '_from', $formValues, NULL);
4613 $to = CRM_Utils_Array::value($customFieldName . '_to', $formValues, NULL);
4614
4615 if (self::isCustomDateField($customFieldName)) {
4616 list($from, $to) = CRM_Utils_Date::getFromTo(NULL, $from, $to);
4617 }
4618 }
4619
4620 if ($from) {
4621 if ($to) {
4622 $relativeFunction = array('BETWEEN' => array($from, $to));
4623 }
4624 else {
4625 $relativeFunction = array('>=' => $from);
4626 }
4627 }
4628 else {
4629 $relativeFunction = array('<=' => $to);
4630 }
4631 $params[] = array(
4632 $customFieldName,
4633 '=',
4634 $relativeFunction,
4635 0,
4636 0,
4637 );
4638 }
4639
4640 /**
4641 * Are we dealing with custom field of type date.
4642 *
4643 * @param $fieldName
4644 *
4645 * @return bool
4646 */
4647 public static function isCustomDateField($fieldName) {
4648 if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($fieldName)) == FALSE) {
4649 return FALSE;
4650 }
4651 if ('Date' == civicrm_api3('CustomField', 'getvalue', array('id' => $customFieldID, 'return' => 'data_type'))) {
4652 return TRUE;
4653 }
4654 return FALSE;
4655 }
4656
4657 /**
4658 * Has this field already been reformatting to Query object syntax.
4659 *
4660 * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems
4661 * to come with associated double queries & is possibly damaging performance.
4662 *
4663 * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns
4664 * them as they are.
4665 *
4666 * @param mixed $values
4667 * Value in formValues for the field.
4668 *
4669 * @return bool;
4670 */
4671 public static function isAlreadyProcessedForQueryFormat($values) {
4672 if (!is_array($values)) {
4673 return FALSE;
4674 }
4675 if (($operator = CRM_Utils_Array::value(1, $values)) == FALSE) {
4676 return FALSE;
4677 }
4678 return in_array($operator, CRM_Core_DAO::acceptedSQLOperators());
4679 }
4680
4681 /**
4682 * If the state and country are passed remove state.
4683 *
4684 * Country is implicit from the state, but including both results in
4685 * a poor query as there is no combined index on state AND country.
4686 *
4687 * CRM-18125
4688 *
4689 * @param array $formValues
4690 */
4691 public static function filterCountryFromValuesIfStateExists(&$formValues) {
4692 if (!empty($formValues['country']) && !empty($formValues['state_province'])) {
4693 // The use of array map sanitises the data by ensuring we are dealing with integers.
4694 $states = implode(', ', array_map('intval', $formValues['state_province']));
4695 $countryList = CRM_Core_DAO::singleValueQuery(
4696 "SELECT GROUP_CONCAT(country_id) FROM civicrm_state_province WHERE id IN ($states)"
4697 );
4698 if ($countryList == $formValues['country']) {
4699 unset($formValues['country']);
4700 }
4701 }
4702 }
4703
4704 /**
4705 * For some special cases, grouping by subset of select fields becomes mandatory.
4706 * Hence, full_group_by mode is handled by appending any_value
4707 * keyword to select fields not present in groupBy
4708 *
4709 * @param array $selectClauses
4710 * @param array $groupBy - Columns already included in GROUP By clause.
4711 * @param string $aggregateFunction
4712 *
4713 * @return string
4714 */
4715 public static function appendAnyValueToSelect($selectClauses, $groupBy, $aggregateFunction = 'ANY_VALUE') {
4716 if (!CRM_Utils_SQL::disableFullGroupByMode()) {
4717 $groupBy = array_map('trim', (array) $groupBy);
4718 $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4719 foreach ($selectClauses as $key => &$val) {
4720 list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL);
4721 // append ANY_VALUE() keyword
4722 if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) {
4723 $val = ($aggregateFunction == 'GROUP_CONCAT') ?
4724 str_replace($selectColumn, "$aggregateFunction(DISTINCT {$selectColumn})", $val) :
4725 str_replace($selectColumn, "$aggregateFunction({$selectColumn})", $val);
4726 }
4727 }
4728 }
4729
4730 return "SELECT " . implode(', ', $selectClauses) . " ";
4731 }
4732
4733 /**
4734 * For some special cases, where if non-aggregate ORDER BY columns are not present in GROUP BY
4735 * on full_group_by mode, then append the those missing columns to GROUP BY clause
4736 * keyword to select fields not present in groupBy
4737 *
4738 * @param string $groupBy - GROUP BY clause where missing ORDER BY columns will be appended if not present
4739 * @param array $orderBys - ORDER BY sub-clauses
4740 *
4741 */
4742 public static function getGroupByFromOrderBy(&$groupBy, $orderBys) {
4743 if (!CRM_Utils_SQL::disableFullGroupByMode()) {
4744 foreach ($orderBys as $orderBy) {
4745 $orderBy = str_ireplace(array(' DESC', ' ASC', '`'), '', $orderBy); // remove sort syntax from ORDER BY clauses if present
4746 // if ORDER BY column is not present in GROUP BY then append it to end
4747 if (preg_match('/(MAX|MIN)\(/i', trim($orderBy)) !== 1 && !strstr($groupBy, $orderBy)) {
4748 $groupBy .= ", {$orderBy}";
4749 }
4750 }
4751 }
4752 }
4753
4754 /**
4755 * Include Select columns in groupBy clause.
4756 *
4757 * @param array $selectClauses
4758 * @param array $groupBy - Columns already included in GROUP By clause.
4759 *
4760 * @return string
4761 */
4762 public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NULL) {
4763 $groupBy = (array) $groupBy;
4764 $mysqlVersion = CRM_Core_DAO::singleValueQuery('SELECT VERSION()');
4765 $sqlMode = CRM_Core_DAO::singleValueQuery('SELECT @@sql_mode');
4766
4767 //return if ONLY_FULL_GROUP_BY is not enabled.
4768 if (CRM_Utils_SQL::supportsFullGroupBy() && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
4769 $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4770 foreach ($selectClauses as $key => $val) {
4771 $aliasArray = preg_split('/ as /i', $val);
4772 // if more than 1 alias we need to split by ','.
4773 if (count($aliasArray) > 2) {
4774 $aliasArray = preg_split('/,/', $val);
4775 foreach ($aliasArray as $key => $value) {
4776 $alias = current(preg_split('/ as /i', $value));
4777 if (!in_array($alias, $groupBy) && preg_match($regexToExclude, trim($alias)) !== 1) {
4778 $groupBy[] = $alias;
4779 }
4780 }
4781 }
4782 else {
4783 list($selectColumn, $alias) = array_pad($aliasArray, 2, NULL);
4784 $dateRegex = '/^(DATE_FORMAT|DATE_ADD|CASE)/i';
4785 $tableName = current(explode('.', $selectColumn));
4786 $primaryKey = "{$tableName}.id";
4787 // exclude columns which are already included in groupBy and aggregate functions from select
4788 // CRM-18439 - Also exclude the columns which are functionally dependent on columns in $groupBy (MySQL 5.7+)
4789 if (!in_array($selectColumn, $groupBy) && !in_array($primaryKey, $groupBy) && preg_match($regexToExclude, trim($selectColumn)) !== 1) {
4790 if (!empty($alias) && preg_match($dateRegex, trim($selectColumn))) {
4791 $groupBy[] = $alias;
4792 }
4793 else {
4794 $groupBy[] = $selectColumn;
4795 }
4796 }
4797 }
4798 }
4799 }
4800
4801 if (!empty($groupBy)) {
4802 return " GROUP BY " . implode(', ', $groupBy);
4803 }
4804 return '';
4805 }
4806
4807 /**
4808 * Create and query the db for an contact search.
4809 *
4810 * @param int $offset
4811 * The offset for the query.
4812 * @param int $rowCount
4813 * The number of rows to return.
4814 * @param string|CRM_Utils_Sort $sort
4815 * The order by string.
4816 * @param bool $count
4817 * Is this a count only query ?.
4818 * @param bool $includeContactIds
4819 * Should we include contact ids?.
4820 * @param bool $sortByChar
4821 * If true returns the distinct array of first characters for search results.
4822 * @param bool $groupContacts
4823 * If true, return only the contact ids.
4824 * @param bool $returnQuery
4825 * Should we return the query as a string.
4826 * @param string $additionalWhereClause
4827 * If the caller wants to further restrict the search (used for components).
4828 * @param null $sortOrder
4829 * @param string $additionalFromClause
4830 * Should be clause with proper joins, effective to reduce where clause load.
4831 *
4832 * @param bool $skipOrderAndLimit
4833 *
4834 * @return CRM_Core_DAO
4835 */
4836 public function searchQuery(
4837 $offset = 0, $rowCount = 0, $sort = NULL,
4838 $count = FALSE, $includeContactIds = FALSE,
4839 $sortByChar = FALSE, $groupContacts = FALSE,
4840 $returnQuery = FALSE,
4841 $additionalWhereClause = NULL, $sortOrder = NULL,
4842 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4843 ) {
4844
4845 if ($includeContactIds) {
4846 $this->_includeContactIds = TRUE;
4847 $this->_whereClause = $this->whereClause();
4848 }
4849
4850 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params);
4851
4852 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4853 // and that contact happens to be deleted, set $onlyDeleted to true
4854 foreach ($this->_params as $values) {
4855 $name = CRM_Utils_Array::value(0, $values);
4856 $op = CRM_Utils_Array::value(1, $values);
4857 $value = CRM_Utils_Array::value(2, $values);
4858 if ($name == 'contact_id' and $op == '=') {
4859 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4860 $onlyDeleted = TRUE;
4861 }
4862 break;
4863 }
4864 }
4865
4866 // building the query string
4867 $groupBy = $groupByCols = NULL;
4868 if (!$count) {
4869 if (isset($this->_groupByComponentClause)) {
4870 $groupBy = $this->_groupByComponentClause;
4871 $groupByCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause));
4872 $groupByCols = explode(', ', $groupByCols);
4873 }
4874 elseif ($this->_useGroupBy) {
4875 $groupByCols = array('contact_a.id');
4876 }
4877 }
4878 if ($this->_mode & CRM_Contact_BAO_Query::MODE_ACTIVITY && (!$count)) {
4879 $groupByCols = array('civicrm_activity.id');
4880 }
4881
4882 $order = $orderBy = $limit = '';
4883 if (!$count) {
4884 list($order, $additionalFromClause) = $this->prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause);
4885
4886 if ($rowCount > 0 && $offset >= 0) {
4887 $offset = CRM_Utils_Type::escape($offset, 'Int');
4888 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
4889 $limit = " LIMIT $offset, $rowCount ";
4890 }
4891 }
4892 // Two cases where we are disabling FGB (FULL_GROUP_BY_MODE):
4893 // 1. Expecting the search query to return all the first single letter characters of contacts ONLY, but when FGB is enabled
4894 // MySQL expect the columns present in GROUP BY, must be present in SELECT clause and that results into error, needless to have other columns.
4895 // 2. When GROUP BY columns are present then disable FGB otherwise it demands to add ORDER BY columns in GROUP BY and eventually in SELECT
4896 // clause. This will impact the search query output.
4897 $disableFullGroupByMode = ($sortByChar || !empty($groupByCols));
4898
4899 if ($disableFullGroupByMode) {
4900 CRM_Core_DAO::disableFullGroupByMode();
4901 }
4902
4903 // CRM-15231
4904 $this->_sort = $sort;
4905
4906 //CRM-15967
4907 $this->includePseudoFieldsJoin($sort);
4908
4909 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4910
4911 if (!empty($groupByCols)) {
4912 $groupBy = " GROUP BY " . implode(', ', $groupByCols);
4913 }
4914
4915 if ($additionalWhereClause) {
4916 $where = $where . ' AND ' . $additionalWhereClause;
4917 }
4918
4919 //additional from clause should be w/ proper joins.
4920 if ($additionalFromClause) {
4921 $from .= "\n" . $additionalFromClause;
4922 }
4923
4924 // if we are doing a transform, do it here
4925 // use the $from, $where and $having to get the contact ID
4926 if ($this->_displayRelationshipType) {
4927 $this->filterRelatedContacts($from, $where, $having);
4928 }
4929
4930 if ($skipOrderAndLimit) {
4931 $query = "$select $from $where $having $groupBy";
4932 }
4933 else {
4934 $query = "$select $from $where $having $groupBy $order $limit";
4935 }
4936
4937 if ($returnQuery) {
4938 return $query;
4939 }
4940 if ($count) {
4941 return CRM_Core_DAO::singleValueQuery($query);
4942 }
4943
4944 $dao = CRM_Core_DAO::executeQuery($query);
4945
4946 if ($disableFullGroupByMode) {
4947 CRM_Core_DAO::reenableFullGroupByMode();
4948 }
4949
4950 if ($groupContacts) {
4951 $ids = array();
4952 while ($dao->fetch()) {
4953 $ids[] = $dao->id;
4954 }
4955 $dao->free();
4956 return implode(',', $ids);
4957 }
4958
4959 return $dao;
4960 }
4961
4962 /**
4963 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4964 *
4965 * @param string $cacheKey
4966 * @param int $offset
4967 * @param int $rowCount
4968 * @param bool $includeContactIds
4969 * @return CRM_Core_DAO
4970 */
4971 public function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4972 $this->_includeContactIds = $includeContactIds;
4973 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params);
4974 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
4975 $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);
4976 $order = " ORDER BY pnc.id";
4977 $groupByCol = array('contact_a.id', 'pnc.id');
4978 $select = self::appendAnyValueToSelect($this->_select, $groupByCol, 'GROUP_CONCAT');
4979 $groupBy = " GROUP BY " . implode(', ', $groupByCol);
4980 $limit = " LIMIT $offset, $rowCount";
4981 $query = "$select $from $where $groupBy $order $limit";
4982
4983 return CRM_Core_DAO::executeQuery($query);
4984 }
4985
4986 /**
4987 * Populate $this->_permissionWhereClause with permission related clause and update other
4988 * query related properties.
4989 *
4990 * Function calls ACL permission class and hooks to filter the query appropriately
4991 *
4992 * Note that these 2 params were in the code when extracted from another function
4993 * and a second round extraction would be to make them properties of the class
4994 *
4995 * @param bool $onlyDeleted
4996 * Only get deleted contacts.
4997 * @param bool $count
4998 * Return Count only.
4999 */
5000 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
5001 if (!$this->_skipPermission) {
5002 $this->_permissionWhereClause = CRM_ACL_API::whereClause(
5003 CRM_Core_Permission::VIEW,
5004 $this->_tables,
5005 $this->_whereTables,
5006 NULL,
5007 $onlyDeleted,
5008 $this->_skipDeleteClause
5009 );
5010
5011 // regenerate fromClause since permission might have added tables
5012 if ($this->_permissionWhereClause) {
5013 //fix for row count in qill (in contribute/membership find)
5014 if (!$count) {
5015 $this->_useDistinct = TRUE;
5016 }
5017 //CRM-15231
5018 $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode);
5019 $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode);
5020 // note : this modifies _fromClause and _simpleFromClause
5021 $this->includePseudoFieldsJoin($this->_sort);
5022 }
5023 }
5024 else {
5025 // add delete clause if needed even if we are skipping permission
5026 // CRM-7639
5027 if (!$this->_skipDeleteClause) {
5028 if (CRM_Core_Permission::check('access deleted contacts') and $onlyDeleted) {
5029 $this->_permissionWhereClause = '(contact_a.is_deleted)';
5030 }
5031 else {
5032 // CRM-6181
5033 $this->_permissionWhereClause = '(contact_a.is_deleted = 0)';
5034 }
5035 }
5036 }
5037 }
5038
5039 /**
5040 * @param $val
5041 */
5042 public function setSkipPermission($val) {
5043 $this->_skipPermission = $val;
5044 }
5045
5046 /**
5047 * @param null $context
5048 *
5049 * @return array
5050 */
5051 public function &summaryContribution($context = NULL) {
5052 list($innerselect, $from, $where, $having) = $this->query(TRUE);
5053
5054 // hack $select
5055 $select = "
5056 SELECT COUNT( conts.total_amount ) as total_count,
5057 SUM( conts.total_amount ) as total_amount,
5058 AVG( conts.total_amount ) as total_avg,
5059 conts.currency as currency";
5060 if ($this->_permissionWhereClause) {
5061 $where .= " AND " . $this->_permissionWhereClause;
5062 }
5063 if ($context == 'search') {
5064 $where .= " AND contact_a.is_deleted = 0 ";
5065 }
5066
5067 $query = $this->appendFinancialTypeWhereAndFromToQueryStrings($where, $from);
5068
5069 // make sure contribution is completed - CRM-4989
5070 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
5071
5072 $summary = array();
5073 $summary['total'] = array();
5074 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
5075 $innerQuery = "SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
5076 civicrm_contribution.currency $from $completedWhere";
5077 $query = "$select FROM (
5078 $innerQuery GROUP BY civicrm_contribution.id
5079 ) as conts
5080 GROUP BY currency";
5081
5082 $dao = CRM_Core_DAO::executeQuery($query);
5083
5084 $summary['total']['count'] = 0;
5085 $summary['total']['amount'] = $summary['total']['avg'] = array();
5086 while ($dao->fetch()) {
5087 $summary['total']['count'] += $dao->total_count;
5088 $summary['total']['amount'][] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
5089 $summary['total']['avg'][] = CRM_Utils_Money::format($dao->total_avg, $dao->currency);
5090 }
5091
5092 $orderBy = 'ORDER BY civicrm_contribution_total_amount_count DESC';
5093 $groupBy = 'GROUP BY currency, civicrm_contribution.total_amount';
5094 $modeSQL = "$select, SUBSTRING_INDEX(GROUP_CONCAT(conts.total_amount
5095 ORDER BY conts.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
5096 MAX(conts.civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count
5097 FROM ($innerQuery
5098 $groupBy $orderBy) as conts
5099 GROUP BY currency";
5100
5101 $summary['total']['mode'] = CRM_Contribute_BAO_Contribution::computeStats('mode', $modeSQL);
5102
5103 $medianSQL = "{$from} {$completedWhere}";
5104 $summary['total']['median'] = CRM_Contribute_BAO_Contribution::computeStats('median', $medianSQL, 'civicrm_contribution');
5105 $summary['total']['currencyCount'] = count($summary['total']['median']);
5106
5107 if (!empty($summary['total']['amount'])) {
5108 $summary['total']['amount'] = implode(',&nbsp;', $summary['total']['amount']);
5109 $summary['total']['avg'] = implode(',&nbsp;', $summary['total']['avg']);
5110 $summary['total']['mode'] = implode(',&nbsp;', $summary['total']['mode']);
5111 $summary['total']['median'] = implode(',&nbsp;', $summary['total']['median']);
5112 }
5113 else {
5114 $summary['total']['amount'] = $summary['total']['avg'] = $summary['total']['median'] = 0;
5115 }
5116
5117 // soft credit summary
5118 if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
5119 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
5120 $query = "
5121 $select FROM (
5122 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
5123 GROUP BY civicrm_contribution_soft.id
5124 ) as conts
5125 GROUP BY currency";
5126 $dao = CRM_Core_DAO::executeQuery($query);
5127 $summary['soft_credit']['count'] = 0;
5128 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
5129 while ($dao->fetch()) {
5130 $summary['soft_credit']['count'] += $dao->total_count;
5131 $summary['soft_credit']['amount'][] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
5132 $summary['soft_credit']['avg'][] = CRM_Utils_Money::format($dao->total_avg, $dao->currency);
5133 }
5134 if (!empty($summary['soft_credit']['amount'])) {
5135 $summary['soft_credit']['amount'] = implode(',&nbsp;', $summary['soft_credit']['amount']);
5136 $summary['soft_credit']['avg'] = implode(',&nbsp;', $summary['soft_credit']['avg']);
5137 }
5138 else {
5139 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
5140 }
5141 }
5142
5143 // hack $select
5144 //@todo - this could be one query using the IF in mysql - eg
5145 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
5146 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
5147 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
5148 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
5149 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
5150 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
5151 // FROM civicrm_contact contact_a
5152 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
5153 // WHERE ( ... where clause....
5154 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
5155 // ) as conts
5156
5157 $select = "
5158 SELECT COUNT( conts.total_amount ) as cancel_count,
5159 SUM( conts.total_amount ) as cancel_amount,
5160 AVG( conts.total_amount ) as cancel_avg,
5161 conts.currency as currency";
5162
5163 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
5164 if ($context == 'search') {
5165 $where .= " AND contact_a.is_deleted = 0 ";
5166 }
5167
5168 $query = "$select FROM (
5169 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
5170 GROUP BY civicrm_contribution.id
5171 ) as conts
5172 GROUP BY currency";
5173
5174 $dao = CRM_Core_DAO::executeQuery($query);
5175
5176 if ($dao->N <= 1) {
5177 if ($dao->fetch()) {
5178 $summary['cancel']['count'] = $dao->cancel_count;
5179 $summary['cancel']['amount'] = CRM_Utils_Money::format($dao->cancel_amount, $dao->currency);
5180 $summary['cancel']['avg'] = CRM_Utils_Money::format($dao->cancel_avg, $dao->currency);
5181 }
5182 }
5183 else {
5184 $summary['cancel']['count'] = 0;
5185 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
5186 while ($dao->fetch()) {
5187 $summary['cancel']['count'] += $dao->cancel_count;
5188 $summary['cancel']['amount'][] = CRM_Utils_Money::format($dao->cancel_amount, $dao->currency);
5189 $summary['cancel']['avg'][] = CRM_Utils_Money::format($dao->cancel_avg, $dao->currency);
5190 }
5191 $summary['cancel']['amount'] = implode(',&nbsp;', $summary['cancel']['amount']);
5192 $summary['cancel']['avg'] = implode(',&nbsp;', $summary['cancel']['avg']);
5193 }
5194
5195 return $summary;
5196 }
5197
5198 /**
5199 * Append financial ACL limits to the query from & where clauses, if applicable.
5200 *
5201 * @param string $where
5202 * @param string $from
5203 */
5204 public function appendFinancialTypeWhereAndFromToQueryStrings(&$where, &$from) {
5205 if (!CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
5206 return;
5207 }
5208 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
5209 if (!empty($financialTypes)) {
5210 $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
5211 $from .= " LEFT JOIN civicrm_line_item li
5212 ON civicrm_contribution.id = li.contribution_id AND
5213 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
5214 }
5215 else {
5216 $where .= " AND civicrm_contribution.financial_type_id IN (0)";
5217 }
5218 }
5219
5220 /**
5221 * Getter for the qill object.
5222 *
5223 * @return string
5224 */
5225 public function qill() {
5226 return $this->_qill;
5227 }
5228
5229 /**
5230 * Default set of return default hier return properties.
5231 *
5232 * @return array
5233 */
5234 public static function &defaultHierReturnProperties() {
5235 if (!isset(self::$_defaultHierReturnProperties)) {
5236 self::$_defaultHierReturnProperties = array(
5237 'home_URL' => 1,
5238 'image_URL' => 1,
5239 'legal_identifier' => 1,
5240 'external_identifier' => 1,
5241 'contact_type' => 1,
5242 'contact_sub_type' => 1,
5243 'sort_name' => 1,
5244 'display_name' => 1,
5245 'nick_name' => 1,
5246 'first_name' => 1,
5247 'middle_name' => 1,
5248 'last_name' => 1,
5249 'prefix_id' => 1,
5250 'suffix_id' => 1,
5251 'formal_title' => 1,
5252 'communication_style_id' => 1,
5253 'email_greeting' => 1,
5254 'postal_greeting' => 1,
5255 'addressee' => 1,
5256 'birth_date' => 1,
5257 'gender_id' => 1,
5258 'preferred_communication_method' => 1,
5259 'do_not_phone' => 1,
5260 'do_not_email' => 1,
5261 'do_not_mail' => 1,
5262 'do_not_sms' => 1,
5263 'do_not_trade' => 1,
5264 'location' => array(
5265 '1' => array(
5266 'location_type' => 1,
5267 'street_address' => 1,
5268 'city' => 1,
5269 'state_province' => 1,
5270 'postal_code' => 1,
5271 'postal_code_suffix' => 1,
5272 'country' => 1,
5273 'phone-Phone' => 1,
5274 'phone-Mobile' => 1,
5275 'phone-Fax' => 1,
5276 'phone-1' => 1,
5277 'phone-2' => 1,
5278 'phone-3' => 1,
5279 'im-1' => 1,
5280 'im-2' => 1,
5281 'im-3' => 1,
5282 'email-1' => 1,
5283 'email-2' => 1,
5284 'email-3' => 1,
5285 ),
5286 '2' => array(
5287 'location_type' => 1,
5288 'street_address' => 1,
5289 'city' => 1,
5290 'state_province' => 1,
5291 'postal_code' => 1,
5292 'postal_code_suffix' => 1,
5293 'country' => 1,
5294 'phone-Phone' => 1,
5295 'phone-Mobile' => 1,
5296 'phone-1' => 1,
5297 'phone-2' => 1,
5298 'phone-3' => 1,
5299 'im-1' => 1,
5300 'im-2' => 1,
5301 'im-3' => 1,
5302 'email-1' => 1,
5303 'email-2' => 1,
5304 'email-3' => 1,
5305 ),
5306 ),
5307 );
5308 }
5309 return self::$_defaultHierReturnProperties;
5310 }
5311
5312 /**
5313 * Build query for a date field.
5314 *
5315 * @param array $values
5316 * @param string $tableName
5317 * @param string $fieldName
5318 * @param string $dbFieldName
5319 * @param string $fieldTitle
5320 * @param bool $appendTimeStamp
5321 * @param string $dateFormat
5322 */
5323 public function dateQueryBuilder(
5324 &$values, $tableName, $fieldName,
5325 $dbFieldName, $fieldTitle,
5326 $appendTimeStamp = TRUE,
5327 $dateFormat = 'YmdHis'
5328 ) {
5329 list($name, $op, $value, $grouping, $wildcard) = $values;
5330
5331 if ($name == "{$fieldName}_low" ||
5332 $name == "{$fieldName}_high"
5333 ) {
5334 if (isset($this->_rangeCache[$fieldName]) || !$value) {
5335 return;
5336 }
5337 $this->_rangeCache[$fieldName] = 1;
5338
5339 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
5340
5341 if ($name == $fieldName . '_low') {
5342 $firstOP = '>=';
5343 $firstPhrase = ts('greater than or equal to');
5344 $firstDate = CRM_Utils_Date::processDate($value, NULL, FALSE, $dateFormat);
5345
5346 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5347 if (!empty($secondValues) && $secondValues[2]) {
5348 $secondOP = '<=';
5349 $secondPhrase = ts('less than or equal to');
5350 $secondValue = $secondValues[2];
5351
5352 if ($appendTimeStamp && strlen($secondValue) == 10) {
5353 $secondValue .= ' 23:59:59';
5354 }
5355 $secondDate = CRM_Utils_Date::processDate($secondValue, NULL, FALSE, $dateFormat);
5356 }
5357 }
5358 elseif ($name == $fieldName . '_high') {
5359 $firstOP = '<=';
5360 $firstPhrase = ts('less than or equal to');
5361
5362 if ($appendTimeStamp && strlen($value) == 10) {
5363 $value .= ' 23:59:59';
5364 }
5365 $firstDate = CRM_Utils_Date::processDate($value, NULL, FALSE, $dateFormat);
5366
5367 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5368 if (!empty($secondValues) && $secondValues[2]) {
5369 $secondOP = '>=';
5370 $secondPhrase = ts('greater than or equal to');
5371 $secondValue = $secondValues[2];
5372 $secondDate = CRM_Utils_Date::processDate($secondValue, NULL, FALSE, $dateFormat);
5373 }
5374 }
5375
5376 if (!$appendTimeStamp) {
5377 $firstDate = substr($firstDate, 0, 8);
5378 }
5379 $firstDateFormat = CRM_Utils_Date::customFormat($firstDate);
5380
5381 if ($secondDate) {
5382 if (!$appendTimeStamp) {
5383 $secondDate = substr($secondDate, 0, 8);
5384 }
5385 $secondDateFormat = CRM_Utils_Date::customFormat($secondDate);
5386 }
5387
5388 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
5389 if ($secondDate) {
5390 $this->_where[$grouping][] = "
5391 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5392 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5393 ";
5394 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5395 }
5396 else {
5397 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5398 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5399 }
5400 }
5401
5402 if ($name == $fieldName) {
5403 //In Get API, for operators other then '=' the $value is in array(op => value) format
5404 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
5405 $op = key($value);
5406 $value = $value[$op];
5407 }
5408
5409 $date = $format = NULL;
5410 if (strstr($op, 'IN')) {
5411 $format = array();
5412 foreach ($value as &$date) {
5413 $date = CRM_Utils_Date::processDate($date, NULL, FALSE, $dateFormat);
5414 if (!$appendTimeStamp) {
5415 $date = substr($date, 0, 8);
5416 }
5417 $format[] = CRM_Utils_Date::customFormat($date);
5418 }
5419 $date = "('" . implode("','", $value) . "')";
5420 $format = implode(', ', $format);
5421 }
5422 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5423 $date = CRM_Utils_Date::processDate($value, NULL, FALSE, $dateFormat);
5424 if (!$appendTimeStamp) {
5425 $date = substr($date, 0, 8);
5426 }
5427 $format = CRM_Utils_Date::customFormat($date);
5428 $date = "'$date'";
5429 }
5430
5431 if ($date) {
5432 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5433 }
5434 else {
5435 $this->_where[$grouping][] = self::buildClause("{$tableName}.{$dbFieldName}", $op);
5436 }
5437
5438 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
5439
5440 $op = CRM_Utils_Array::value($op, CRM_Core_SelectValues::getSearchBuilderOperators(), $op);
5441 $this->_qill[$grouping][] = "$fieldTitle $op $format";
5442 }
5443 }
5444
5445 /**
5446 * @param $values
5447 * @param string $tableName
5448 * @param string $fieldName
5449 * @param string $dbFieldName
5450 * @param $fieldTitle
5451 * @param null $options
5452 */
5453 public function numberRangeBuilder(
5454 &$values,
5455 $tableName, $fieldName,
5456 $dbFieldName, $fieldTitle,
5457 $options = NULL
5458 ) {
5459 list($name, $op, $value, $grouping, $wildcard) = $values;
5460
5461 if ($name == "{$fieldName}_low" ||
5462 $name == "{$fieldName}_high"
5463 ) {
5464 if (isset($this->_rangeCache[$fieldName])) {
5465 return;
5466 }
5467 $this->_rangeCache[$fieldName] = 1;
5468
5469 $secondOP = $secondPhrase = $secondValue = NULL;
5470
5471 if ($name == "{$fieldName}_low") {
5472 $firstOP = '>=';
5473 $firstPhrase = ts('greater than');
5474
5475 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5476 if (!empty($secondValues)) {
5477 $secondOP = '<=';
5478 $secondPhrase = ts('less than');
5479 $secondValue = $secondValues[2];
5480 }
5481 }
5482 else {
5483 $firstOP = '<=';
5484 $firstPhrase = ts('less than');
5485
5486 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5487 if (!empty($secondValues)) {
5488 $secondOP = '>=';
5489 $secondPhrase = ts('greater than');
5490 $secondValue = $secondValues[2];
5491 }
5492 }
5493
5494 if ($secondOP) {
5495 $this->_where[$grouping][] = "
5496 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5497 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5498 ";
5499 $displayValue = $options ? $options[$value] : $value;
5500 $secondDisplayValue = $options ? $options[$secondValue] : $secondValue;
5501
5502 $this->_qill[$grouping][]
5503 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5504 }
5505 else {
5506 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5507 $displayValue = $options ? $options[$value] : $value;
5508 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5509 }
5510 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
5511
5512 return;
5513 }
5514
5515 if ($name == $fieldName) {
5516 $op = '=';
5517 $phrase = '=';
5518
5519 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5520
5521 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
5522 $displayValue = $options ? $options[$value] : $value;
5523 $this->_qill[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5524 }
5525 }
5526
5527
5528 /**
5529 * @param $values
5530 * @param string $tableName
5531 * @param string $fieldName
5532 * @param string $dbFieldName
5533 * @param $fieldTitle
5534 * @param null $options
5535 */
5536 public function ageRangeQueryBuilder(
5537 &$values,
5538 $tableName, $fieldName,
5539 $dbFieldName, $fieldTitle,
5540 $options = NULL
5541 ) {
5542 list($name, $op, $value, $grouping, $wildcard) = $values;
5543
5544 $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
5545 $asofDate = NULL; // will be treated as current day
5546 if ($asofDateValues) {
5547 $asofDate = CRM_Utils_Date::processDate($asofDateValues[2]);
5548 $asofDateFormat = CRM_Utils_Date::customFormat(substr($asofDate, 0, 8));
5549 $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat;
5550 }
5551
5552 if ($name == "{$fieldName}_low" ||
5553 $name == "{$fieldName}_high"
5554 ) {
5555 if (isset($this->_rangeCache[$fieldName])) {
5556 return;
5557 }
5558 $this->_rangeCache[$fieldName] = 1;
5559
5560 $secondOP = $secondPhrase = $secondValue = NULL;
5561
5562 if ($name == "{$fieldName}_low") {
5563 $firstPhrase = ts('greater than or equal to');
5564 // NB: age > X means date of birth < Y
5565 $firstOP = '<=';
5566 $firstDate = self::calcDateFromAge($asofDate, $value, 'min');
5567
5568 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5569 if (!empty($secondValues)) {
5570 $secondOP = '>=';
5571 $secondPhrase = ts('less than or equal to');
5572 $secondValue = $secondValues[2];
5573 $secondDate = self::calcDateFromAge($asofDate, $secondValue, 'max');
5574 }
5575 }
5576 else {
5577 $firstOP = '>=';
5578 $firstPhrase = ts('less than or equal to');
5579 $firstDate = self::calcDateFromAge($asofDate, $value, 'max');
5580
5581 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5582 if (!empty($secondValues)) {
5583 $secondOP = '<=';
5584 $secondPhrase = ts('greater than or equal to');
5585 $secondValue = $secondValues[2];
5586 $secondDate = self::calcDateFromAge($asofDate, $secondValue, 'min');
5587 }
5588 }
5589
5590 if ($secondOP) {
5591 $this->_where[$grouping][] = "
5592 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5593 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5594 ";
5595 $displayValue = $options ? $options[$value] : $value;
5596 $secondDisplayValue = $options ? $options[$secondValue] : $secondValue;
5597
5598 $this->_qill[$grouping][]
5599 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5600 }
5601 else {
5602 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5603 $displayValue = $options ? $options[$value] : $value;
5604 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5605 }
5606 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
5607 return;
5608 }
5609 }
5610
5611 /**
5612 * Calculate date from age.
5613 *
5614 * @param string $asofDate
5615 * @param int $age
5616 * @param string $type
5617 *
5618 * @return string
5619 */
5620 public static function calcDateFromAge($asofDate, $age, $type) {
5621 $date = new DateTime($asofDate);
5622 if ($type == "min") {
5623 // minimum age is $age: dob <= date - age "235959"
5624 $date->sub(new DateInterval("P" . $age . "Y"));
5625 return $date->format('Ymd') . "235959";
5626 }
5627 else {
5628 // max age is $age: dob >= date - (age + 1y) + 1d "000000"
5629 $date->sub(new DateInterval("P" . ($age + 1) . "Y"))->add(new DateInterval("P1D"));
5630 return $date->format('Ymd') . "000000";
5631 }
5632 }
5633
5634 /**
5635 * Given the field name, operator, value & its data type
5636 * builds the where Clause for the query
5637 * used for handling 'IS NULL'/'IS NOT NULL' operators
5638 *
5639 * @param string $field
5640 * Fieldname.
5641 * @param string $op
5642 * Operator.
5643 * @param string $value
5644 * Value.
5645 * @param string $dataType
5646 * Data type of the field.
5647 *
5648 * @return string
5649 * Where clause for the query.
5650 */
5651 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5652 $op = trim($op);
5653 $clause = "$field $op";
5654
5655 switch ($op) {
5656 case 'IS NULL':
5657 case 'IS NOT NULL':
5658 return $clause;
5659
5660 case 'IS EMPTY':
5661 $clause = " (NULLIF($field, '') IS NULL) ";
5662 return $clause;
5663
5664 case 'IS NOT EMPTY':
5665 $clause = " (NULLIF($field, '') IS NOT NULL) ";
5666 return $clause;
5667
5668 case 'IN':
5669 case 'NOT IN':
5670 // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
5671 if (!empty($value) && (!is_array($value) || !array_key_exists($op, $value))) {
5672 $value = array($op => (array) $value);
5673 }
5674
5675 default:
5676 if (empty($dataType)) {
5677 $dataType = 'String';
5678 }
5679 if (is_array($value)) {
5680 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5681 // widely used and consistent across the codebase
5682 // adding this here won't accept the search functions which don't submit an array
5683 if (($queryString = CRM_Core_DAO::createSqlFilter($field, $value, $dataType)) != FALSE) {
5684
5685 return $queryString;
5686 }
5687
5688 // 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))
5689 // but we got only array(2,5) from the form.
5690 // We could get away with keeping this in 4.6 if we make it such that it throws an enotice in 4.7 so
5691 // people have to de-slopify it.
5692 if (!empty($value[0])) {
5693 if ($op != 'BETWEEN') {
5694 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReport;
5695 }
5696 if (($queryString = CRM_Core_DAO::createSqlFilter($field, array($op => $value), $dataType)) != FALSE) {
5697 return $queryString;
5698 }
5699 }
5700 else {
5701 $op = 'IN';
5702 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReportUsingOldFormat;
5703 if (($queryString = CRM_Core_DAO::createSqlFilter($field, array($op => array_keys($value)), $dataType)) != FALSE) {
5704 return $queryString;
5705 }
5706 }
5707 }
5708
5709 $value = CRM_Utils_Type::escape($value, $dataType);
5710 // if we don't have a dataType we should assume
5711 if ($dataType == 'String' || $dataType == 'Text') {
5712 $value = "'" . strtolower($value) . "'";
5713 }
5714 return "$clause $value";
5715 }
5716 }
5717
5718 /**
5719 * @param bool $reset
5720 *
5721 * @return array
5722 */
5723 public function openedSearchPanes($reset = FALSE) {
5724 if (!$reset || empty($this->_whereTables)) {
5725 return self::$_openedPanes;
5726 }
5727
5728 // pane name to table mapper
5729 $panesMapper = array(
5730 ts('Contributions') => 'civicrm_contribution',
5731 ts('Memberships') => 'civicrm_membership',
5732 ts('Events') => 'civicrm_participant',
5733 ts('Relationships') => 'civicrm_relationship',
5734 ts('Activities') => 'civicrm_activity',
5735 ts('Pledges') => 'civicrm_pledge',
5736 ts('Cases') => 'civicrm_case',
5737 ts('Grants') => 'civicrm_grant',
5738 ts('Address Fields') => 'civicrm_address',
5739 ts('Notes') => 'civicrm_note',
5740 ts('Change Log') => 'civicrm_log',
5741 ts('Mailings') => 'civicrm_mailing',
5742 );
5743 CRM_Contact_BAO_Query_Hook::singleton()->getPanesMapper($panesMapper);
5744
5745 foreach (array_keys($this->_whereTables) as $table) {
5746 if ($panName = array_search($table, $panesMapper)) {
5747 self::$_openedPanes[$panName] = TRUE;
5748 }
5749 }
5750
5751 return self::$_openedPanes;
5752 }
5753
5754 /**
5755 * @param $operator
5756 */
5757 public function setOperator($operator) {
5758 $validOperators = array('AND', 'OR');
5759 if (!in_array($operator, $validOperators)) {
5760 $operator = 'AND';
5761 }
5762 $this->_operator = $operator;
5763 }
5764
5765 /**
5766 * @return string
5767 */
5768 public function getOperator() {
5769 return $this->_operator;
5770 }
5771
5772 /**
5773 * @param $from
5774 * @param $where
5775 * @param $having
5776 */
5777 public function filterRelatedContacts(&$from, &$where, &$having) {
5778 static $_rTypeProcessed = NULL;
5779 static $_rTypeFrom = NULL;
5780 static $_rTypeWhere = NULL;
5781
5782 if (!$_rTypeProcessed) {
5783 $_rTypeProcessed = TRUE;
5784
5785 // create temp table with contact ids
5786 $tableName = CRM_Core_DAO::createTempTableName('civicrm_transform', TRUE);
5787 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5788 CRM_Core_DAO::executeQuery($sql);
5789
5790 $sql = "
5791 REPLACE INTO $tableName ( contact_id )
5792 SELECT contact_a.id
5793 $from
5794 $where
5795 $having
5796 ";
5797 CRM_Core_DAO::executeQuery($sql);
5798
5799 $qillMessage = ts('Contacts with a Relationship Type of: ');
5800 $rTypes = CRM_Core_PseudoConstant::relationshipType();
5801
5802 if (is_numeric($this->_displayRelationshipType)) {
5803 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType]['label_a_b'];
5804 $_rTypeFrom = "
5805 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5806 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5807 ";
5808 $_rTypeWhere = "
5809 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5810 AND displayRelType.is_active = 1
5811 ";
5812 }
5813 else {
5814 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType);
5815 if ($dirOne == 'a') {
5816 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5817 $_rTypeFrom .= "
5818 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5819 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5820 ";
5821 }
5822 else {
5823 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5824 $_rTypeFrom .= "
5825 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5826 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5827 ";
5828 }
5829 $_rTypeWhere = "
5830 WHERE displayRelType.relationship_type_id = $relType
5831 AND displayRelType.is_active = 1
5832 ";
5833 }
5834 $this->_qill[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5835 }
5836
5837 if (!empty($this->_permissionWhereClause)) {
5838 $_rTypeWhere .= "AND $this->_permissionWhereClause";
5839 }
5840
5841 if (strpos($from, $_rTypeFrom) === FALSE) {
5842 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5843 // this happens when we have an event_type in the quert (CRM-7969)
5844 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5845 $from .= $_rTypeFrom;
5846 $where = $_rTypeWhere;
5847 }
5848
5849 $having = NULL;
5850 }
5851
5852 /**
5853 * See CRM-19811 for why this is database hurty without apparent benefit.
5854 *
5855 * @param $op
5856 *
5857 * @return bool
5858 */
5859 public static function caseImportant($op) {
5860 return
5861 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ? FALSE : TRUE;
5862 }
5863
5864 /**
5865 * @param $returnProperties
5866 * @param $prefix
5867 *
5868 * @return bool
5869 */
5870 public static function componentPresent(&$returnProperties, $prefix) {
5871 foreach ($returnProperties as $name => $dontCare) {
5872 if (substr($name, 0, strlen($prefix)) == $prefix) {
5873 return TRUE;
5874 }
5875 }
5876 return FALSE;
5877 }
5878
5879 /**
5880 * Builds the necessary structures for all fields that are similar to option value look-ups.
5881 *
5882 * @param string $name
5883 * the name of the field.
5884 * @param string $op
5885 * the sql operator, this function should handle ALL SQL operators.
5886 * @param string $value
5887 * depends on the operator and who's calling the query builder.
5888 * @param int $grouping
5889 * the index where to place the where clause.
5890 * @param string $daoName
5891 * DAO Name.
5892 * @param array $field
5893 * an array that contains various properties of the field identified by $name.
5894 * @param string $label
5895 * The label for this field element.
5896 * @param string $dataType
5897 * The data type for this element.
5898 * @param bool $useIDsOnly
5899 */
5900 public function optionValueQuery(
5901 $name,
5902 $op,
5903 $value,
5904 $grouping,
5905 $daoName = NULL,
5906 $field,
5907 $label,
5908 $dataType = 'String',
5909 $useIDsOnly = FALSE
5910 ) {
5911
5912 $pseudoFields = array(
5913 'email_greeting',
5914 'postal_greeting',
5915 'addressee',
5916 'gender_id',
5917 'prefix_id',
5918 'suffix_id',
5919 'communication_style_id',
5920 );
5921
5922 if ($useIDsOnly) {
5923 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5924 if ($tableName == 'civicrm_contact') {
5925 $wc = "contact_a.$fieldName";
5926 }
5927 else {
5928 $wc = "$tableName.id";
5929 }
5930 }
5931 else {
5932 // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
5933 $wc = self::caseImportant($op) ? "LOWER({$field['where']})" : "{$field['where']}";
5934 }
5935 if (in_array($name, $pseudoFields)) {
5936 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5937 $wc = "contact_a.{$name}_id";
5938 }
5939 $dataType = 'Positive';
5940 $value = (!$value) ? 0 : $value;
5941 }
5942 if ($name == "world_region") {
5943 $field['name'] = $name;
5944 }
5945
5946 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue($daoName, $field['name'], $value, $op);
5947 $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillop, 3 => $qillVal));
5948 $this->_where[$grouping][] = self::buildClause($wc, $op, $value, $dataType);
5949 }
5950
5951 /**
5952 * Check and explode a user defined numeric string into an array
5953 * this was the protocol used by search builder in the old old days before we had
5954 * super nice js widgets to do the hard work
5955 *
5956 * @param string $string
5957 * @param string $dataType
5958 * The dataType we should check for the values, default integer.
5959 *
5960 * @return bool|array
5961 * false if string does not match the pattern
5962 * array of numeric values if string does match the pattern
5963 */
5964 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5965 $string = trim($string);
5966 if (substr($string, 0, 1) != '(' || substr($string, -1, 1) != ')') {
5967 Return FALSE;
5968 }
5969
5970 $string = substr($string, 1, -1);
5971 $values = explode(',', $string);
5972 if (empty($values)) {
5973 return FALSE;
5974 }
5975
5976 $returnValues = array();
5977 foreach ($values as $v) {
5978 if ($dataType == 'Integer' && !is_numeric($v)) {
5979 return FALSE;
5980 }
5981 elseif ($dataType == 'String' && !is_string($v)) {
5982 return FALSE;
5983 }
5984 $returnValues[] = trim($v);
5985 }
5986
5987 if (empty($returnValues)) {
5988 return FALSE;
5989 }
5990
5991 return $returnValues;
5992 }
5993
5994 /**
5995 * Convert the pseudo constants id's to their names
5996 *
5997 * @param CRM_Core_DAO $dao
5998 * @param bool $return
5999 * @param bool $usedForAPI
6000 *
6001 * @return array|NULL
6002 */
6003 public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) {
6004 if (empty($this->_pseudoConstantsSelect)) {
6005 return NULL;
6006 }
6007 $values = array();
6008 foreach ($this->_pseudoConstantsSelect as $key => $value) {
6009 if (!empty($this->_pseudoConstantsSelect[$key]['sorting'])) {
6010 continue;
6011 }
6012
6013 if (is_object($dao) && property_exists($dao, $value['idCol'])) {
6014 $val = $dao->{$value['idCol']};
6015 if ($key == 'groups') {
6016 $dao->groups = $this->convertGroupIDStringToLabelString($dao, $val);
6017 continue;
6018 }
6019
6020 if (CRM_Utils_System::isNull($val)) {
6021 $dao->$key = NULL;
6022 }
6023 elseif (!empty($value['pseudoconstant'])) {
6024 // If pseudoconstant is set that is kind of defacto for 'we have a bit more info about this'
6025 // and we can use the metadata to figure it out.
6026 // ideally this bit of IF will absorb & replace all the rest in time as we move to
6027 // more metadata based choices.
6028 if (strpos($val, CRM_Core_DAO::VALUE_SEPARATOR) !== FALSE) {
6029 $dbValues = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($val, CRM_Core_DAO::VALUE_SEPARATOR));
6030 foreach ($dbValues as $pseudoValue) {
6031 $convertedValues[] = CRM_Core_PseudoConstant::getLabel($value['bao'], $value['idCol'], $pseudoValue);
6032 }
6033
6034 $dao->$key = ($usedForAPI) ? $convertedValues : implode(', ', $convertedValues);
6035 $realFieldName = CRM_Utils_Array::value('field_name', $this->_pseudoConstantsSelect[$key]);
6036 if ($usedForAPI && $realFieldName) {
6037 // normally we would see 2 fields returned for pseudoConstants. An exception is
6038 // preferred_communication_method where there is no id-variant.
6039 // For the api we prioritise getting the real data returned.
6040 // over the resolved version
6041 $dao->$realFieldName = $dbValues;
6042 }
6043
6044 }
6045 else {
6046 // This is basically the same as the default but since we have the bao we can use
6047 // a cached function.
6048 $dao->$key = CRM_Core_PseudoConstant::getLabel($value['bao'], $value['idCol'], $val);
6049 }
6050 }
6051 elseif ($baoName = CRM_Utils_Array::value('bao', $value, NULL)) {
6052 //preserve id value
6053 $idColumn = "{$key}_id";
6054 $dao->$idColumn = $val;
6055
6056 if ($key == 'state_province_name') {
6057 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant::stateProvince($val);
6058 }
6059 else {
6060 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant::getLabel($baoName, $value['pseudoField'], $val);
6061 }
6062 }
6063 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
6064 $dao->$key = CRM_Core_PseudoConstant::stateProvinceAbbreviation($val);
6065 }
6066 // @todo handle this in the section above for pseudoconstants.
6067 elseif (in_array($value['pseudoField'], array('participant_role_id', 'participant_role'))) {
6068 // @todo define bao on this & merge into the above condition.
6069 $viewValues = explode(CRM_Core_DAO::VALUE_SEPARATOR, $val);
6070
6071 if ($value['pseudoField'] == 'participant_role') {
6072 $pseudoOptions = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'role_id');
6073 foreach ($viewValues as $k => $v) {
6074 $viewValues[$k] = $pseudoOptions[$v];
6075 }
6076 }
6077 $dao->$key = ($usedForAPI && count($viewValues) > 1) ? $viewValues : implode(', ', $viewValues);
6078 }
6079 else {
6080 $labels = CRM_Core_OptionGroup::values($value['pseudoField']);
6081 $dao->$key = $labels[$val];
6082 }
6083
6084 // return converted values in array format
6085 if ($return) {
6086 if (strpos($key, '-') !== FALSE) {
6087 $keyVal = explode('-', $key);
6088 $current = &$values;
6089 $lastElement = array_pop($keyVal);
6090 foreach ($keyVal as $v) {
6091 if (!array_key_exists($v, $current)) {
6092 $current[$v] = array();
6093 }
6094 $current = &$current[$v];
6095 }
6096 $current[$lastElement] = $dao->$key;
6097 }
6098 else {
6099 $values[$key] = $dao->$key;
6100 }
6101 }
6102 }
6103 }
6104 if (!$usedForAPI) {
6105 foreach (array(
6106 'gender_id' => 'gender',
6107 'prefix_id' => 'individual_prefix',
6108 'suffix_id' => 'individual_suffix',
6109 'communication_style_id' => 'communication_style',
6110 ) as $realField => $labelField) {
6111 // This is a temporary routine for handling these fields while
6112 // we figure out how to handled them based on metadata in
6113 /// export and search builder. CRM-19815, CRM-19830.
6114 if (isset($dao->$realField) && is_numeric($dao->$realField) && isset($dao->$labelField)) {
6115 $dao->$realField = $dao->$labelField;
6116 }
6117 }
6118 }
6119 return $values;
6120 }
6121
6122 /**
6123 * Include pseudo fields LEFT JOIN.
6124 * @param string|array $sort can be a object or string
6125 *
6126 * @return array|NULL
6127 */
6128 public function includePseudoFieldsJoin($sort) {
6129 if (!$sort || empty($this->_pseudoConstantsSelect)) {
6130 return NULL;
6131 }
6132 $sort = is_string($sort) ? $sort : $sort->orderBy();
6133 $present = array();
6134
6135 foreach ($this->_pseudoConstantsSelect as $name => $value) {
6136 if (!empty($value['table'])) {
6137 $regex = "/({$value['table']}\.|{$name})/";
6138 if (preg_match($regex, $sort)) {
6139 $this->_elemnt[$value['element']] = 1;
6140 $this->_select[$value['element']] = $value['select'];
6141 $this->_pseudoConstantsSelect[$name]['sorting'] = 1;
6142 $present[$value['table']] = $value['join'];
6143 }
6144 }
6145 }
6146 $presentSimpleFrom = $present;
6147
6148 if (array_key_exists('civicrm_worldregion', $this->_whereTables) &&
6149 array_key_exists('civicrm_country', $presentSimpleFrom)
6150 ) {
6151 unset($presentSimpleFrom['civicrm_country']);
6152 }
6153 if (array_key_exists('civicrm_worldregion', $this->_tables) &&
6154 array_key_exists('civicrm_country', $present)
6155 ) {
6156 unset($present['civicrm_country']);
6157 }
6158
6159 $presentClause = $presentSimpleFromClause = NULL;
6160 if (!empty($present)) {
6161 $presentClause = implode(' ', $present);
6162 }
6163 if (!empty($presentSimpleFrom)) {
6164 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
6165 }
6166
6167 $this->_fromClause = $this->_fromClause . $presentClause;
6168 $this->_simpleFromClause = $this->_simpleFromClause . $presentSimpleFromClause;
6169
6170 return array($presentClause, $presentSimpleFromClause);
6171 }
6172
6173 /**
6174 * Build qill for field.
6175 *
6176 * Qill refers to the query detail visible on the UI.
6177 *
6178 * @param string $daoName
6179 * @param string $fieldName
6180 * @param mixed $fieldValue
6181 * @param string $op
6182 * @param array $pseudoExtraParam
6183 * @param int $type
6184 * Type of the field per CRM_Utils_Type
6185 *
6186 * @return array
6187 */
6188 public static function buildQillForFieldValue(
6189 $daoName,
6190 $fieldName,
6191 $fieldValue,
6192 $op,
6193 $pseudoExtraParam = array(),
6194 $type = CRM_Utils_Type::T_STRING
6195 ) {
6196 $qillOperators = CRM_Core_SelectValues::getSearchBuilderOperators();
6197
6198 //API usually have fieldValue format as array(operator => array(values)),
6199 //so we need to separate operator out of fieldValue param
6200 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
6201 $op = key($fieldValue);
6202 $fieldValue = $fieldValue[$op];
6203 }
6204
6205 // if Operator chosen is NULL/EMPTY then
6206 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
6207 return array(CRM_Utils_Array::value($op, $qillOperators, $op), '');
6208 }
6209
6210 if ($fieldName == 'activity_type_id') {
6211 $pseudoOptions = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
6212 }
6213 elseif ($fieldName == 'country_id') {
6214 $pseudoOptions = CRM_Core_PseudoConstant::country();
6215 }
6216 elseif ($fieldName == 'county_id') {
6217 $pseudoOptions = CRM_Core_PseudoConstant::county();
6218 }
6219 elseif ($fieldName == 'world_region') {
6220 $pseudoOptions = CRM_Core_PseudoConstant::worldRegion();
6221 }
6222 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
6223 $checkPermission = CRM_Utils_Array::value('check_permission', $pseudoExtraParam, TRUE);
6224 $pseudoOptions = CRM_Event_BAO_Event::getEvents(0, $fieldValue, TRUE, $checkPermission, TRUE);
6225 }
6226 elseif ($fieldName == 'contribution_product_id') {
6227 $pseudoOptions = CRM_Contribute_PseudoConstant::products();
6228 }
6229 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
6230 $pseudoOptions = CRM_Core_PseudoConstant::group();
6231 }
6232 elseif ($daoName == 'CRM_Batch_BAO_EntityBatch' && $fieldName == 'batch_id') {
6233 $pseudoOptions = CRM_Contribute_PseudoConstant::batch();
6234 }
6235 elseif ($daoName) {
6236 $pseudoOptions = CRM_Core_PseudoConstant::get($daoName, $fieldName, $pseudoExtraParam);
6237 }
6238
6239 if (is_array($fieldValue)) {
6240 $qillString = array();
6241 if (!empty($pseudoOptions)) {
6242 foreach ((array) $fieldValue as $val) {
6243 $qillString[] = CRM_Utils_Array::value($val, $pseudoOptions, $val);
6244 }
6245 $fieldValue = implode(', ', $qillString);
6246 }
6247 else {
6248 if ($type == CRM_Utils_Type::T_DATE) {
6249 foreach ($fieldValue as $index => $value) {
6250 $fieldValue[$index] = CRM_Utils_Date::customFormat($value);
6251 }
6252 }
6253 $separator = ', ';
6254 // @todo - this is a bit specific (one operator).
6255 // However it is covered by a unit test so can be altered later with
6256 // some confidence.
6257 if ($op == 'BETWEEN') {
6258 $separator = ' AND ';
6259 }
6260 $fieldValue = implode($separator, $fieldValue);
6261 }
6262 }
6263 elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) {
6264 $fieldValue = $pseudoOptions[$fieldValue];
6265 }
6266 elseif ($type === CRM_Utils_Type::T_DATE) {
6267 $fieldValue = CRM_Utils_Date::customFormat($fieldValue);
6268 }
6269
6270 return array(CRM_Utils_Array::value($op, $qillOperators, $op), $fieldValue);
6271 }
6272
6273 /**
6274 * Alter value to reflect wildcard settings.
6275 *
6276 * The form will have tried to guess whether this is a good field to wildcard but there is
6277 * also a site-wide setting that specifies whether it is OK to append the wild card to the beginning
6278 * or only the end of the string
6279 *
6280 * @param bool $wildcard
6281 * This is a bool made on an assessment 'elsewhere' on whether this is a good field to wildcard.
6282 * @param string $op
6283 * Generally '=' or 'LIKE'.
6284 * @param string $value
6285 * The search string.
6286 *
6287 * @return string
6288 */
6289 public static function getWildCardedValue($wildcard, $op, $value) {
6290 if ($wildcard && $op == 'LIKE') {
6291 if (CRM_Core_Config::singleton()->includeWildCardInName && (substr($value, 0, 1) != '%')) {
6292 return "%$value%";
6293 }
6294 else {
6295 return "$value%";
6296 }
6297 }
6298 else {
6299 return "$value";
6300 }
6301 }
6302
6303 /**
6304 * Process special fields of Search Form in OK (Operator in Key) format
6305 *
6306 * @param array $formValues
6307 * @param array $specialFields
6308 * Special params to be processed
6309 * @param array $changeNames
6310 * Array of fields whose name should be changed
6311 */
6312 public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = array()) {
6313 // Array of special fields whose value are considered only for NULL or EMPTY operators
6314 $nullableFields = array('contribution_batch_id');
6315
6316 foreach ($specialFields as $element) {
6317 $value = CRM_Utils_Array::value($element, $formValues);
6318 if ($value) {
6319 if (is_array($value)) {
6320 if (in_array($element, array_keys($changeNames))) {
6321 unset($formValues[$element]);
6322 $element = $changeNames[$element];
6323 }
6324 $formValues[$element] = array('IN' => $value);
6325 }
6326 elseif (in_array($value, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
6327 $formValues[$element] = array($value => 1);
6328 }
6329 elseif (!in_array($element, $nullableFields)) {
6330 // if wildcard is already present return searchString as it is OR append and/or prepend with wildcard
6331 $isWilcard = strstr($value, '%') ? FALSE : CRM_Core_Config::singleton()->includeWildCardInName;
6332 $formValues[$element] = array('LIKE' => self::getWildCardedValue($isWilcard, 'LIKE', $value));
6333 }
6334 }
6335 }
6336 }
6337
6338 /**
6339 * Parse and assimilate the various sort options.
6340 *
6341 * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`,
6342 * `email`), the related table may be joined automatically.
6343 *
6344 * At time of writing, this code is deeply flawed and should be rewritten. For the moment,
6345 * it's been extracted to a standalone function.
6346 *
6347 * @param string|CRM_Utils_Sort $sort
6348 * The order by string.
6349 * @param bool $sortByChar
6350 * If true returns the distinct array of first characters for search results.
6351 * @param null $sortOrder
6352 * Who knows? Hu knows. He who knows Hu knows who.
6353 * @param string $additionalFromClause
6354 * Should be clause with proper joins, effective to reduce where clause load.
6355 * @return array
6356 * list(string $orderByClause, string $additionalFromClause).
6357 */
6358 protected function prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause) {
6359 $order = NULL;
6360 $orderByArray = array();
6361 $config = CRM_Core_Config::singleton();
6362 if ($config->includeOrderByClause ||
6363 isset($this->_distinctComponentClause)
6364 ) {
6365 if ($sort) {
6366 if (is_string($sort)) {
6367 $orderBy = $sort;
6368 }
6369 else {
6370 $orderBy = trim($sort->orderBy());
6371 }
6372 // Deliberately remove the backticks again, as they mess up the evil
6373 // string munging below. This balanced by re-escaping before use.
6374 $orderBy = str_replace('`', '', $orderBy);
6375
6376 if (!empty($orderBy)) {
6377 // this is special case while searching for
6378 // change log CRM-1718
6379 if (preg_match('/sort_name/i', $orderBy)) {
6380 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
6381 }
6382
6383 $order = " ORDER BY $orderBy";
6384
6385 if ($sortOrder) {
6386 $order .= " $sortOrder";
6387 }
6388
6389 // always add contact_a.id to the ORDER clause
6390 // so the order is deterministic
6391 if (strpos('contact_a.id', $order) === FALSE) {
6392 $order .= ", contact_a.id";
6393 }
6394 }
6395 }
6396 elseif ($sortByChar) {
6397 $orderByArray = array("UPPER(LEFT(contact_a.sort_name, 1)) asc");
6398 }
6399 else {
6400 $order = " ORDER BY contact_a.sort_name ASC, contact_a.id";
6401 }
6402 }
6403 if (!$order && empty($orderByArray)) {
6404 return array($order, $additionalFromClause);
6405 }
6406 // Remove this here & add it at the end for simplicity.
6407 $order = trim(str_replace('ORDER BY', '', $order));
6408
6409 // hack for order clause
6410 if (!empty($orderByArray)) {
6411 $order = implode(', ', $orderByArray);
6412 }
6413 else {
6414 $orderByArray = explode(',', $order);
6415 }
6416 foreach ($orderByArray as $orderByClause) {
6417 $orderByClauseParts = explode(' ', trim($orderByClause));
6418 $field = $orderByClauseParts[0];
6419 $direction = isset($orderByClauseParts[1]) ? $orderByClauseParts[1] : 'asc';
6420
6421 switch ($field) {
6422 case 'city':
6423 case 'postal_code':
6424 $this->_tables["civicrm_address"] = $this->_whereTables["civicrm_address"] = 1;
6425 $order = str_replace($field, "civicrm_address.{$field}", $order);
6426 break;
6427
6428 case 'country':
6429 case 'state_province':
6430 $this->_tables["civicrm_{$field}"] = $this->_whereTables["civicrm_{$field}"] = 1;
6431 if (is_array($this->_returnProperties) && empty($this->_returnProperties)) {
6432 $additionalFromClause .= " LEFT JOIN civicrm_{$field} ON civicrm_{$field}.id = civicrm_address.{$field}_id";
6433 }
6434 $order = str_replace($field, "civicrm_{$field}.name", $order);
6435 break;
6436
6437 case 'email':
6438 $this->_tables["civicrm_email"] = $this->_whereTables["civicrm_email"] = 1;
6439 $order = str_replace($field, "civicrm_email.{$field}", $order);
6440 break;
6441
6442 default:
6443 $cfID = CRM_Core_BAO_CustomField::getKeyID($field);
6444 // add to cfIDs array if not present
6445 if (!empty($cfID) && !array_key_exists($cfID, $this->_cfIDs)) {
6446 $this->_cfIDs[$cfID] = array();
6447 $this->_customQuery = new CRM_Core_BAO_CustomQuery($this->_cfIDs, TRUE, $this->_locationSpecificCustomFields);
6448 $this->_customQuery->query();
6449 $this->_select = array_merge($this->_select, $this->_customQuery->_select);
6450 $this->_tables = array_merge($this->_tables, $this->_customQuery->_tables);
6451 }
6452 foreach ($this->_pseudoConstantsSelect as $key => $pseudoConstantMetadata) {
6453 // By replacing the join to the option value table with the mysql construct
6454 // ORDER BY field('contribution_status_id', 2,1,4)
6455 // we can remove a join. In the case of the option value join it is
6456 /// a join known to cause slow queries.
6457 // @todo cover other pseudoconstant types. Limited to option group ones in the
6458 // first instance for scope reasons. They require slightly different handling as the column (label)
6459 // is not declared for them.
6460 // @todo so far only integer fields are being handled. If we add string fields we need to look at
6461 // escaping.
6462 if (isset($pseudoConstantMetadata['pseudoconstant'])
6463 && isset($pseudoConstantMetadata['pseudoconstant']['optionGroupName'])
6464 && $field === CRM_Utils_Array::value('optionGroupName', $pseudoConstantMetadata['pseudoconstant'])
6465 ) {
6466 $sortedOptions = $pseudoConstantMetadata['bao']::buildOptions($pseudoConstantMetadata['pseudoField'], NULL, array(
6467 'orderColumn' => 'label',
6468 ));
6469 $order = str_replace("$field $direction", "field({$pseudoConstantMetadata['pseudoField']}," . implode(',', array_keys($sortedOptions)) . ") $direction", $order);
6470 }
6471 //CRM-12565 add "`" around $field if it is a pseudo constant
6472 // This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
6473 if (!empty($pseudoConstantMetadata['element']) && $pseudoConstantMetadata['element'] == $field) {
6474 $order = str_replace($field, "`{$field}`", $order);
6475 }
6476 }
6477 }
6478 }
6479
6480 $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode);
6481 $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode);
6482
6483 // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
6484 // clause. But this magic helper which forgivingly reescapes ORDER BY.
6485 // Note: $sortByChar implies that $order was hard-coded/trusted, so it can do funky things.
6486 if ($sortByChar) {
6487 return array(' ORDER BY ' . $order, $additionalFromClause);
6488 }
6489 if ($order) {
6490 $order = CRM_Utils_Type::escape($order, 'MysqlOrderBy');
6491 return array(' ORDER BY ' . $order, $additionalFromClause);
6492 }
6493 }
6494
6495 /**
6496 * Convert a string of group IDs to a string of group labels.
6497 *
6498 * The original string may include duplicates and groups the user does not have
6499 * permission to see.
6500 *
6501 * @param CRM_Core_DAO $dao
6502 * @param string $val
6503 *
6504 * @return string
6505 */
6506 public function convertGroupIDStringToLabelString(&$dao, $val) {
6507 $groupIDs = explode(',', $val);
6508 // Note that groups that the user does not have permission to will be excluded (good).
6509 $groups = array_intersect_key(CRM_Core_PseudoConstant::group(), array_flip($groupIDs));
6510 return implode(', ', $groups);
6511
6512 }
6513
6514 /**
6515 * Set the qill and where properties for a field.
6516 *
6517 * This function is intended as a short-term function to encourage refactoring
6518 * & re-use - but really we should just have less special-casing.
6519 *
6520 * @param string $name
6521 * @param string $op
6522 * @param string|array $value
6523 * @param string $grouping
6524 * @param string $field
6525 */
6526 public function setQillAndWhere($name, $op, $value, $grouping, $field) {
6527 $this->_where[$grouping][] = self::buildClause("contact_a.{$name}", $op, $value);
6528 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $name, $value, $op);
6529 $this->_qill[$grouping][] = ts("%1 %2 %3", array(
6530 1 => $field['title'],
6531 2 => $qillop,
6532 3 => $qillVal,
6533 ));
6534 }
6535
6536 /**
6537 * Has the pseudoconstant of the field been requested.
6538 *
6539 * For example if the field is payment_instrument_id then it
6540 * has been requested if either payment_instrument_id or payment_instrument
6541 * have been requested. Payment_instrument is the option groun name field value.
6542 *
6543 * @param array $field
6544 * @param string $fieldName
6545 * The unique name of the field - ie. the one it will be aliased to in the query.
6546 *
6547 * @return bool
6548 */
6549 private function pseudoConstantNameIsInReturnProperties($field, $fieldName = NULL) {
6550 if (!isset($field['pseudoconstant']['optionGroupName'])) {
6551 return FALSE;
6552 }
6553
6554 if (CRM_Utils_Array::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties)) {
6555 return TRUE;
6556 }
6557 if (CRM_Utils_Array::value($fieldName, $this->_returnProperties)) {
6558 return TRUE;
6559 }
6560 // Is this still required - the above goes off the unique name. Test with things like
6561 // communication_prefferences & prefix_id.
6562 if (CRM_Utils_Array::value($field['name'], $this->_returnProperties)) {
6563 return TRUE;
6564 }
6565 return FALSE;
6566 }
6567
6568 /**
6569 * Get Select Clause.
6570 *
6571 * @return string
6572 */
6573 public function getSelect() {
6574 $select = "SELECT ";
6575 if (isset($this->_distinctComponentClause)) {
6576 $select .= "{$this->_distinctComponentClause}, ";
6577 }
6578 $select .= implode(', ', $this->_select);
6579 return $select;
6580 }
6581
6582 }