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