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