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