CRM-17022 fix - Bug introduced in 4.6.6 breaks Grant Search
[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 (!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO::acceptedSQLOperators(), TRUE))
1606 ) {
1607 $result = array($id, 'IN', $values, 0, $wildcard);
1608 }
1609 else {
1610 $result = array($id, '=', $values, 0, $wildcard);
1611 }
1612
1613 return $result;
1614 }
1615
1616 /**
1617 * @param $values
1618 */
1619 public function whereClauseSingle(&$values) {
1620 // do not process custom fields or prefixed contact ids or component params
1621 if (CRM_Core_BAO_CustomField::getKeyID($values[0]) ||
1622 (substr($values[0], 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) ||
1623 (substr($values[0], 0, 13) == 'contribution_') ||
1624 (substr($values[0], 0, 6) == 'event_') ||
1625 (substr($values[0], 0, 12) == 'participant_') ||
1626 (substr($values[0], 0, 7) == 'member_') ||
1627 (substr($values[0], 0, 6) == 'grant_') ||
1628 (substr($values[0], 0, 7) == 'pledge_') ||
1629 (substr($values[0], 0, 5) == 'case_') ||
1630 (substr($values[0], 0, 10) == 'financial_') ||
1631 (substr($values[0], 0, 8) == 'payment_') ||
1632 (substr($values[0], 0, 11) == 'membership_')
1633 ) {
1634 return;
1635 }
1636
1637 // skip for hook injected fields / params
1638 $extFields = CRM_Contact_BAO_Query_Hook::singleton()->getFields();
1639 if (array_key_exists($values[0], $extFields)) {
1640 return;
1641 }
1642
1643 switch ($values[0]) {
1644 case 'deleted_contacts':
1645 $this->deletedContacts($values);
1646 return;
1647
1648 case 'contact_type':
1649 $this->contactType($values);
1650 return;
1651
1652 case 'contact_sub_type':
1653 $this->contactSubType($values);
1654 return;
1655
1656 case 'group':
1657 $this->group($values);
1658 return;
1659
1660 case 'group_type':
1661 // so we resolve this into a list of groups & proceed as if they had been
1662 // handed in
1663 list($name, $op, $value, $grouping, $wildcard) = $values;
1664 $values[0] = 'group';
1665 $values[1] = 'IN';
1666 $this->_paramLookup['group'][0][0] = 'group';
1667 $this->_paramLookup['group'][0][1] = 'IN';
1668 $this->_paramLookup['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1669 $this->group($values);
1670 return;
1671
1672 // case tag comes from find contacts
1673 case 'tag_search':
1674 $this->tagSearch($values);
1675 return;
1676
1677 case 'tag':
1678 case 'contact_tags':
1679 $this->tag($values);
1680 return;
1681
1682 case 'note':
1683 case 'note_body':
1684 case 'note_subject':
1685 $this->notes($values);
1686 return;
1687
1688 case 'uf_user':
1689 $this->ufUser($values);
1690 return;
1691
1692 case 'sort_name':
1693 case 'display_name':
1694 $this->sortName($values);
1695 return;
1696
1697 case 'addressee':
1698 case 'postal_greeting':
1699 case 'email_greeting':
1700 $this->greetings($values);
1701 return;
1702
1703 case 'email':
1704 $this->email($values);
1705 return;
1706
1707 case 'phone_numeric':
1708 $this->phone_numeric($values);
1709 return;
1710
1711 case 'phone_phone_type_id':
1712 case 'phone_location_type_id':
1713 $this->phone_option_group($values);
1714 return;
1715
1716 case 'street_address':
1717 $this->street_address($values);
1718 return;
1719
1720 case 'street_number':
1721 $this->street_number($values);
1722 return;
1723
1724 case 'sortByCharacter':
1725 $this->sortByCharacter($values);
1726 return;
1727
1728 case 'location_type':
1729 $this->locationType($values);
1730 return;
1731
1732 case 'county':
1733 $this->county($values);
1734 return;
1735
1736 case 'state_province':
1737 $this->stateProvince($values);
1738 return;
1739
1740 case 'country':
1741 $this->country($values, FALSE);
1742 return;
1743
1744 case 'postal_code':
1745 case 'postal_code_low':
1746 case 'postal_code_high':
1747 $this->postalCode($values);
1748 return;
1749
1750 case 'activity_date':
1751 case 'activity_date_low':
1752 case 'activity_date_high':
1753 case 'activity_role':
1754 case 'activity_status_id':
1755 case 'activity_status':
1756 case 'followup_parent_id':
1757 case 'parent_id':
1758 case 'source_contact_id':
1759 case 'activity_subject':
1760 case 'test_activities':
1761 case 'activity_type_id':
1762 case 'activity_type':
1763 case 'activity_survey_id':
1764 case 'activity_tags':
1765 case 'activity_taglist':
1766 case 'activity_test':
1767 case 'activity_campaign_id':
1768 case 'activity_engagement_level':
1769 case 'activity_id':
1770 case 'activity_result':
1771 case 'source_contact':
1772 CRM_Activity_BAO_Query::whereClauseSingle($values, $this);
1773 return;
1774
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 'log_date_low':
1783 case 'log_date_high':
1784 $this->modifiedDates($values);
1785 return;
1786
1787 case 'changed_by':
1788 $this->changeLog($values);
1789 return;
1790
1791 case 'do_not_phone':
1792 case 'do_not_email':
1793 case 'do_not_mail':
1794 case 'do_not_sms':
1795 case 'do_not_trade':
1796 case 'is_opt_out':
1797 $this->privacy($values);
1798 return;
1799
1800 case 'privacy_options':
1801 $this->privacyOptions($values);
1802 return;
1803
1804 case 'privacy_operator':
1805 case 'privacy_toggle':
1806 // these are handled by privacy options
1807 return;
1808
1809 case 'preferred_communication_method':
1810 $this->preferredCommunication($values);
1811 return;
1812
1813 case 'relation_type_id':
1814 case 'relation_start_date_high':
1815 case 'relation_start_date_low':
1816 case 'relation_end_date_high':
1817 case 'relation_end_date_low':
1818 case 'relation_target_name':
1819 case 'relation_status':
1820 case 'relation_date_low':
1821 case 'relation_date_high':
1822 $this->relationship($values);
1823 $this->_relationshipValuesAdded = TRUE;
1824 return;
1825
1826 case 'task_status_id':
1827 $this->task($values);
1828 return;
1829
1830 case 'task_id':
1831 // since this case is handled with the above
1832 return;
1833
1834 case 'prox_distance':
1835 CRM_Contact_BAO_ProximityQuery::process($this, $values);
1836 return;
1837
1838 case 'prox_street_address':
1839 case 'prox_city':
1840 case 'prox_postal_code':
1841 case 'prox_state_province_id':
1842 case 'prox_country_id':
1843 // handled by the proximity_distance clause
1844 return;
1845
1846 default:
1847 $this->restWhere($values);
1848 return;
1849 }
1850 }
1851
1852 /**
1853 * Given a list of conditions in params generate the required.
1854 * where clause
1855 *
1856 * @return string
1857 */
1858 public function whereClause() {
1859 $this->_where[0] = array();
1860 $this->_qill[0] = array();
1861
1862 $this->includeContactIds();
1863 if (!empty($this->_params)) {
1864 foreach (array_keys($this->_params) as $id) {
1865 if (empty($this->_params[$id][0])) {
1866 continue;
1867 }
1868 // check for both id and contact_id
1869 if ($this->_params[$id][0] == 'id' || $this->_params[$id][0] == 'contact_id') {
1870 if (
1871 $this->_params[$id][1] == 'IS NULL' ||
1872 $this->_params[$id][1] == 'IS NOT NULL'
1873 ) {
1874 $this->_where[0][] = "contact_a.id {$this->_params[$id][1]}";
1875 }
1876 elseif (is_array($this->_params[$id][2])) {
1877 $idList = implode("','", $this->_params[$id][2]);
1878 //why on earth do they put ' in the middle & not on the outside? We have to assume it's
1879 //to support 'something' so lets add them conditionally to support the api (which is a tested flow
1880 // so if you are looking to alter this check api test results
1881 if (strpos(trim($idList), "'") > 0) {
1882 $idList = "'" . $idList . "'";
1883 }
1884
1885 $this->_where[0][] = "contact_a.id IN ({$idList})";
1886 }
1887 else {
1888 $this->_where[0][] = self::buildClause("contact_a.id", "{$this->_params[$id][1]}", "{$this->_params[$id][2]}");
1889 }
1890 }
1891 else {
1892 $this->whereClauseSingle($this->_params[$id]);
1893 }
1894 }
1895
1896 CRM_Core_Component::alterQuery($this, 'where');
1897
1898 CRM_Contact_BAO_Query_Hook::singleton()->alterSearchQuery($this, 'where');
1899 }
1900
1901 if ($this->_customQuery) {
1902 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1903 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1904 if (!empty($this->_customQuery->_where)) {
1905 $this->_where = CRM_Utils_Array::crmArrayMerge($this->_where, $this->_customQuery->_where);
1906 }
1907
1908 $this->_qill = CRM_Utils_Array::crmArrayMerge($this->_qill, $this->_customQuery->_qill);
1909 }
1910
1911 $clauses = array();
1912 $andClauses = array();
1913
1914 $validClauses = 0;
1915 if (!empty($this->_where)) {
1916 foreach ($this->_where as $grouping => $values) {
1917 if ($grouping > 0 && !empty($values)) {
1918 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1919 $validClauses++;
1920 }
1921 }
1922
1923 if (!empty($this->_where[0])) {
1924 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where[0]) . ' ) ';
1925 }
1926 if (!empty($clauses)) {
1927 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1928 }
1929
1930 if ($validClauses > 1) {
1931 $this->_useDistinct = TRUE;
1932 }
1933 }
1934
1935 return implode(' AND ', $andClauses);
1936 }
1937
1938 /**
1939 * @param $values
1940 *
1941 * @throws Exception
1942 */
1943 public function restWhere(&$values) {
1944 $name = CRM_Utils_Array::value(0, $values);
1945 $op = CRM_Utils_Array::value(1, $values);
1946 $value = CRM_Utils_Array::value(2, $values);
1947 $grouping = CRM_Utils_Array::value(3, $values);
1948 $wildcard = CRM_Utils_Array::value(4, $values);
1949
1950 if (isset($grouping) && empty($this->_where[$grouping])) {
1951 $this->_where[$grouping] = array();
1952 }
1953
1954 $multipleFields = array('url');
1955
1956 //check if the location type exits for fields
1957 $lType = '';
1958 $locType = explode('-', $name);
1959
1960 if (!in_array($locType[0], $multipleFields)) {
1961 //add phone type if exists
1962 if (isset($locType[2]) && $locType[2]) {
1963 $locType[2] = CRM_Core_DAO::escapeString($locType[2]);
1964 }
1965 }
1966
1967 $field = CRM_Utils_Array::value($name, $this->_fields);
1968
1969 if (!$field) {
1970 $field = CRM_Utils_Array::value($locType[0], $this->_fields);
1971
1972 if (!$field) {
1973 return;
1974 }
1975 }
1976
1977 $setTables = TRUE;
1978
1979 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
1980 $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
1981
1982 if (substr($name, 0, 14) === 'state_province') {
1983 if (isset($locType[1]) && is_numeric($locType[1])) {
1984 $setTables = FALSE;
1985 $aName = "{$locationType[$locType[1]]}-address";
1986 $where = "`$aName`.state_province_id";
1987 }
1988 else {
1989 $where = "civicrm_address.state_province_id";
1990 }
1991
1992 $states = CRM_Core_PseudoConstant::stateProvince();
1993 if (is_numeric($value)) {
1994 $this->_where[$grouping][] = self::buildClause($where, $op, $value, 'Positive');
1995 $value = $states[(int ) $value];
1996 }
1997 else {
1998 $intVal = CRM_Utils_Array::key($value, $states);
1999 $this->_where[$grouping][] = self::buildClause($where, $op, $intVal, 'Positive');
2000 }
2001 if (!$lType) {
2002 $this->_qill[$grouping][] = ts('State') . " $op '$value'";
2003 }
2004 else {
2005 $this->_qill[$grouping][] = ts('State') . " ($lType) $op '$value'";
2006 }
2007 }
2008 elseif (!empty($field['pseudoconstant'])) {
2009 $this->optionValueQuery(
2010 $name, $op, $value, $grouping,
2011 CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', $field['name']),
2012 $field,
2013 $field['title'],
2014 'String',
2015 TRUE
2016 );
2017 if ($name == 'gender_id') {
2018 self::$_openedPanes[ts('Demographics')] = TRUE;
2019 }
2020 }
2021 elseif (substr($name, 0, 7) === 'country') {
2022 if (isset($locType[1]) && is_numeric($locType[1])) {
2023 $setTables = FALSE;
2024 $aName = "{$locationType[$locType[1]]}-address";
2025 $where = "`$aName`.country_id";
2026 }
2027 else {
2028 $where = "civicrm_address.country_id";
2029 }
2030
2031 $countries = CRM_Core_PseudoConstant::country();
2032 if (is_numeric($value)) {
2033 $this->_where[$grouping][] = self::buildClause($where, $op, $value, 'Positive');
2034 $value = $countries[(int ) $value];
2035 }
2036 else {
2037 $intVal = CRM_Utils_Array::key($value, $countries);
2038 $this->_where[$grouping][] = self::buildClause($where, $op, $intVal, 'Positive');
2039 }
2040
2041 if (!$lType) {
2042 $this->_qill[$grouping][] = ts('Country') . " $op '$value'";
2043 }
2044 else {
2045 $this->_qill[$grouping][] = ts('Country') . " ($lType) $op '$value'";
2046 }
2047 }
2048 elseif (substr($name, 0, 6) === 'county') {
2049 if (isset($locType[1]) && is_numeric($locType[1])) {
2050 $setTables = FALSE;
2051 $aName = "{$locationType[$locType[1]]}-address";
2052 $where = "`$aName`.county_id";
2053 }
2054 else {
2055 $where = "civicrm_address.county_id";
2056 }
2057
2058 $counties = CRM_Core_PseudoConstant::county();
2059 if (is_numeric($value)) {
2060 $this->_where[$grouping][] = self::buildClause($where, $op, $value, 'Positive');
2061 $value = $counties[(int ) $value];
2062 }
2063 else {
2064 $intVal = CRM_Utils_Array::key($value, $counties);
2065 $this->_where[$grouping][] = self::buildClause($where, $op, $intVal, 'Positive');
2066 }
2067
2068 if (!$lType) {
2069 $this->_qill[$grouping][] = ts('County') . " $op '$value'";
2070 }
2071 else {
2072 $this->_qill[$grouping][] = ts('County') . " ($lType) $op '$value'";
2073 }
2074 }
2075 elseif ($name === 'world_region') {
2076 $field['where'] = 'civicrm_worldregion.id';
2077 $this->optionValueQuery(
2078 $name, $op, $value, $grouping,
2079 CRM_Core_PseudoConstant::worldRegion(),
2080 $field,
2081 ts('World Region'),
2082 'Positive',
2083 TRUE
2084 );
2085 }
2086 elseif ($name === 'is_deceased') {
2087 $this->_where[$grouping][] = self::buildClause("contact_a.{$name}", $op, $value);
2088 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2089 self::$_openedPanes[ts('Demographics')] = TRUE;
2090 }
2091 elseif ($name === 'created_date' || $name === 'modified_date' || $name === 'deceased_date' || $name === 'birth_date') {
2092 $appendDateTime = TRUE;
2093 if ($name === 'deceased_date' || $name === 'birth_date') {
2094 $appendDateTime = FALSE;
2095 self::$_openedPanes[ts('Demographics')] = TRUE;
2096 }
2097 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2098 }
2099 elseif ($name === 'contact_id') {
2100 if (is_int($value)) {
2101 $this->_where[$grouping][] = self::buildClause($field['where'], $op, $value);
2102 $this->_qill[$grouping][] = "$field[title] $op $value";
2103 }
2104 }
2105 elseif ($name === 'name') {
2106 $value = $strtolower(CRM_Core_DAO::escapeString($value));
2107 if ($wildcard) {
2108 $value = "%$value%";
2109 $op = 'LIKE';
2110 }
2111 $wc = self::caseImportant($op) ? "LOWER({$field['where']})" : "{$field['where']}";
2112 $this->_where[$grouping][] = self::buildClause($wc, $op, "'$value'");
2113 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2114 }
2115 elseif ($name === 'current_employer') {
2116 $value = $strtolower(CRM_Core_DAO::escapeString($value));
2117 if ($wildcard) {
2118 $value = "%$value%";
2119 $op = 'LIKE';
2120 }
2121 $wc = self::caseImportant($op) ? "LOWER(contact_a.organization_name)" : "contact_a.organization_name";
2122 $ceWhereClause = self::buildClause($wc, $op,
2123 $value
2124 );
2125 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2126 $this->_where[$grouping][] = $ceWhereClause;
2127 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2128 }
2129 elseif ($name === 'email_greeting') {
2130 $filterCondition = array('greeting_type' => 'email_greeting');
2131 $this->optionValueQuery(
2132 $name, $op, $value, $grouping,
2133 CRM_Core_PseudoConstant::greeting($filterCondition),
2134 $field,
2135 ts('Email Greeting')
2136 );
2137 }
2138 elseif ($name === 'postal_greeting') {
2139 $filterCondition = array('greeting_type' => 'postal_greeting');
2140 $this->optionValueQuery(
2141 $name, $op, $value, $grouping,
2142 CRM_Core_PseudoConstant::greeting($filterCondition),
2143 $field,
2144 ts('Postal Greeting')
2145 );
2146 }
2147 elseif ($name === 'addressee') {
2148 $filterCondition = array('greeting_type' => 'addressee');
2149 $this->optionValueQuery(
2150 $name, $op, $value, $grouping,
2151 CRM_Core_PseudoConstant::greeting($filterCondition),
2152 $field,
2153 ts('Addressee')
2154 );
2155 }
2156 elseif (substr($name, 0, 4) === 'url-') {
2157 $tName = 'civicrm_website';
2158 $this->_whereTables[$tName] = $this->_tables[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2159 $value = $strtolower(CRM_Core_DAO::escapeString($value));
2160 if ($wildcard) {
2161 $value = "%$value%";
2162 $op = 'LIKE';
2163 }
2164
2165 $wc = 'civicrm_website.url';
2166 $this->_where[$grouping][] = $d = self::buildClause($wc, $op, $value);
2167 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2168 }
2169 elseif ($name === 'contact_is_deleted') {
2170 $this->_where[$grouping][] = self::buildClause("contact_a.is_deleted", $op, $value);
2171 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2172 }
2173 elseif (!empty($field['where'])) {
2174 $type = NULL;
2175 if (!empty($field['type'])) {
2176 $type = CRM_Utils_Type::typeToString($field['type']);
2177 }
2178
2179 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2180
2181 if (isset($locType[1]) &&
2182 is_numeric($locType[1])
2183 ) {
2184 $setTables = FALSE;
2185
2186 //get the location name
2187 list($tName, $fldName) = self::getLocationTableName($field['where'], $locType);
2188
2189 $fieldName = "LOWER(`$tName`.$fldName)";
2190
2191 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2192 $this->_tables[$tName] = $this->_whereTables[$tName] = 1;
2193
2194 }
2195 else {
2196 if ($tableName == 'civicrm_contact') {
2197 $fieldName = "LOWER(contact_a.{$fieldName})";
2198 }
2199 else {
2200 if ($op != 'IN' && !is_numeric($value)) {
2201 $fieldName = "LOWER({$field['where']})";
2202 }
2203 else {
2204 $fieldName = "{$field['where']}";
2205 }
2206 }
2207 }
2208
2209 list($qillop, $qillVal) = self::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2210 $this->_qill[$grouping][] = "$field[title] $qillop '$qillVal'";
2211
2212 if (is_array($value)) {
2213 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2214 // for api style operators for functions that hit this point without worrying about regression
2215 // (the previous comments indicated the condition for hitting this point were unknown
2216 // per CRM-14743 we are adding modified_date & created_date operator support
2217 $operations = array_keys($value);
2218 foreach ($operations as $operator) {
2219 if (!in_array($operator, CRM_Core_DAO::acceptedSQLOperators())) {
2220 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2221 //so this condition will satisfy the search for now
2222 if (strpos($op, 'IN') !== FALSE) {
2223 $value = array($op => $value);
2224 }
2225 // we don't know when this might happen
2226 else {
2227 CRM_Core_Error::fatal(ts("%1 is not a valid operator", array(1 => $operator)));
2228 }
2229 }
2230 }
2231 $this->_where[$grouping][] = CRM_Core_DAO::createSQLFilter($fieldName, $value, $type);
2232 }
2233 else {
2234 if ($op != 'IN') {
2235 $value = $strtolower($value);
2236 }
2237 if ($wildcard) {
2238 $value = "%$value%";
2239 $op = 'LIKE';
2240 }
2241
2242 $this->_where[$grouping][] = self::buildClause($fieldName, $op, $value, $type);
2243 }
2244 }
2245
2246 if ($setTables && isset($field['where'])) {
2247 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2248 if (isset($tableName)) {
2249 $this->_tables[$tableName] = 1;
2250 $this->_whereTables[$tableName] = 1;
2251 }
2252 }
2253 }
2254
2255
2256 /**
2257 * @param $where
2258 * @param $locType
2259 *
2260 * @return array
2261 * @throws Exception
2262 */
2263 public static function getLocationTableName(&$where, &$locType) {
2264 if (isset($locType[1]) && is_numeric($locType[1])) {
2265 list($tbName, $fldName) = explode(".", $where);
2266
2267 //get the location name
2268 $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
2269 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2270 if (in_array($locType[0], $specialFields)) {
2271 //hack to fix / special handing for phone_ext
2272 if ($locType[0] == 'phone_ext') {
2273 $locType[0] = 'phone';
2274 }
2275 if (isset($locType[2]) && $locType[2]) {
2276 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2277 }
2278 else {
2279 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2280 }
2281 }
2282 elseif (in_array($locType[0],
2283 array(
2284 'address_name',
2285 'street_address',
2286 'supplemental_address_1',
2287 'supplemental_address_2',
2288 'city',
2289 'postal_code',
2290 'postal_code_suffix',
2291 'geo_code_1',
2292 'geo_code_2',
2293 )
2294 )) {
2295 //fix for search by profile with address fields.
2296 $tName = "{$locationType[$locType[1]]}-address";
2297 }
2298 elseif ($locType[0] == 'on_hold') {
2299 $tName = "{$locationType[$locType[1]]}-email";
2300 }
2301 else {
2302 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2303 }
2304 $tName = str_replace(' ', '_', $tName);
2305 return array($tName, $fldName);
2306 }
2307 CRM_Core_Error::fatal();
2308 }
2309
2310 /**
2311 * Given a result dao, extract the values and return that array
2312 *
2313 * @param CRM_Core_DAO $dao
2314 *
2315 * @return array
2316 * values for this query
2317 */
2318 public function store($dao) {
2319 $value = array();
2320
2321 foreach ($this->_element as $key => $dontCare) {
2322 if (property_exists($dao, $key)) {
2323 if (strpos($key, '-') !== FALSE) {
2324 $values = explode('-', $key);
2325 $lastElement = array_pop($values);
2326 $current = &$value;
2327 $cnt = count($values);
2328 $count = 1;
2329 foreach ($values as $v) {
2330 if (!array_key_exists($v, $current)) {
2331 $current[$v] = array();
2332 }
2333 //bad hack for im_provider
2334 if ($lastElement == 'provider_id') {
2335 if ($count < $cnt) {
2336 $current = &$current[$v];
2337 }
2338 else {
2339 $lastElement = "{$v}_{$lastElement}";
2340 }
2341 }
2342 else {
2343 $current = &$current[$v];
2344 }
2345 $count++;
2346 }
2347
2348 $current[$lastElement] = $dao->$key;
2349 }
2350 else {
2351 $value[$key] = $dao->$key;
2352 }
2353 }
2354 }
2355 return $value;
2356 }
2357
2358 /**
2359 * Getter for tables array.
2360 *
2361 * @return array
2362 */
2363 public function tables() {
2364 return $this->_tables;
2365 }
2366
2367 /**
2368 * Where tables is sometimes used to create the from clause, but, not reliably, set this AND set tables
2369 * It's unclear the intent - there is a 'simpleFrom' clause which takes whereTables into account & a fromClause which doesn't
2370 * logic may have eroded
2371 * @return array
2372 */
2373 public function whereTables() {
2374 return $this->_whereTables;
2375 }
2376
2377 /**
2378 * Generate the where clause (used in match contacts and permissions)
2379 *
2380 * @param array $params
2381 * @param array $fields
2382 * @param array $tables
2383 * @param $whereTables
2384 * @param bool $strict
2385 *
2386 * @return string
2387 */
2388 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2389 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2390 FALSE, $strict
2391 );
2392
2393 $tables = array_merge($query->tables(), $tables);
2394 $whereTables = array_merge($query->whereTables(), $whereTables);
2395
2396 return $query->_whereClause;
2397 }
2398
2399 /**
2400 * Create the from clause.
2401 *
2402 * @param array $tables
2403 * Tables that need to be included in this from clause.
2404 * if null, return mimimal from clause (i.e. civicrm_contact)
2405 * @param array $inner
2406 * Tables that should be inner-joined.
2407 * @param array $right
2408 * Tables that should be right-joined.
2409 *
2410 * @param bool $primaryLocation
2411 * @param int $mode
2412 *
2413 * @return string
2414 * the from clause
2415 */
2416 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2417
2418 $from = ' FROM civicrm_contact contact_a';
2419 if (empty($tables)) {
2420 return $from;
2421 }
2422
2423 if (!empty($tables['civicrm_worldregion'])) {
2424 $tables = array_merge(array('civicrm_country' => 1), $tables);
2425 }
2426
2427 if ((!empty($tables['civicrm_state_province']) || !empty($tables['civicrm_country']) ||
2428 CRM_Utils_Array::value('civicrm_county', $tables)
2429 ) && empty($tables['civicrm_address'])
2430 ) {
2431 $tables = array_merge(array('civicrm_address' => 1),
2432 $tables
2433 );
2434 }
2435
2436 // add group_contact and group_contact_cache table if group table is present
2437 if (!empty($tables['civicrm_group'])) {
2438 if (empty($tables['civicrm_group_contact'])) {
2439 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added' ";
2440 }
2441 if (empty($tables['civicrm_group_contact_cache'])) {
2442 $tables['civicrm_group_contact_cache'] = " LEFT JOIN civicrm_group_contact_cache ON civicrm_group_contact_cache.contact_id = contact_a.id ";
2443 }
2444 }
2445
2446 // add group_contact and group table is subscription history is present
2447 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2448 $tables = array_merge(array(
2449 'civicrm_group' => 1,
2450 'civicrm_group_contact' => 1,
2451 ),
2452 $tables
2453 );
2454 }
2455
2456 // to handle table dependencies of components
2457 CRM_Core_Component::tableNames($tables);
2458 // to handle table dependencies of hook injected tables
2459 CRM_Contact_BAO_Query_Hook::singleton()->setTableDependency($tables);
2460
2461 //format the table list according to the weight
2462 $info = CRM_Core_TableHierarchy::info();
2463
2464 foreach ($tables as $key => $value) {
2465 $k = 99;
2466 if (strpos($key, '-') !== FALSE) {
2467 $keyArray = explode('-', $key);
2468 $k = CRM_Utils_Array::value('civicrm_' . $keyArray[1], $info, 99);
2469 }
2470 elseif (strpos($key, '_') !== FALSE) {
2471 $keyArray = explode('_', $key);
2472 if (is_numeric(array_pop($keyArray))) {
2473 $k = CRM_Utils_Array::value(implode('_', $keyArray), $info, 99);
2474 }
2475 else {
2476 $k = CRM_Utils_Array::value($key, $info, 99);
2477 }
2478 }
2479 else {
2480 $k = CRM_Utils_Array::value($key, $info, 99);
2481 }
2482 $tempTable[$k . ".$key"] = $key;
2483 }
2484 ksort($tempTable);
2485 $newTables = array();
2486 foreach ($tempTable as $key) {
2487 $newTables[$key] = $tables[$key];
2488 }
2489
2490 $tables = $newTables;
2491
2492 foreach ($tables as $name => $value) {
2493 if (!$value) {
2494 continue;
2495 }
2496
2497 if (!empty($inner[$name])) {
2498 $side = 'INNER';
2499 }
2500 elseif (!empty($right[$name])) {
2501 $side = 'RIGHT';
2502 }
2503 else {
2504 $side = 'LEFT';
2505 }
2506
2507 if ($value != 1) {
2508 // if there is already a join statement in value, use value itself
2509 if (strpos($value, 'JOIN')) {
2510 $from .= " $value ";
2511 }
2512 else {
2513 $from .= " $side JOIN $name ON ( $value ) ";
2514 }
2515 continue;
2516 }
2517 switch ($name) {
2518 case 'civicrm_address':
2519 if ($primaryLocation) {
2520 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2521 }
2522 else {
2523 //CRM-14263 further handling of address joins further down...
2524 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2525 }
2526 continue;
2527
2528 case 'civicrm_phone':
2529 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2530 continue;
2531
2532 case 'civicrm_email':
2533 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2534 continue;
2535
2536 case 'civicrm_im':
2537 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2538 continue;
2539
2540 case 'im_provider':
2541 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2542 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2543 $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)";
2544 continue;
2545
2546 case 'civicrm_openid':
2547 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2548 continue;
2549
2550 case 'civicrm_worldregion':
2551 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2552 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2553 continue;
2554
2555 case 'civicrm_location_type':
2556 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2557 continue;
2558
2559 case 'civicrm_group':
2560 $from .= " $side JOIN civicrm_group ON (civicrm_group.id = civicrm_group_contact.group_id OR civicrm_group.id = civicrm_group_contact_cache.group_id) ";
2561 continue;
2562
2563 case 'civicrm_group_contact':
2564 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2565 continue;
2566
2567 case 'civicrm_group_contact_cache':
2568 $from .= " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
2569 continue;
2570
2571 case 'civicrm_activity':
2572 case 'civicrm_activity_tag':
2573 case 'activity_type':
2574 case 'activity_status':
2575 case 'parent_id':
2576 case 'civicrm_activity_contact':
2577 case 'source_contact':
2578 $from .= CRM_Activity_BAO_Query::from($name, $mode, $side);
2579 continue;
2580
2581 case 'civicrm_entity_tag':
2582 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2583 civicrm_entity_tag.entity_id = contact_a.id ) ";
2584 continue;
2585
2586 case 'civicrm_note':
2587 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2588 contact_a.id = civicrm_note.entity_id ) ";
2589 continue;
2590
2591 case 'civicrm_subscription_history':
2592 $from .= " $side JOIN civicrm_subscription_history
2593 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2594 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2595 continue;
2596
2597 case 'civicrm_relationship':
2598 if (self::$_relType == 'reciprocal') {
2599 if (self::$_relationshipTempTable) {
2600 // we have a temptable to join on
2601 $tbl = self::$_relationshipTempTable;
2602 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2603 }
2604 else {
2605 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2606 $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)";
2607 }
2608 }
2609 elseif (self::$_relType == 'b') {
2610 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2611 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2612 }
2613 else {
2614 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2615 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2616 }
2617 continue;
2618
2619 case 'civicrm_log':
2620 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2621 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2622 continue;
2623
2624 case 'civicrm_tag':
2625 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2626 continue;
2627
2628 case 'civicrm_grant':
2629 $from .= CRM_Grant_BAO_Query::from($name, $mode, $side);
2630 continue;
2631
2632 case 'civicrm_website':
2633 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2634 continue;
2635
2636 default:
2637 $locationTypeName = '';
2638 if (strpos($name, '-address') != 0) {
2639 $locationTypeName = 'address';
2640 }
2641 elseif (strpos($name, '-phone') != 0) {
2642 $locationTypeName = 'phone';
2643 }
2644 elseif (strpos($name, '-email') != 0) {
2645 $locationTypeName = 'email';
2646 }
2647 if ($locationTypeName) {
2648 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2649 $parts = explode('-', $name);
2650 $locationID = array_search($parts[0], CRM_Core_BAO_Address::buildOptions('location_type_id', 'get', array('name' => $parts[0])));
2651 $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2652 }
2653 else {
2654 $from .= CRM_Core_Component::from($name, $mode, $side);
2655 }
2656 $from .= CRM_Contact_BAO_Query_Hook::singleton()->buildSearchfrom($name, $mode, $side);
2657
2658 continue;
2659 }
2660 }
2661 return $from;
2662 }
2663
2664 /**
2665 * WHERE / QILL clause for deleted_contacts
2666 *
2667 * @param $values
2668 *
2669 * @return void
2670 */
2671 public function deletedContacts($values) {
2672 list($_, $_, $value, $grouping, $_) = $values;
2673 if ($value) {
2674 // *prepend* to the relevant grouping as this is quite an important factor
2675 array_unshift($this->_qill[$grouping], ts('Search in Trash'));
2676 }
2677 }
2678
2679 /**
2680 * Where / qill clause for contact_type
2681 *
2682 * @param $values
2683 *
2684 * @return void
2685 */
2686 public function contactType(&$values) {
2687 list($name, $op, $value, $grouping, $wildcard) = $values;
2688
2689 $subTypes = array();
2690 $clause = array();
2691
2692 // account for search builder mapping multiple values
2693 if (!is_array($value)) {
2694 $values = self::parseSearchBuilderString($value, 'String');
2695 if (is_array($values)) {
2696 $value = array_flip($values);
2697 }
2698 }
2699
2700 if (is_array($value)) {
2701 foreach ($value as $k => $v) {
2702 // fix for CRM-771
2703 if ($k) {
2704 $subType = NULL;
2705 $contactType = $k;
2706 if (strpos($k, CRM_Core_DAO::VALUE_SEPARATOR)) {
2707 list($contactType, $subType) = explode(CRM_Core_DAO::VALUE_SEPARATOR, $k, 2);
2708 }
2709
2710 if (!empty($subType)) {
2711 $subTypes[$subType] = 1;
2712 }
2713 $clause[$contactType] = "'" . CRM_Utils_Type::escape($contactType, 'String') . "'";
2714 }
2715 }
2716 }
2717 else {
2718 $contactTypeANDSubType = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value, 2);
2719 $contactType = $contactTypeANDSubType[0];
2720 $subType = CRM_Utils_Array::value(1, $contactTypeANDSubType);
2721 if (!empty($subType)) {
2722 $subTypes[$subType] = 1;
2723 }
2724 $clause[$contactType] = "'" . CRM_Utils_Type::escape($contactType, 'String') . "'";
2725 }
2726
2727 // fix for CRM-771
2728 if (!empty($clause)) {
2729 $quill = $clause;
2730 if ($op == 'IN' || $op == 'NOT IN') {
2731 $this->_where[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2732 }
2733 else {
2734 $type = array_pop($clause);
2735 $this->_where[$grouping][] = self::buildClause("contact_a.contact_type", $op, $contactType);
2736 }
2737
2738 $this->_qill[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2739
2740 if (!empty($subTypes)) {
2741 $this->includeContactSubTypes($subTypes, $grouping);
2742 }
2743 }
2744 }
2745
2746 /**
2747 * Where / qill clause for contact_sub_type
2748 *
2749 * @param $values
2750 *
2751 * @return void
2752 */
2753 public function contactSubType(&$values) {
2754 list($name, $op, $value, $grouping, $wildcard) = $values;
2755 $this->includeContactSubTypes($value, $grouping, $op);
2756 }
2757
2758 /**
2759 * @param $value
2760 * @param $grouping
2761 * @param string $op
2762 */
2763 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2764
2765 $clause = array();
2766 $alias = "contact_a.contact_sub_type";
2767 $qillOperators = array('NOT LIKE' => ts('Not Like')) + CRM_Core_SelectValues::getSearchBuilderOperators();
2768
2769 $op = str_replace('IN', 'LIKE', $op);
2770 $op = str_replace('=', 'LIKE', $op);
2771 $op = str_replace('!', 'NOT ', $op);
2772
2773 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
2774 $this->_where[$grouping][] = self::buildClause($alias, $op, $value, 'String');
2775 }
2776 elseif (is_array($value)) {
2777 foreach ($value as $k => $v) {
2778 if (!empty($k)) {
2779 $clause[$k] = "($alias $op '%" . CRM_Core_DAO::VALUE_SEPARATOR . CRM_Utils_Type::escape($k, 'String') . CRM_Core_DAO::VALUE_SEPARATOR . "%')";
2780 }
2781 }
2782 }
2783 else {
2784 $clause[$value] = "($alias $op '%" . CRM_Core_DAO::VALUE_SEPARATOR . CRM_Utils_Type::escape($value, 'String') . CRM_Core_DAO::VALUE_SEPARATOR . "%')";
2785 }
2786
2787 if (!empty($clause)) {
2788 $this->_where[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2789 }
2790 $this->_qill[$grouping][] = ts('Contact Subtype %1 ', array(1 => $qillOperators[$op])) . implode(' ' . ts('or') . ' ', array_keys($clause));
2791 }
2792
2793 /**
2794 * Where / qill clause for groups
2795 *
2796 * @param $values
2797 *
2798 * @return void
2799 */
2800 public function group(&$values) {
2801 list($name, $op, $value, $grouping, $wildcard) = $values;
2802
2803 // Replace pseudo operators from search builder
2804 $op = str_replace('EMPTY', 'NULL', $op);
2805
2806 if (count($value) > 1) {
2807 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
2808 CRM_Core_Error::fatal(ts("%1 is not a valid operator", array(1 => $op)));
2809 }
2810 $this->_useDistinct = TRUE;
2811 }
2812
2813 $groupIds = NULL;
2814 $names = array();
2815 $isSmart = FALSE;
2816 $isNotOp = ($op == 'NOT IN' || $op == '!=');
2817
2818 if ($value) {
2819 if (strpos($op, 'IN') === FALSE) {
2820 $value = key($value);
2821 }
2822 else {
2823 $value = array_keys($value);
2824 }
2825 }
2826
2827 $statii = array();
2828 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2829 if ($gcsValues &&
2830 is_array($gcsValues[2])
2831 ) {
2832 foreach ($gcsValues[2] as $k => $v) {
2833 if ($v) {
2834 $statii[] = "'" . CRM_Utils_Type::escape($k, 'String') . "'";
2835 }
2836 }
2837 }
2838 else {
2839 $statii[] = '"Added"';
2840 }
2841
2842 $skipGroup = FALSE;
2843 if (!is_array($value) &&
2844 count($statii) == 1 &&
2845 $statii[0] == '"Added"' &&
2846 !$isNotOp
2847 ) {
2848 if (!empty($value) && CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $value, 'saved_search_id')) {
2849 $isSmart = TRUE;
2850 }
2851 }
2852
2853 $ssClause = $this->addGroupContactCache($value, NULL, "contact_a", $op);
2854 $isSmart = (!$ssClause) ? FALSE : $isSmart;
2855 $groupClause = NULL;
2856
2857 if (!$isSmart) {
2858 $groupIds = implode(',', (array) $value);
2859 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2860 $joinClause = array("contact_a.id = {$gcTable}.contact_id");
2861 if ($statii) {
2862 $joinClause[] = "{$gcTable}.status IN (" . implode(', ', $statii) . ")";
2863 }
2864 $this->_tables[$gcTable] = $this->_whereTables[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
2865 $groupClause = "{$gcTable}.group_id $op $groupIds";
2866 if (strpos($op, 'IN') !== FALSE) {
2867 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2868 }
2869 }
2870
2871 if ($ssClause) {
2872 $and = ($op == 'IS NULL') ? 'AND' : 'OR';
2873 if ($groupClause) {
2874 $groupClause = "( ( $groupClause ) $and ( $ssClause ) )";
2875 }
2876 else {
2877 $groupClause = $ssClause;
2878 }
2879 }
2880
2881 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
2882 $this->_qill[$grouping][] = ts("Group(s) %1 %2", array(1 => $qillop, 2 => $qillVal));
2883 if (strpos($op, 'NULL') === FALSE) {
2884 $this->_qill[$grouping][] = ts("Group Status %1", array(1 => implode(' ' . ts('or') . ' ', $statii)));
2885 }
2886 if ($groupClause) {
2887 $this->_where[$grouping][] = $groupClause;
2888 }
2889 }
2890
2891 /**
2892 * Function translates selection of group type into a list of groups.
2893 * @param $value
2894 *
2895 * @return array
2896 */
2897 public function getGroupsFromTypeCriteria($value) {
2898 $groupIds = array();
2899 foreach ((array) $value as $groupTypeValue) {
2900 $groupList = CRM_Core_PseudoConstant::group($groupTypeValue);
2901 $groupIds = ($groupIds + $groupList);
2902 }
2903 return $groupIds;
2904 }
2905
2906 /**
2907 * @param array $groups
2908 * @param string $tableAlias
2909 * @param string $joinTable
2910 * @param string $op
2911 *
2912 * @return null|string
2913 */
2914 public function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a", $op) {
2915 $isNullOp = (strpos($op, 'NULL') !== FALSE);
2916 $groupsIds = $groups;
2917 if (!$isNullOp && !$groups) {
2918 return NULL;
2919 }
2920 elseif (strpos($op, 'IN') !== FALSE) {
2921 $groups = array($op => $groups);
2922 }
2923 elseif (is_array($groups) && count($groups)) {
2924 $groups = array('IN' => $groups);
2925 }
2926
2927 // Find all the groups that are part of a saved search.
2928 $smartGroupClause = self::buildClause("id", $op, $groups, 'Int');
2929 $sql = "
2930 SELECT id, cache_date, saved_search_id, children
2931 FROM civicrm_group
2932 WHERE $smartGroupClause
2933 AND ( saved_search_id != 0
2934 OR saved_search_id IS NOT NULL
2935 OR children IS NOT NULL )
2936 ";
2937
2938 $group = CRM_Core_DAO::executeQuery($sql);
2939
2940 while ($group->fetch()) {
2941 $this->_useDistinct = TRUE;
2942 if (!$this->_smartGroupCache || $group->cache_date == NULL) {
2943 CRM_Contact_BAO_GroupContactCache::load($group);
2944 }
2945 }
2946
2947 if (!$tableAlias) {
2948 $tableAlias = "`civicrm_group_contact_cache_";
2949 $tableAlias .= ($isNullOp) ? "a`" : implode(',', (array) $groupsIds) . "`";
2950 }
2951
2952 $this->_tables[$tableAlias] = $this->_whereTables[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.id = {$tableAlias}.contact_id ";
2953 return self::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
2954 }
2955
2956 /**
2957 * Where / qill clause for cms users
2958 *
2959 * @param $values
2960 *
2961 * @return void
2962 */
2963 public function ufUser(&$values) {
2964 list($name, $op, $value, $grouping, $wildcard) = $values;
2965
2966 if ($value == 1) {
2967 $this->_tables['civicrm_uf_match'] = $this->_whereTables['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2968
2969 $this->_qill[$grouping][] = ts('CMS User');
2970 }
2971 elseif ($value == 0) {
2972 $this->_tables['civicrm_uf_match'] = $this->_whereTables['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2973
2974 $this->_where[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2975 $this->_qill[$grouping][] = ts('Not a CMS User');
2976 }
2977 }
2978
2979 /**
2980 * All tag search specific.
2981 *
2982 * @param $values
2983 *
2984 * @return void
2985 */
2986 public function tagSearch(&$values) {
2987 list($name, $op, $value, $grouping, $wildcard) = $values;
2988
2989 $op = "LIKE";
2990 $value = "%{$value}%";
2991
2992 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2993 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2994
2995 $etTable = "`civicrm_entity_tag-" . $value . "`";
2996 $tTable = "`civicrm_tag-" . $value . "`";
2997
2998 if ($useAllTagTypes[2]) {
2999 $this->_tables[$etTable] = $this->_whereTables[$etTable]
3000 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3001 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3002
3003 // search tag in cases
3004 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3005 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
3006 $this->_tables[$etCaseTable] = $this->_whereTables[$etCaseTable]
3007 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3008 LEFT JOIN civicrm_case
3009 ON (civicrm_case_contact.case_id = civicrm_case.id
3010 AND civicrm_case.is_deleted = 0 )
3011 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3012 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3013 // search tag in activities
3014 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3015 $tActTable = "`civicrm_act_tag-" . $value . "`";
3016 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3017 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
3018
3019 $this->_tables[$etActTable] = $this->_whereTables[$etActTable]
3020 = " LEFT JOIN civicrm_activity_contact
3021 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3022 LEFT JOIN civicrm_activity
3023 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3024 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3025 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3026 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3027
3028 $this->_where[$grouping][] = "({$tTable}.name $op '" . $value . "' OR {$tCaseTable}.name $op '" . $value . "' OR {$tActTable}.name $op '" . $value . "')";
3029 $this->_qill[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
3030 }
3031 else {
3032 $etTable = "`civicrm_entity_tag-" . $value . "`";
3033 $tTable = "`civicrm_tag-" . $value . "`";
3034 $this->_tables[$etTable] = $this->_whereTables[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3035 {$etTable}.entity_table = 'civicrm_contact' )
3036 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3037
3038 $this->_where[$grouping][] = self::buildClause("{$tTable}.name", $op, $value, 'String');
3039 $this->_qill[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
3040 }
3041 }
3042
3043 /**
3044 * Where / qill clause for tag
3045 *
3046 * @param $values
3047 *
3048 * @return void
3049 */
3050 public function tag(&$values) {
3051 list($name, $op, $value, $grouping, $wildcard) = $values;
3052
3053 $tagNames = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
3054 if (is_array($value)) {
3055 if (count($value) > 1) {
3056 $this->_useDistinct = TRUE;
3057 }
3058 foreach ($value as $id => $dontCare) {
3059 $names[] = CRM_Utils_Array::value($id, $tagNames);
3060 }
3061 $names = implode(' ' . ts('or') . ' ', $names);
3062 $value = implode(',', array_keys($value));
3063 }
3064 else {
3065 $names = CRM_Utils_Array::value($value, $tagNames);
3066 }
3067
3068 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3069 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3070
3071 $etTable = "`civicrm_entity_tag-" . $value . "`";
3072
3073 if ($useAllTagTypes[2]) {
3074 $this->_tables[$etTable] = $this->_whereTables[$etTable]
3075 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3076
3077 // search tag in cases
3078 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
3079 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
3080 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
3081
3082 $this->_tables[$etCaseTable] = $this->_whereTables[$etCaseTable]
3083 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3084 LEFT JOIN civicrm_case
3085 ON (civicrm_case_contact.case_id = civicrm_case.id
3086 AND civicrm_case.is_deleted = 0 )
3087 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3088 // search tag in activities
3089 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
3090 $this->_tables[$etActTable] = $this->_whereTables[$etActTable]
3091 = " LEFT JOIN civicrm_activity_contact
3092 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3093 LEFT JOIN civicrm_activity
3094 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3095 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3096 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3097
3098 // CRM-10338
3099 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3100 $this->_where[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3101 }
3102 else {
3103 $this->_where[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3104 }
3105 $this->_qill[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
3106 }
3107 else {
3108 $this->_tables[$etTable] = $this->_whereTables[$etTable]
3109 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3110
3111 // CRM-10338
3112 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3113 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3114 $op = str_replace('EMPTY', 'NULL', $op);
3115 $this->_where[$grouping][] = "{$etTable}.tag_id $op";
3116 }
3117 else {
3118 $this->_where[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
3119 }
3120 $this->_qill[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $names;
3121 }
3122
3123 }
3124
3125 /**
3126 * Where/qill clause for notes
3127 *
3128 * @param $values
3129 *
3130 * @return void
3131 */
3132 public function notes(&$values) {
3133 list($name, $op, $value, $grouping, $wildcard) = $values;
3134
3135 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3136 $noteOption = CRM_Utils_Array::value('2', $noteOptionValues, '6');
3137 $noteOption = ($name == 'note_body') ? 2 : (($name == 'note_subject') ? 3 : $noteOption);
3138
3139 $this->_useDistinct = TRUE;
3140
3141 $this->_tables['civicrm_note'] = $this->_whereTables['civicrm_note']
3142 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3143
3144 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
3145 $n = trim($value);
3146 $value = $strtolower(CRM_Core_DAO::escapeString($n));
3147 if ($wildcard || $op == 'LIKE') {
3148 if (strpos($value, '%') === FALSE) {
3149 $value = "%$value%";
3150 }
3151 $op = 'LIKE';
3152 }
3153 elseif ($op == 'IS NULL' || $op == 'IS NOT NULL') {
3154 $value = NULL;
3155 }
3156
3157 $label = NULL;
3158 $clauses = array();
3159 if ($noteOption % 2 == 0) {
3160 $clauses[] = self::buildClause('civicrm_note.note', $op, $value, 'String');
3161 $label = ts('Note: Body Only');
3162 }
3163 if ($noteOption % 3 == 0) {
3164 $clauses[] = self::buildClause('civicrm_note.subject', $op, $value, 'String');
3165 $label = $label ? ts('Note: Body and Subject') : ts('Note: Subject Only');
3166 }
3167 $this->_where[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3168 $this->_qill[$grouping][] = $label . " $op - '$n'";
3169 }
3170
3171 /**
3172 * @param string $name
3173 * @param $op
3174 * @param $grouping
3175 *
3176 * @return bool
3177 */
3178 public function nameNullOrEmptyOp($name, $op, $grouping) {
3179 switch ($op) {
3180 case 'IS NULL':
3181 case 'IS NOT NULL':
3182 $this->_where[$grouping][] = "contact_a.$name $op";
3183 $this->_qill[$grouping][] = ts('Name') . ' ' . $op;
3184 return TRUE;
3185
3186 case 'IS EMPTY':
3187 $this->_where[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3188 $this->_qill[$grouping][] = ts('Name') . ' ' . $op;
3189 return TRUE;
3190
3191 case 'IS NOT EMPTY':
3192 $this->_where[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3193 $this->_qill[$grouping][] = ts('Name') . ' ' . $op;
3194 return TRUE;
3195
3196 default:
3197 return FALSE;
3198 }
3199 }
3200
3201 /**
3202 * Where / qill clause for sort_name
3203 *
3204 * @param $values
3205 *
3206 * @return void
3207 */
3208 public function sortName(&$values) {
3209 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3210
3211 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3212 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3213 return;
3214 }
3215
3216 $input = $value = trim($value);
3217
3218 if (!strlen($value)) {
3219 return;
3220 }
3221
3222 $config = CRM_Core_Config::singleton();
3223
3224 $sub = array();
3225
3226 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3227 $subGlue = ' OR ';
3228
3229 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
3230
3231 $firstChar = substr($value, 0, 1);
3232 $lastChar = substr($value, -1, 1);
3233 $quotes = array("'", '"');
3234 // If string is quoted, strip quotes and otherwise don't alter it
3235 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3236 $value = trim($value, implode('', $quotes));
3237 }
3238 // Replace spaces with wildcards for a LIKE operation
3239 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3240 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3241 $value = str_replace(' ', '%', $value);
3242 }
3243 $value = $strtolower(CRM_Core_DAO::escapeString(trim($value)));
3244 if (strlen($value)) {
3245 $fieldsub = array();
3246 if ($wildcard && $op == 'LIKE') {
3247 if ($config->includeWildCardInName) {
3248 $value = "'%$value%'";
3249 }
3250 else {
3251 $value = "'$value%'";
3252 }
3253 $op = 'LIKE';
3254 }
3255 else {
3256 $value = "'$value'";
3257 }
3258 if ($fieldName == 'sort_name') {
3259 $wc = self::caseImportant($op) ? "LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3260 }
3261 else {
3262 $wc = self::caseImportant($op) ? "LOWER(contact_a.display_name)" : "contact_a.display_name";
3263 }
3264 $fieldsub[] = " ( $wc $op $value )";
3265 if ($config->includeNickNameInName) {
3266 $wc = self::caseImportant($op) ? "LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3267 $fieldsub[] = " ( $wc $op $value )";
3268 }
3269 if ($config->includeEmailInName) {
3270 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3271 }
3272 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3273 }
3274
3275 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3276
3277 $this->_where[$grouping][] = $sub;
3278 if ($config->includeEmailInName) {
3279 $this->_tables['civicrm_email'] = $this->_whereTables['civicrm_email'] = 1;
3280 $this->_qill[$grouping][] = ts('Name or Email') . " $op - '$input'";
3281 }
3282 else {
3283 $this->_qill[$grouping][] = ts('Name') . " $op - '$input'";
3284 }
3285 }
3286
3287 /**
3288 * Where/qill clause for greeting fields.
3289 *
3290 * @param array $values
3291 */
3292 public function greetings(&$values) {
3293 list($name, $op, $value, $grouping, $wildcard) = $values;
3294 $name .= '_display';
3295
3296 $this->_qill[$grouping][] = ts('Greeting %1 %2', array(1 => $op, 2 => $value));
3297 $this->_where[$grouping][] = self::buildClause("contact_a.{$name}", 'LIKE', "$value", 'String');
3298 }
3299
3300 /**
3301 * Where / qill clause for email
3302 *
3303 * @param $values
3304 *
3305 * @return void
3306 */
3307 public function email(&$values) {
3308 list($name, $op, $value, $grouping, $wildcard) = $values;
3309
3310 $n = trim($value);
3311 if ($n) {
3312 $config = CRM_Core_Config::singleton();
3313
3314 if (substr($n, 0, 1) == '"' &&
3315 substr($n, -1, 1) == '"'
3316 ) {
3317 $n = substr($n, 1, -1);
3318 $value = strtolower(CRM_Core_DAO::escapeString($n));
3319 $value = "'$value'";
3320 $op = '=';
3321 }
3322 else {
3323 $value = strtolower($n);
3324 if ($wildcard) {
3325 if (strpos($value, '%') === FALSE) {
3326 $value = "%{$value}%";
3327 }
3328 $op = 'LIKE';
3329 }
3330 }
3331 $this->_qill[$grouping][] = ts('Email') . " $op '$n'";
3332 $this->_where[$grouping][] = self::buildClause('civicrm_email.email', $op, $value, 'String');
3333 }
3334 else {
3335 $this->_qill[$grouping][] = ts('Email') . " $op ";
3336 $this->_where[$grouping][] = self::buildClause('civicrm_email.email', $op, NULL, 'String');
3337 }
3338
3339 $this->_tables['civicrm_email'] = $this->_whereTables['civicrm_email'] = 1;
3340 }
3341
3342 /**
3343 * Where / qill clause for phone number
3344 *
3345 * @param $values
3346 *
3347 * @return void
3348 */
3349 public function phone_numeric(&$values) {
3350 list($name, $op, $value, $grouping, $wildcard) = $values;
3351 // Strip non-numeric characters; allow wildcards
3352 $number = preg_replace('/[^\d%]/', '', $value);
3353 if ($number) {
3354 if (strpos($number, '%') === FALSE) {
3355 $number = "%$number%";
3356 }
3357
3358 $this->_qill[$grouping][] = ts('Phone number contains') . " $number";
3359 $this->_where[$grouping][] = self::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3360 $this->_tables['civicrm_phone'] = $this->_whereTables['civicrm_phone'] = 1;
3361 }
3362 }
3363
3364 /**
3365 * Where / qill clause for phone type/location
3366 *
3367 * @param $values
3368 *
3369 * @return void
3370 */
3371 public function phone_option_group($values) {
3372 list($name, $op, $value, $grouping, $wildcard) = $values;
3373 $option = ($name == 'phone_phone_type_id' ? 'phone_type_id' : 'location_type_id');
3374 $options = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', $option);
3375 $optionName = $options[$value];
3376 $this->_qill[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ? ts('type') : ('location')) . " $op $optionName";
3377 $this->_where[$grouping][] = self::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3378 $this->_tables['civicrm_phone'] = $this->_whereTables['civicrm_phone'] = 1;
3379 }
3380
3381 /**
3382 * Where / qill clause for street_address
3383 *
3384 * @param $values
3385 *
3386 * @return void
3387 */
3388 public function street_address(&$values) {
3389 list($name, $op, $value, $grouping, $wildcard) = $values;
3390
3391 if (!$op) {
3392 $op = 'LIKE';
3393 }
3394
3395 $n = trim($value);
3396
3397 if ($n) {
3398 $value = strtolower($n);
3399 if (strpos($value, '%') === FALSE) {
3400 // only add wild card if not there
3401 $value = "%{$value}%";
3402 }
3403 $op = 'LIKE';
3404 $this->_where[$grouping][] = self::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3405 $this->_qill[$grouping][] = ts('Street') . " $op '$n'";
3406 }
3407 else {
3408 $this->_where[$grouping][] = self::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3409 $this->_qill[$grouping][] = ts('Street') . " $op ";
3410 }
3411
3412 $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1;
3413 }
3414
3415 /**
3416 * Where / qill clause for street_unit
3417 *
3418 * @param $values
3419 *
3420 * @return void
3421 */
3422 public function street_number(&$values) {
3423 list($name, $op, $value, $grouping, $wildcard) = $values;
3424
3425 if (!$op) {
3426 $op = '=';
3427 }
3428
3429 $n = trim($value);
3430
3431 if (strtolower($n) == 'odd') {
3432 $this->_where[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3433 $this->_qill[$grouping][] = ts('Street Number is odd');
3434 }
3435 elseif (strtolower($n) == 'even') {
3436 $this->_where[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3437 $this->_qill[$grouping][] = ts('Street Number is even');
3438 }
3439 else {
3440 $value = strtolower($n);
3441
3442 $this->_where[$grouping][] = self::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3443 $this->_qill[$grouping][] = ts('Street Number') . " $op '$n'";
3444 }
3445
3446 $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1;
3447 }
3448
3449 /**
3450 * Where / qill clause for sorting by character
3451 *
3452 * @param $values
3453 *
3454 * @return void
3455 */
3456 public function sortByCharacter(&$values) {
3457 list($name, $op, $value, $grouping, $wildcard) = $values;
3458
3459 $name = trim($value);
3460 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO::escapeWildCardString($name)) . "%'";
3461 $this->_where[$grouping][] = $cond;
3462 $this->_qill[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3463 }
3464
3465 /**
3466 * Where / qill clause for including contact ids
3467 *
3468 * @return void
3469 */
3470 public function includeContactIDs() {
3471 if (!$this->_includeContactIds || empty($this->_params)) {
3472 return;
3473 }
3474
3475 $contactIds = array();
3476 foreach ($this->_params as $id => $values) {
3477 if (substr($values[0], 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
3478 $contactIds[] = substr($values[0], CRM_Core_Form::CB_PREFIX_LEN);
3479 }
3480 }
3481 if (!empty($contactIds)) {
3482 $this->_where[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3483 }
3484 }
3485
3486 /**
3487 * Where / qill clause for postal code
3488 *
3489 * @param $values
3490 *
3491 * @return void
3492 */
3493 public function postalCode(&$values) {
3494 // skip if the fields dont have anything to do with postal_code
3495 if (empty($this->_fields['postal_code'])) {
3496 return;
3497 }
3498
3499 list($name, $op, $value, $grouping, $wildcard) = $values;
3500
3501 // Handle numeric postal code range searches properly by casting the column as numeric
3502 if (is_numeric($value)) {
3503 $field = 'ROUND(civicrm_address.postal_code)';
3504 $val = CRM_Utils_Type::escape($value, 'Integer');
3505 }
3506 else {
3507 $field = 'civicrm_address.postal_code';
3508 $val = CRM_Utils_Type::escape($value, 'String');
3509 }
3510
3511 $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1;
3512
3513 if ($name == 'postal_code') {
3514 $this->_where[$grouping][] = self::buildClause($field, $op, $val, 'String');
3515 $this->_qill[$grouping][] = ts('Postal code') . " {$op} {$value}";
3516 }
3517 elseif ($name == 'postal_code_low') {
3518 $this->_where[$grouping][] = " ( $field >= '$val' ) ";
3519 $this->_qill[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3520 }
3521 elseif ($name == 'postal_code_high') {
3522 $this->_where[$grouping][] = " ( $field <= '$val' ) ";
3523 $this->_qill[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3524 }
3525 }
3526
3527 /**
3528 * Where / qill clause for location type
3529 *
3530 * @param $values
3531 * @param null $status
3532 *
3533 * @return void
3534 */
3535 public function locationType(&$values, $status = NULL) {
3536 list($name, $op, $value, $grouping, $wildcard) = $values;
3537
3538 if (is_array($value)) {
3539 $this->_where[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3540 $this->_tables['civicrm_address'] = 1;
3541 $this->_whereTables['civicrm_address'] = 1;
3542
3543 $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
3544 $names = array();
3545 foreach ($value as $id) {
3546 $names[] = $locationType[$id];
3547 }
3548
3549 $this->_primaryLocation = FALSE;
3550
3551 if (!$status) {
3552 $this->_qill[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3553 }
3554 else {
3555 return implode(' ' . ts('or') . ' ', $names);
3556 }
3557 }
3558 }
3559
3560 /**
3561 * @param $values
3562 * @param bool $fromStateProvince
3563 *
3564 * @return array|NULL
3565 */
3566 public function country(&$values, $fromStateProvince = TRUE) {
3567 list($name, $op, $value, $grouping, $wildcard) = $values;
3568
3569 if (!$fromStateProvince) {
3570 $stateValues = $this->getWhereValues('state_province', $grouping);
3571 if (!empty($stateValues)) {
3572 // return back to caller if there are state province values
3573 // since that handles this case
3574 return NULL;
3575 }
3576 }
3577
3578 $countryClause = $countryQill = NULL;
3579 if (
3580 $values &&
3581 !empty($value)
3582 ) {
3583
3584 $this->_tables['civicrm_address'] = 1;
3585 $this->_whereTables['civicrm_address'] = 1;
3586
3587 $countries = CRM_Core_PseudoConstant::country();
3588 if (is_numeric($value)) {
3589 $countryClause = self::buildClause(
3590 'civicrm_address.country_id',
3591 $op,
3592 $value,
3593 'Positive'
3594 );
3595 $countryName = $countries[(int ) $value];
3596 }
3597
3598 else {
3599 $intValues = self::parseSearchBuilderString($value);
3600 if ($intValues && ($op == 'IN' || $op == 'NOT IN')) {
3601 $countryClause = self::buildClause(
3602 'civicrm_address.country_id',
3603 $op,
3604 $intValues,
3605 'Positive'
3606 );
3607 $countryNames = array();
3608 foreach ($intValues as $v) {
3609 $countryNames[] = $countries[$v];
3610 }
3611 $countryName = implode(',', $countryNames);
3612 }
3613 else {
3614 $countries = CRM_Core_PseudoConstant::country();
3615 $intVal = CRM_Utils_Array::key($value, $countries);
3616 $countryClause = self::buildClause(
3617 'civicrm_address.country_id',
3618 $op,
3619 $intVal,
3620 'Integer'
3621 );
3622 $countryName = $value;
3623 }
3624 }
3625 $countryQill = ts('Country') . " {$op} '$countryName'";
3626
3627 if (!$fromStateProvince) {
3628 $this->_where[$grouping][] = $countryClause;
3629 $this->_qill[$grouping][] = $countryQill;
3630 }
3631 }
3632
3633 if ($fromStateProvince) {
3634 if (!empty($countryClause)) {
3635 return array(
3636 $countryClause,
3637 " ...AND... " . $countryQill,
3638 );
3639 }
3640 else {
3641 return array(NULL, NULL);
3642 }
3643 }
3644 }
3645
3646 /**
3647 * Where / qill clause for county (if present)
3648 *
3649 * @param $values
3650 * @param null $status
3651 *
3652 * @return void
3653 */
3654 public function county(&$values, $status = NULL) {
3655 list($name, $op, $value, $grouping, $wildcard) = $values;
3656
3657 if (!is_array($value)) {
3658 // force the county to be an array
3659 $value = array($value);
3660 }
3661
3662 // check if the values are ids OR names of the counties
3663 $inputFormat = 'id';
3664 foreach ($value as $v) {
3665 if (!is_numeric($v)) {
3666 $inputFormat = 'name';
3667 break;
3668 }
3669 }
3670 $names = array();
3671 if ($op == '=') {
3672 $op = 'IN';
3673 }
3674 elseif ($op == '!=') {
3675 $op = 'NOT IN';
3676 }
3677 else {
3678 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3679 $op = str_replace('EMPTY', 'NULL', $op);
3680 }
3681
3682 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3683 $clause = "civicrm_address.county_id $op";
3684 }
3685 elseif ($inputFormat == 'id') {
3686 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3687
3688 $county = CRM_Core_PseudoConstant::county();
3689 foreach ($value as $id) {
3690 $names[] = CRM_Utils_Array::value($id, $county);
3691 }
3692 }
3693 else {
3694 $inputClause = array();
3695 $county = CRM_Core_PseudoConstant::county();
3696 foreach ($value as $name) {
3697 $name = trim($name);
3698 $inputClause[] = CRM_Utils_Array::key($name, $county);
3699 }
3700 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3701 $names = $value;
3702 }
3703 $this->_tables['civicrm_address'] = 1;
3704 $this->_whereTables['civicrm_address'] = 1;
3705
3706 $this->_where[$grouping][] = $clause;
3707 if (!$status) {
3708 $this->_qill[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3709 }
3710 else {
3711 return implode(' ' . ts('or') . ' ', $names);
3712 }
3713 }
3714
3715 /**
3716 * Where / qill clause for state/province AND country (if present)
3717 *
3718 * @param $values
3719 * @param null $status
3720 *
3721 * @return void
3722 */
3723 public function stateProvince(&$values, $status = NULL) {
3724 list($name, $op, $value, $grouping, $wildcard) = $values;
3725
3726 // quick escape for IS NULL
3727 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3728 $value = NULL;
3729 }
3730 elseif (!is_array($value)) {
3731 // force the state to be an array
3732 // check if its in the mapper format!
3733 $values = self::parseSearchBuilderString($value);
3734 if (is_array($values)) {
3735 $value = $values;
3736 }
3737 else {
3738 $value = array($value);
3739 }
3740 }
3741
3742 // check if the values are ids OR names of the states
3743 $inputFormat = 'id';
3744 if ($value) {
3745 foreach ($value as $v) {
3746 if (!is_numeric($v)) {
3747 $inputFormat = 'name';
3748 break;
3749 }
3750 }
3751 }
3752
3753 $names = array();
3754 if ($op == '=') {
3755 $op = 'IN';
3756 }
3757 elseif ($op == '!=') {
3758 $op = 'NOT IN';
3759 }
3760 else {
3761 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3762 $op = str_replace('EMPTY', 'NULL', $op);
3763 }
3764 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3765 $stateClause = "civicrm_address.state_province_id $op";
3766 }
3767 elseif ($inputFormat == 'id') {
3768 if ($op != 'NOT IN') {
3769 $op = 'IN';
3770 }
3771 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
3772
3773 foreach ($value as $id) {
3774 $names[] = CRM_Core_PseudoConstant::stateProvince($id, FALSE);
3775 }
3776 }
3777 else {
3778 $inputClause = array();
3779 $stateProvince = CRM_Core_PseudoConstant::stateProvince();
3780 foreach ($value as $name) {
3781 $name = trim($name);
3782 $inputClause[] = CRM_Utils_Array::key($name, $stateProvince);
3783 }
3784 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
3785 $names = $value;
3786 }
3787 $this->_tables['civicrm_address'] = 1;
3788 $this->_whereTables['civicrm_address'] = 1;
3789
3790 $countryValues = $this->getWhereValues('country', $grouping);
3791 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3792
3793 if ($countryClause) {
3794 $clause = "( $stateClause AND $countryClause )";
3795 }
3796 else {
3797 $clause = $stateClause;
3798 }
3799
3800 $this->_where[$grouping][] = $clause;
3801 if (!$status) {
3802 $this->_qill[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3803 }
3804 else {
3805 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
3806 }
3807 }
3808
3809 /**
3810 * Where / qill clause for change log
3811 *
3812 * @param $values
3813 *
3814 * @return void
3815 */
3816 public function changeLog(&$values) {
3817 list($name, $op, $value, $grouping, $wildcard) = $values;
3818
3819 $targetName = $this->getWhereValues('changed_by', $grouping);
3820 if (!$targetName) {
3821 return;
3822 }
3823
3824 $name = trim($targetName[2]);
3825 $name = strtolower(CRM_Core_DAO::escapeString($name));
3826 $name = $targetName[4] ? "%$name%" : $name;
3827 $this->_where[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3828 $this->_tables['civicrm_log'] = $this->_whereTables['civicrm_log'] = 1;
3829 $this->_qill[$grouping][] = ts('Modified By') . " $name";
3830 }
3831
3832 /**
3833 * @param $values
3834 */
3835 public function modifiedDates($values) {
3836 $this->_useDistinct = TRUE;
3837
3838 // CRM-11281, default to added date if not set
3839 $fieldTitle = ts('Added Date');
3840 $fieldName = 'created_date';
3841 foreach (array_keys($this->_params) as $id) {
3842 if ($this->_params[$id][0] == 'log_date') {
3843 if ($this->_params[$id][2] == 2) {
3844 $fieldTitle = ts('Modified Date');
3845 $fieldName = 'modified_date';
3846 }
3847 }
3848 }
3849
3850 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3851
3852 self::$_openedPanes[ts('Change Log')] = TRUE;
3853 }
3854
3855 /**
3856 * @param $values
3857 */
3858 public function demographics(&$values) {
3859 list($name, $op, $value, $grouping, $wildcard) = $values;
3860
3861 if (($name == 'birth_date_low') || ($name == 'birth_date_high')) {
3862
3863 $this->dateQueryBuilder($values,
3864 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3865 );
3866 }
3867 elseif (($name == 'deceased_date_low') || ($name == 'deceased_date_high')) {
3868
3869 $this->dateQueryBuilder($values,
3870 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3871 );
3872 }
3873
3874 self::$_openedPanes[ts('Demographics')] = TRUE;
3875 }
3876
3877 /**
3878 * @param $values
3879 */
3880 public function privacy(&$values) {
3881 list($name, $op, $value, $grouping, $wildcard) = $values;
3882 //fixed for profile search listing CRM-4633
3883 if (strpbrk($value, "[")) {
3884 $value = "'{$value}'";
3885 $op = "!{$op}";
3886 $this->_where[$grouping][] = "contact_a.{$name} $op $value";
3887 }
3888 else {
3889 $this->_where[$grouping][] = "contact_a.{$name} $op $value";
3890 }
3891 $field = CRM_Utils_Array::value($name, $this->_fields);
3892 $title = $field ? $field['title'] : $name;
3893 $this->_qill[$grouping][] = "$title $op $value";
3894 }
3895
3896 /**
3897 * @param $values
3898 */
3899 public function privacyOptions($values) {
3900 list($name, $op, $value, $grouping, $wildcard) = $values;
3901
3902 if (empty($value) || !is_array($value)) {
3903 return;
3904 }
3905
3906 // get the operator and toggle values
3907 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3908 $operator = 'OR';
3909 if ($opValues &&
3910 strtolower($opValues[2] == 'AND')
3911 ) {
3912 $operator = 'AND';
3913 }
3914
3915 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3916 $compareOP = '!';
3917 if ($toggleValues &&
3918 $toggleValues[2] == 2
3919 ) {
3920 $compareOP = '';
3921 }
3922
3923 $clauses = array();
3924 $qill = array();
3925 foreach ($value as $dontCare => $pOption) {
3926 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
3927 $field = CRM_Utils_Array::value($pOption, $this->_fields);
3928 $title = $field ? $field['title'] : $pOption;
3929 $qill[] = " $title = 1 ";
3930 }
3931
3932 $this->_where[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
3933 $this->_qill[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
3934 }
3935
3936 /**
3937 * @param $values
3938 */
3939 public function preferredCommunication(&$values) {
3940 list($name, $op, $value, $grouping, $wildcard) = $values;
3941
3942 $pref = array();
3943 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3944 $value = NULL;
3945 }
3946 elseif (!is_array($value)) {
3947 $v = array();
3948 $value = trim($value, ' ()');
3949 if (strpos($value, CRM_Core_DAO::VALUE_SEPARATOR) !== FALSE) {
3950 $v = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
3951 }
3952 else {
3953 $v = explode(",", $value);
3954 }
3955
3956 foreach ($v as $item) {
3957 if ($item) {
3958 $pref[] = $item;
3959 }
3960 }
3961 }
3962 else {
3963 foreach ($value as $key => $checked) {
3964 if ($checked) {
3965 $pref[] = $key;
3966 }
3967 }
3968 }
3969
3970 $commPref = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
3971
3972 $sqlValue = array();
3973 $showValue = array();
3974 $sql = "contact_a.preferred_communication_method";
3975 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3976 $sqlValue[] = "{$sql} {$op}";
3977 }
3978 else {
3979 foreach ($pref as $val) {
3980 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO::VALUE_SEPARATOR . $val . CRM_Core_DAO::VALUE_SEPARATOR . "%' ) ";
3981 $showValue[] = $commPref[$val];
3982 }
3983 }
3984 $this->_where[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
3985 $this->_qill[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
3986 }
3987
3988 /**
3989 * Where / qill clause for relationship
3990 *
3991 * @param $values
3992 *
3993 * @return void
3994 */
3995 public function relationship(&$values) {
3996 list($name, $op, $value, $grouping, $wildcard) = $values;
3997 if ($this->_relationshipValuesAdded) {
3998 return;
3999 }
4000 // also get values array for relation_target_name
4001 // for relationship search we always do wildcard
4002 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4003 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4004 $relStatus = $this->getWhereValues('relation_status', $grouping);
4005 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4006 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4007
4008 $nameClause = $name = NULL;
4009 if ($targetName) {
4010 $name = trim($targetName[2]);
4011 if (substr($name, 0, 1) == '"' &&
4012 substr($name, -1, 1) == '"'
4013 ) {
4014 $name = substr($name, 1, -1);
4015 $name = strtolower(CRM_Core_DAO::escapeString($name));
4016 $nameClause = "= '$name'";
4017 }
4018 else {
4019 $name = strtolower(CRM_Core_DAO::escapeString($name));
4020 $nameClause = "LIKE '%{$name}%'";
4021 }
4022 }
4023
4024 $rTypeValues = array();
4025 if (!empty($relationType)) {
4026 $rel = explode('_', $relationType[2]);
4027 self::$_relType = $rel[1];
4028 $params = array('id' => $rel[0]);
4029 $rType = CRM_Contact_BAO_RelationshipType::retrieve($params, $rTypeValues);
4030 }
4031 if (!empty($rTypeValues) && $rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
4032 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4033 //@todo unless we are dealing with a target group
4034 self::$_relType = 'reciprocal';
4035 }
4036 // if we are creating a temp table we build our own where for the relationship table
4037 $relationshipTempTable = NULL;
4038 if (self::$_relType == 'reciprocal' && empty($targetGroup)) {
4039 $where = array();
4040 self::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO::createTempTableName('civicrm_rel');
4041 if ($nameClause) {
4042 $where[$grouping][] = " sort_name $nameClause ";
4043 }
4044 }
4045 else {
4046 $where = &$this->_where;
4047 if ($nameClause) {
4048 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4049 }
4050 }
4051
4052 $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
4053 $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
4054 $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Household');
4055 $allRelationshipType = array();
4056 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
4057 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
4058
4059 if ($nameClause || !$targetGroup) {
4060 if (!empty($relationType)) {
4061 $this->_qill[$grouping][] = $allRelationshipType[$relationType[2]] . " $name";
4062 }
4063 else {
4064 $this->_qill[$grouping][] = $name;
4065 }
4066 }
4067
4068 //check to see if the target contact is in specified group
4069 if ($targetGroup) {
4070 //add contacts from static groups
4071 $this->_tables['civicrm_relationship_group_contact'] = $this->_whereTables['civicrm_relationship_group_contact']
4072 = " 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'";
4073 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4074 implode(",", $targetGroup[2]) . ") ) ";
4075
4076 //add contacts from saved searches
4077 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b", $op);
4078
4079 //set the group where clause
4080 if ($ssWhere) {
4081 $groupWhere[] = "( " . $ssWhere . " )";
4082 }
4083 $this->_where[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4084
4085 //Get the names of the target groups for the qill
4086 $groupNames = CRM_Core_PseudoConstant::group();
4087 $qillNames = array();
4088 foreach ($targetGroup[2] as $groupId) {
4089 if (array_key_exists($groupId, $groupNames)) {
4090 $qillNames[] = $groupNames[$groupId];
4091 }
4092 }
4093 if (!empty($relationType)) {
4094 $this->_qill[$grouping][] = $allRelationshipType[$relationType[2]] . " ( " . implode(", ", $qillNames) . " )";
4095 }
4096 else {
4097 $this->_qill[$grouping][] = implode(", ", $qillNames);
4098 }
4099 }
4100
4101 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4102 $today = date('Ymd');
4103 //check for active, inactive and all relation status
4104 if ($relStatus[2] == 0) {
4105 $where[$grouping][] = "(
4106 civicrm_relationship.is_active = 1 AND
4107 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4108 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4109 )";
4110 $this->_qill[$grouping][] = ts('Relationship - Active and Current');
4111 }
4112 elseif ($relStatus[2] == 1) {
4113 $where[$grouping][] = "(
4114 civicrm_relationship.is_active = 0 OR
4115 civicrm_relationship.end_date < {$today} OR
4116 civicrm_relationship.start_date > {$today}
4117 )";
4118 $this->_qill[$grouping][] = ts('Relationship - Inactive or not Current');
4119 }
4120
4121 $onlyDeleted = 0;
4122 if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params)) {
4123 $onlyDeleted = 1;
4124 }
4125 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4126
4127 //check for permissioned, non-permissioned and all permissioned relations
4128 if ($relPermission[2] == 1) {
4129 $where[$grouping][] = "(
4130 civicrm_relationship.is_permission_a_b = 1
4131 )";
4132 $this->_qill[$grouping][] = ts('Relationship - Permissioned');
4133 }
4134 elseif ($relPermission[2] == 2) {
4135 //non-allowed permission relationship.
4136 $where[$grouping][] = "(
4137 civicrm_relationship.is_permission_a_b = 0
4138 )";
4139 $this->_qill[$grouping][] = ts('Relationship - Non-permissioned');
4140 }
4141
4142 $this->addRelationshipDateClauses($grouping, $where);
4143 if (!empty($relationType) && !empty($rType) && isset($rType->id)) {
4144 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id;
4145 }
4146 $this->_tables['civicrm_relationship'] = $this->_whereTables['civicrm_relationship'] = 1;
4147 $this->_useDistinct = TRUE;
4148 $this->_relationshipValuesAdded = TRUE;
4149 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4150 // join on that,
4151 // @todo creating a temp table could be expanded to group filter
4152 // as even creating a temp table of all relationships is much much more efficient than
4153 // an OR in the join
4154 if ($relationshipTempTable) {
4155 $whereClause = '';
4156 if (!empty($where[$grouping])) {
4157 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4158 $whereClause = str_replace('contact_b', 'c', $whereClause);
4159 }
4160 $sql = "
4161 CREATE TEMPORARY TABLE {$relationshipTempTable}
4162 (SELECT contact_id_b as contact_id, civicrm_relationship.id
4163 FROM civicrm_relationship
4164 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4165 $whereClause )
4166 UNION
4167 (SELECT contact_id_a as contact_id, civicrm_relationship.id
4168 FROM civicrm_relationship
4169 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4170 $whereClause )
4171 ";
4172 CRM_Core_DAO::executeQuery($sql);
4173 }
4174
4175 }
4176
4177 /**
4178 * Add start & end date criteria in
4179 * @param string $grouping
4180 * @param array $where
4181 * = array to add where clauses to, in case you are generating a temp table.
4182 * not the main query.
4183 */
4184 public function addRelationshipDateClauses($grouping, &$where) {
4185 $dateValues = array();
4186 $dateTypes = array(
4187 'start_date',
4188 'end_date',
4189 );
4190
4191 foreach ($dateTypes as $dateField) {
4192 $dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping);
4193 $dateValueHigh = $this->getWhereValues('relation_' . $dateField . '_high', $grouping);
4194 if (!empty($dateValueLow)) {
4195 $date = date('Ymd', strtotime($dateValueLow[2]));
4196 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4197 $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);
4198 }
4199 if (!empty($dateValueHigh)) {
4200 $date = date('Ymd', strtotime($dateValueHigh[2]));
4201 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4202 $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);
4203 }
4204 }
4205 }
4206
4207 /**
4208 * Default set of return properties.
4209 *
4210 * @param int $mode
4211 *
4212 * @return array
4213 * derault return properties
4214 */
4215 public static function &defaultReturnProperties($mode = 1) {
4216 if (!isset(self::$_defaultReturnProperties)) {
4217 self::$_defaultReturnProperties = array();
4218 }
4219
4220 if (!isset(self::$_defaultReturnProperties[$mode])) {
4221 // add activity return properties
4222 if ($mode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
4223 self::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query::defaultReturnProperties($mode, FALSE);
4224 }
4225 else {
4226 self::$_defaultReturnProperties[$mode] = CRM_Core_Component::defaultReturnProperties($mode, FALSE);
4227 }
4228
4229 if (empty(self::$_defaultReturnProperties[$mode])) {
4230 self::$_defaultReturnProperties[$mode] = array(
4231 'home_URL' => 1,
4232 'image_URL' => 1,
4233 'legal_identifier' => 1,
4234 'external_identifier' => 1,
4235 'contact_type' => 1,
4236 'contact_sub_type' => 1,
4237 'sort_name' => 1,
4238 'display_name' => 1,
4239 'preferred_mail_format' => 1,
4240 'nick_name' => 1,
4241 'first_name' => 1,
4242 'middle_name' => 1,
4243 'last_name' => 1,
4244 'prefix_id' => 1,
4245 'suffix_id' => 1,
4246 'formal_title' => 1,
4247 'communication_style_id' => 1,
4248 'birth_date' => 1,
4249 'gender_id' => 1,
4250 'street_address' => 1,
4251 'supplemental_address_1' => 1,
4252 'supplemental_address_2' => 1,
4253 'city' => 1,
4254 'postal_code' => 1,
4255 'postal_code_suffix' => 1,
4256 'state_province' => 1,
4257 'country' => 1,
4258 'world_region' => 1,
4259 'geo_code_1' => 1,
4260 'geo_code_2' => 1,
4261 'email' => 1,
4262 'on_hold' => 1,
4263 'phone' => 1,
4264 'im' => 1,
4265 'household_name' => 1,
4266 'organization_name' => 1,
4267 'deceased_date' => 1,
4268 'is_deceased' => 1,
4269 'job_title' => 1,
4270 'legal_name' => 1,
4271 'sic_code' => 1,
4272 'current_employer' => 1,
4273 // FIXME: should we use defaultHierReturnProperties() for the below?
4274 'do_not_email' => 1,
4275 'do_not_mail' => 1,
4276 'do_not_sms' => 1,
4277 'do_not_phone' => 1,
4278 'do_not_trade' => 1,
4279 'is_opt_out' => 1,
4280 'contact_is_deleted' => 1,
4281 'preferred_communication_method' => 1,
4282 'preferred_language' => 1,
4283 );
4284 }
4285 }
4286 return self::$_defaultReturnProperties[$mode];
4287 }
4288
4289 /**
4290 * Get primary condition for a sql clause.
4291 *
4292 * @param int $value
4293 *
4294 * @return string|NULL
4295 */
4296 public static function getPrimaryCondition($value) {
4297 if (is_numeric($value)) {
4298 $value = (int ) $value;
4299 return ($value == 1) ? 'is_primary = 1' : 'is_primary = 0';
4300 }
4301 return NULL;
4302 }
4303
4304 /**
4305 * Wrapper for a simple search query.
4306 *
4307 * @param array $params
4308 * @param array $returnProperties
4309 * @param bool $count
4310 *
4311 * @return string
4312 */
4313 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4314 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4315 list($select, $from, $where, $having) = $query->query();
4316
4317 return "$select $from $where $having";
4318 }
4319
4320 /**
4321 * These are stub comments as this function needs more explanation - particularly in terms of how it
4322 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4323 *
4324 * This function was originally written as a wrapper for the api query but is called from multiple places
4325 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4326 * but it is unclear as to whehter that is historical or there is a reason
4327 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4328 *
4329 * @param array $params
4330 * @param array $returnProperties
4331 * @param null $fields
4332 * @param string $sort
4333 * @param int $offset
4334 * @param int $row_count
4335 * @param bool $smartGroupCache
4336 * ?? update smart group cache?.
4337 * @param bool $count
4338 * Return count obnly.
4339 * @param bool $skipPermissions
4340 * Should permissions be ignored or should the logged in user's permissions be applied.
4341 *
4342 *
4343 * @return array
4344 */
4345 public static function apiQuery(
4346 $params = NULL,
4347 $returnProperties = NULL,
4348 $fields = NULL,
4349 $sort = NULL,
4350 $offset = 0,
4351 $row_count = 25,
4352 $smartGroupCache = TRUE,
4353 $count = FALSE,
4354 $skipPermissions = TRUE
4355 ) {
4356
4357 $query = new CRM_Contact_BAO_Query(
4358 $params, $returnProperties,
4359 NULL, TRUE, FALSE, 1,
4360 $skipPermissions,
4361 TRUE, $smartGroupCache
4362 );
4363
4364 //this should add a check for view deleted if permissions are enabled
4365 if ($skipPermissions) {
4366 $query->_skipDeleteClause = TRUE;
4367 }
4368 $query->generatePermissionClause(FALSE, $count);
4369
4370 // note : this modifies _fromClause and _simpleFromClause
4371 $query->includePseudoFieldsJoin($sort);
4372
4373 list($select, $from, $where, $having) = $query->query($count);
4374
4375 $options = $query->_options;
4376 if (!empty($query->_permissionWhereClause)) {
4377 if (empty($where)) {
4378 $where = "WHERE $query->_permissionWhereClause";
4379 }
4380 else {
4381 $where = "$where AND $query->_permissionWhereClause";
4382 }
4383 }
4384
4385 $sql = "$select $from $where $having";
4386
4387 // add group by
4388 if ($query->_useGroupBy) {
4389 $sql .= ' GROUP BY contact_a.id';
4390 }
4391 if (!empty($sort)) {
4392 $sort = CRM_Utils_Type::escape($sort, 'String');
4393 $sql .= " ORDER BY $sort ";
4394 }
4395 if ($row_count > 0 && $offset >= 0) {
4396 $offset = CRM_Utils_Type::escape($offset, 'Int');
4397 $rowCount = CRM_Utils_Type::escape($row_count, 'Int');
4398 $sql .= " LIMIT $offset, $row_count ";
4399 }
4400
4401 $dao = CRM_Core_DAO::executeQuery($sql);
4402
4403 $values = array();
4404 while ($dao->fetch()) {
4405 if ($count) {
4406 $noRows = $dao->rowCount;
4407 $dao->free();
4408 return array($noRows, NULL);
4409 }
4410 $val = $query->store($dao);
4411 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
4412
4413 if (!empty($convertedVals)) {
4414 $val = array_replace_recursive($val, $convertedVals);
4415 }
4416 $values[$dao->contact_id] = $val;
4417 }
4418 $dao->free();
4419 return array($values, $options);
4420 }
4421
4422 /**
4423 * Create and query the db for an contact search.
4424 *
4425 * @param int $offset
4426 * The offset for the query.
4427 * @param int $rowCount
4428 * The number of rows to return.
4429 * @param string $sort
4430 * The order by string.
4431 * @param bool $count
4432 * Is this a count only query ?.
4433 * @param bool $includeContactIds
4434 * Should we include contact ids?.
4435 * @param bool $sortByChar
4436 * If true returns the distinct array of first characters for search results.
4437 * @param bool $groupContacts
4438 * If true, return only the contact ids.
4439 * @param bool $returnQuery
4440 * Should we return the query as a string.
4441 * @param string $additionalWhereClause
4442 * If the caller wants to further restrict the search (used for components).
4443 * @param null $sortOrder
4444 * @param string $additionalFromClause
4445 * Should be clause with proper joins, effective to reduce where clause load.
4446 *
4447 * @param bool $skipOrderAndLimit
4448 *
4449 * @return CRM_Core_DAO
4450 */
4451 public function searchQuery(
4452 $offset = 0, $rowCount = 0, $sort = NULL,
4453 $count = FALSE, $includeContactIds = FALSE,
4454 $sortByChar = FALSE, $groupContacts = FALSE,
4455 $returnQuery = FALSE,
4456 $additionalWhereClause = NULL, $sortOrder = NULL,
4457 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4458 ) {
4459
4460 if ($includeContactIds) {
4461 $this->_includeContactIds = TRUE;
4462 $this->_whereClause = $this->whereClause();
4463 }
4464
4465 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params);
4466
4467 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
4468 // and that contact happens to be deleted, set $onlyDeleted to true
4469 foreach ($this->_params as $values) {
4470 $name = CRM_Utils_Array::value(0, $values);
4471 $op = CRM_Utils_Array::value(1, $values);
4472 $value = CRM_Utils_Array::value(2, $values);
4473 if ($name == 'contact_id' and $op == '=') {
4474 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4475 $onlyDeleted = TRUE;
4476 }
4477 break;
4478 }
4479 }
4480
4481 // building the query string
4482 $groupBy = NULL;
4483 if (!$count) {
4484 if (isset($this->_groupByComponentClause)) {
4485 $groupBy = $this->_groupByComponentClause;
4486 }
4487 elseif ($this->_useGroupBy) {
4488 $groupBy = ' GROUP BY contact_a.id';
4489 }
4490 }
4491 if ($this->_mode & CRM_Contact_BAO_Query::MODE_ACTIVITY && (!$count)) {
4492 $groupBy = 'GROUP BY civicrm_activity.id ';
4493 }
4494
4495 $order = $orderBy = $limit = '';
4496 if (!$count) {
4497 $config = CRM_Core_Config::singleton();
4498 if ($config->includeOrderByClause ||
4499 isset($this->_distinctComponentClause)
4500 ) {
4501 if ($sort) {
4502 if (is_string($sort)) {
4503 $orderBy = $sort;
4504 }
4505 else {
4506 $orderBy = trim($sort->orderBy());
4507 }
4508 if (!empty($orderBy)) {
4509 // this is special case while searching for
4510 // change log CRM-1718
4511 if (preg_match('/sort_name/i', $orderBy)) {
4512 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4513 }
4514
4515 $orderBy = CRM_Utils_Type::escape($orderBy, 'String');
4516 $order = " ORDER BY $orderBy";
4517
4518 if ($sortOrder) {
4519 $sortOrder = CRM_Utils_Type::escape($sortOrder, 'String');
4520 $order .= " $sortOrder";
4521 }
4522
4523 // always add contact_a.id to the ORDER clause
4524 // so the order is deterministic
4525 if (strpos('contact_a.id', $order) === FALSE) {
4526 $order .= ", contact_a.id";
4527 }
4528 }
4529 }
4530 elseif ($sortByChar) {
4531 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4532 }
4533 else {
4534 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4535 }
4536 }
4537
4538 // hack for order clause
4539 if ($order) {
4540 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4541 $fieldOrder = explode(' ', $fieldStr);
4542 $field = $fieldOrder[0];
4543
4544 if ($field) {
4545 switch ($field) {
4546 case 'city':
4547 case 'postal_code':
4548 $this->_whereTables["civicrm_address"] = 1;
4549 $order = str_replace($field, "civicrm_address.{$field}", $order);
4550 break;
4551
4552 case 'country':
4553 case 'state_province':
4554 $this->_whereTables["civicrm_{$field}"] = 1;
4555 $order = str_replace($field, "civicrm_{$field}.name", $order);
4556 break;
4557
4558 case 'email':
4559 $this->_whereTables["civicrm_email"] = 1;
4560 $order = str_replace($field, "civicrm_email.{$field}", $order);
4561 break;
4562
4563 default:
4564 //CRM-12565 add "`" around $field if it is a pseudo constant
4565 foreach ($this->_pseudoConstantsSelect as $key => $value) {
4566 if (!empty($value['element']) && $value['element'] == $field) {
4567 $order = str_replace($field, "`{$field}`", $order);
4568 }
4569 }
4570 }
4571 $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode);
4572 $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode);
4573 }
4574 }
4575
4576 if ($rowCount > 0 && $offset >= 0) {
4577 $offset = CRM_Utils_Type::escape($offset, 'Int');
4578 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
4579 $limit = " LIMIT $offset, $rowCount ";
4580 }
4581 }
4582
4583 // CRM-15231
4584 $this->_sort = $sort;
4585
4586 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
4587
4588 if ($additionalWhereClause) {
4589 $where = $where . ' AND ' . $additionalWhereClause;
4590 }
4591
4592 //additional from clause should be w/ proper joins.
4593 if ($additionalFromClause) {
4594 $from .= "\n" . $additionalFromClause;
4595 }
4596
4597 // if we are doing a transform, do it here
4598 // use the $from, $where and $having to get the contact ID
4599 if ($this->_displayRelationshipType) {
4600 $this->filterRelatedContacts($from, $where, $having);
4601 }
4602
4603 if ($skipOrderAndLimit) {
4604 $query = "$select $from $where $having $groupBy";
4605 }
4606 else {
4607 $query = "$select $from $where $having $groupBy $order $limit";
4608 }
4609
4610 if ($returnQuery) {
4611 return $query;
4612 }
4613 if ($count) {
4614 return CRM_Core_DAO::singleValueQuery($query);
4615 }
4616
4617 $dao = CRM_Core_DAO::executeQuery($query);
4618 if ($groupContacts) {
4619 $ids = array();
4620 while ($dao->fetch()) {
4621 $ids[] = $dao->id;
4622 }
4623 return implode(',', $ids);
4624 }
4625
4626 return $dao;
4627 }
4628
4629 /**
4630 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4631 *
4632 * @param string $cacheKey
4633 * @param int $offset
4634 * @param int $rowCount
4635 * @param bool $includeContactIds
4636 * @return CRM_Core_DAO
4637 */
4638 public function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4639 $this->_includeContactIds = $includeContactIds;
4640 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params);
4641 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
4642 $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);
4643 $order = " ORDER BY pnc.id";
4644 $groupBy = " GROUP BY contact_a.id";
4645 $limit = " LIMIT $offset, $rowCount";
4646 $query = "$select $from $where $groupBy $order $limit";
4647
4648 return CRM_Core_DAO::executeQuery($query);
4649 }
4650
4651 /**
4652 * Populate $this->_permissionWhereClause with permission related clause and update other
4653 * query related properties.
4654 *
4655 * Function calls ACL permission class and hooks to filter the query appropriately
4656 *
4657 * Note that these 2 params were in the code when extracted from another function
4658 * and a second round extraction would be to make them properties of the class
4659 *
4660 * @param bool $onlyDeleted
4661 * Only get deleted contacts.
4662 * @param bool $count
4663 * Return Count only.
4664 */
4665 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4666 if (!$this->_skipPermission) {
4667 $this->_permissionWhereClause = CRM_ACL_API::whereClause(
4668 CRM_Core_Permission::VIEW,
4669 $this->_tables,
4670 $this->_whereTables,
4671 NULL,
4672 $onlyDeleted,
4673 $this->_skipDeleteClause
4674 );
4675
4676 // regenerate fromClause since permission might have added tables
4677 if ($this->_permissionWhereClause) {
4678 //fix for row count in qill (in contribute/membership find)
4679 if (!$count) {
4680 $this->_useDistinct = TRUE;
4681 }
4682 //CRM-15231
4683 $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode);
4684 $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode);
4685 // note : this modifies _fromClause and _simpleFromClause
4686 $this->includePseudoFieldsJoin($this->_sort);
4687 }
4688 }
4689 else {
4690 // add delete clause if needed even if we are skipping permission
4691 // CRM-7639
4692 if (!$this->_skipDeleteClause) {
4693 if (CRM_Core_Permission::check('access deleted contacts') and $onlyDeleted) {
4694 $this->_permissionWhereClause = '(contact_a.is_deleted)';
4695 }
4696 else {
4697 // CRM-6181
4698 $this->_permissionWhereClause = '(contact_a.is_deleted = 0)';
4699 }
4700 }
4701 }
4702 }
4703
4704 /**
4705 * @param $val
4706 */
4707 public function setSkipPermission($val) {
4708 $this->_skipPermission = $val;
4709 }
4710
4711 /**
4712 * @param null $context
4713 *
4714 * @return array
4715 */
4716 public function &summaryContribution($context = NULL) {
4717 list($innerselect, $from, $where, $having) = $this->query(TRUE);
4718
4719 // hack $select
4720 $select = "
4721 SELECT COUNT( conts.total_amount ) as total_count,
4722 SUM( conts.total_amount ) as total_amount,
4723 AVG( conts.total_amount ) as total_avg,
4724 conts.currency as currency";
4725 if ($this->_permissionWhereClause) {
4726 $where .= " AND " . $this->_permissionWhereClause;
4727 }
4728 if ($context == 'search') {
4729 $where .= " AND contact_a.is_deleted = 0 ";
4730 }
4731
4732 // make sure contribution is completed - CRM-4989
4733 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4734
4735 $summary = array();
4736 $summary['total'] = array();
4737 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4738
4739 $query = "$select FROM (
4740 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $completedWhere
4741 GROUP BY civicrm_contribution.id
4742 ) as conts
4743 GROUP BY currency";
4744
4745 $dao = CRM_Core_DAO::executeQuery($query);
4746
4747 $summary['total']['count'] = 0;
4748 $summary['total']['amount'] = $summary['total']['avg'] = array();
4749 while ($dao->fetch()) {
4750 $summary['total']['count'] += $dao->total_count;
4751 $summary['total']['amount'][] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
4752 $summary['total']['avg'][] = CRM_Utils_Money::format($dao->total_avg, $dao->currency);
4753 }
4754 if (!empty($summary['total']['amount'])) {
4755 $summary['total']['amount'] = implode(',&nbsp;', $summary['total']['amount']);
4756 $summary['total']['avg'] = implode(',&nbsp;', $summary['total']['avg']);
4757 }
4758 else {
4759 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4760 }
4761
4762 // soft credit summary
4763 if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
4764 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
4765 $query = "
4766 $select FROM (
4767 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
4768 GROUP BY civicrm_contribution_soft.id
4769 ) as conts
4770 GROUP BY currency";
4771 $dao = CRM_Core_DAO::executeQuery($query);
4772 $summary['soft_credit']['count'] = 0;
4773 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
4774 while ($dao->fetch()) {
4775 $summary['soft_credit']['count'] += $dao->total_count;
4776 $summary['soft_credit']['amount'][] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
4777 $summary['soft_credit']['avg'][] = CRM_Utils_Money::format($dao->total_avg, $dao->currency);
4778 }
4779 if (!empty($summary['soft_credit']['amount'])) {
4780 $summary['soft_credit']['amount'] = implode(',&nbsp;', $summary['soft_credit']['amount']);
4781 $summary['soft_credit']['avg'] = implode(',&nbsp;', $summary['soft_credit']['avg']);
4782 }
4783 else {
4784 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
4785 }
4786 }
4787
4788 // hack $select
4789 //@todo - this could be one query using the IF in mysql - eg
4790 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
4791 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
4792 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
4793 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
4794 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
4795 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
4796 // FROM civicrm_contact contact_a
4797 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
4798 // WHERE ( ... where clause....
4799 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
4800 // ) as conts
4801
4802 $select = "
4803 SELECT COUNT( conts.total_amount ) as cancel_count,
4804 SUM( conts.total_amount ) as cancel_amount,
4805 AVG( conts.total_amount ) as cancel_avg,
4806 conts.currency as currency";
4807
4808 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4809 if ($context == 'search') {
4810 $where .= " AND contact_a.is_deleted = 0 ";
4811 }
4812
4813 $query = "$select FROM (
4814 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
4815 GROUP BY civicrm_contribution.id
4816 ) as conts
4817 GROUP BY currency";
4818
4819 $dao = CRM_Core_DAO::executeQuery($query);
4820
4821 if ($dao->N <= 1) {
4822 if ($dao->fetch()) {
4823 $summary['cancel']['count'] = $dao->cancel_count;
4824 $summary['cancel']['amount'] = $dao->cancel_amount;
4825 $summary['cancel']['avg'] = $dao->cancel_avg;
4826 }
4827 }
4828 else {
4829 $summary['cancel']['count'] = 0;
4830 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4831 while ($dao->fetch()) {
4832 $summary['cancel']['count'] += $dao->cancel_count;
4833 $summary['cancel']['amount'][] = CRM_Utils_Money::format($dao->cancel_amount, $dao->currency);
4834 $summary['cancel']['avg'][] = CRM_Utils_Money::format($dao->cancel_avg, $dao->currency);
4835 }
4836 $summary['cancel']['amount'] = implode(',&nbsp;', $summary['cancel']['amount']);
4837 $summary['cancel']['avg'] = implode(',&nbsp;', $summary['cancel']['avg']);
4838 }
4839
4840 return $summary;
4841 }
4842
4843 /**
4844 * Getter for the qill object.
4845 *
4846 * @return string
4847 */
4848 public function qill() {
4849 return $this->_qill;
4850 }
4851
4852 /**
4853 * Default set of return default hier return properties.
4854 *
4855 * @return array
4856 */
4857 public static function &defaultHierReturnProperties() {
4858 if (!isset(self::$_defaultHierReturnProperties)) {
4859 self::$_defaultHierReturnProperties = array(
4860 'home_URL' => 1,
4861 'image_URL' => 1,
4862 'legal_identifier' => 1,
4863 'external_identifier' => 1,
4864 'contact_type' => 1,
4865 'contact_sub_type' => 1,
4866 'sort_name' => 1,
4867 'display_name' => 1,
4868 'nick_name' => 1,
4869 'first_name' => 1,
4870 'middle_name' => 1,
4871 'last_name' => 1,
4872 'prefix_id' => 1,
4873 'suffix_id' => 1,
4874 'formal_title' => 1,
4875 'communication_style_id' => 1,
4876 'email_greeting' => 1,
4877 'postal_greeting' => 1,
4878 'addressee' => 1,
4879 'birth_date' => 1,
4880 'gender_id' => 1,
4881 'preferred_communication_method' => 1,
4882 'do_not_phone' => 1,
4883 'do_not_email' => 1,
4884 'do_not_mail' => 1,
4885 'do_not_sms' => 1,
4886 'do_not_trade' => 1,
4887 'location' => array(
4888 '1' => array(
4889 'location_type' => 1,
4890 'street_address' => 1,
4891 'city' => 1,
4892 'state_province' => 1,
4893 'postal_code' => 1,
4894 'postal_code_suffix' => 1,
4895 'country' => 1,
4896 'phone-Phone' => 1,
4897 'phone-Mobile' => 1,
4898 'phone-Fax' => 1,
4899 'phone-1' => 1,
4900 'phone-2' => 1,
4901 'phone-3' => 1,
4902 'im-1' => 1,
4903 'im-2' => 1,
4904 'im-3' => 1,
4905 'email-1' => 1,
4906 'email-2' => 1,
4907 'email-3' => 1,
4908 ),
4909 '2' => array(
4910 'location_type' => 1,
4911 'street_address' => 1,
4912 'city' => 1,
4913 'state_province' => 1,
4914 'postal_code' => 1,
4915 'postal_code_suffix' => 1,
4916 'country' => 1,
4917 'phone-Phone' => 1,
4918 'phone-Mobile' => 1,
4919 'phone-1' => 1,
4920 'phone-2' => 1,
4921 'phone-3' => 1,
4922 'im-1' => 1,
4923 'im-2' => 1,
4924 'im-3' => 1,
4925 'email-1' => 1,
4926 'email-2' => 1,
4927 'email-3' => 1,
4928 ),
4929 ),
4930 );
4931 }
4932 return self::$_defaultHierReturnProperties;
4933 }
4934
4935 /**
4936 * @param $values
4937 * @param string $tableName
4938 * @param string $fieldName
4939 * @param string $dbFieldName
4940 * @param $fieldTitle
4941 * @param bool $appendTimeStamp
4942 */
4943 public function dateQueryBuilder(
4944 &$values, $tableName, $fieldName,
4945 $dbFieldName, $fieldTitle,
4946 $appendTimeStamp = TRUE
4947 ) {
4948 list($name, $op, $value, $grouping, $wildcard) = $values;
4949
4950 if ($name == "{$fieldName}_low" ||
4951 $name == "{$fieldName}_high"
4952 ) {
4953 if (isset($this->_rangeCache[$fieldName]) || !$value) {
4954 return;
4955 }
4956 $this->_rangeCache[$fieldName] = 1;
4957
4958 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4959
4960 if ($name == $fieldName . '_low') {
4961 $firstOP = '>=';
4962 $firstPhrase = ts('greater than or equal to');
4963 $firstDate = CRM_Utils_Date::processDate($value);
4964
4965 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4966 if (!empty($secondValues) && $secondValues[2]) {
4967 $secondOP = '<=';
4968 $secondPhrase = ts('less than or equal to');
4969 $secondValue = $secondValues[2];
4970
4971 if ($appendTimeStamp && strlen($secondValue) == 10) {
4972 $secondValue .= ' 23:59:59';
4973 }
4974 $secondDate = CRM_Utils_Date::processDate($secondValue);
4975 }
4976 }
4977 elseif ($name == $fieldName . '_high') {
4978 $firstOP = '<=';
4979 $firstPhrase = ts('less than or equal to');
4980
4981 if ($appendTimeStamp && strlen($value) == 10) {
4982 $value .= ' 23:59:59';
4983 }
4984 $firstDate = CRM_Utils_Date::processDate($value);
4985
4986 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4987 if (!empty($secondValues) && $secondValues[2]) {
4988 $secondOP = '>=';
4989 $secondPhrase = ts('greater than or equal to');
4990 $secondValue = $secondValues[2];
4991 $secondDate = CRM_Utils_Date::processDate($secondValue);
4992 }
4993 }
4994
4995 if (!$appendTimeStamp) {
4996 $firstDate = substr($firstDate, 0, 8);
4997 }
4998 $firstDateFormat = CRM_Utils_Date::customFormat($firstDate);
4999
5000 if ($secondDate) {
5001 if (!$appendTimeStamp) {
5002 $secondDate = substr($secondDate, 0, 8);
5003 }
5004 $secondDateFormat = CRM_Utils_Date::customFormat($secondDate);
5005 }
5006
5007 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
5008 if ($secondDate) {
5009 $this->_where[$grouping][] = "
5010 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5011 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5012 ";
5013 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5014 }
5015 else {
5016 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5017 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5018 }
5019 }
5020
5021 if ($name == $fieldName) {
5022 //In Get API, for operators other then '=' the $value is in array(op => value) format
5023 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
5024 $op = key($value);
5025 $value = $value[$op];
5026 }
5027
5028 $date = $format = NULL;
5029 if (strstr($op, 'IN')) {
5030 $format = array();
5031 foreach ($value as &$date) {
5032 $date = CRM_Utils_Date::processDate($date);
5033 if (!$appendTimeStamp) {
5034 $date = substr($date, 0, 8);
5035 }
5036 $format[] = CRM_Utils_Date::customFormat($date);
5037 }
5038 $date = "('" . implode("','", $value) . "')";
5039 $format = implode(', ', $format);
5040 }
5041 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5042 $date = CRM_Utils_Date::processDate($value);
5043 if (!$appendTimeStamp) {
5044 $date = substr($date, 0, 8);
5045 }
5046 $format = CRM_Utils_Date::customFormat($date);
5047 $date = "'$date'";
5048 }
5049
5050 if ($date) {
5051 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5052 }
5053 else {
5054 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op";
5055 }
5056
5057 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
5058
5059 $op = CRM_Utils_Array::value($op, CRM_Core_SelectValues::getSearchBuilderOperators(), $op);
5060 $this->_qill[$grouping][] = "$fieldTitle $op $format";
5061 }
5062 }
5063
5064 /**
5065 * @param $values
5066 * @param string $tableName
5067 * @param string $fieldName
5068 * @param string $dbFieldName
5069 * @param $fieldTitle
5070 * @param null $options
5071 */
5072 public function numberRangeBuilder(
5073 &$values,
5074 $tableName, $fieldName,
5075 $dbFieldName, $fieldTitle,
5076 $options = NULL
5077 ) {
5078 list($name, $op, $value, $grouping, $wildcard) = $values;
5079
5080 if ($name == "{$fieldName}_low" ||
5081 $name == "{$fieldName}_high"
5082 ) {
5083 if (isset($this->_rangeCache[$fieldName])) {
5084 return;
5085 }
5086 $this->_rangeCache[$fieldName] = 1;
5087
5088 $secondOP = $secondPhrase = $secondValue = NULL;
5089
5090 if ($name == "{$fieldName}_low") {
5091 $firstOP = '>=';
5092 $firstPhrase = ts('greater than');
5093
5094 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5095 if (!empty($secondValues)) {
5096 $secondOP = '<=';
5097 $secondPhrase = ts('less than');
5098 $secondValue = $secondValues[2];
5099 }
5100 }
5101 else {
5102 $firstOP = '<=';
5103 $firstPhrase = ts('less than');
5104
5105 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5106 if (!empty($secondValues)) {
5107 $secondOP = '>=';
5108 $secondPhrase = ts('greater than');
5109 $secondValue = $secondValues[2];
5110 }
5111 }
5112
5113 if ($secondOP) {
5114 $this->_where[$grouping][] = "
5115 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5116 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5117 ";
5118 $displayValue = $options ? $options[$value] : $value;
5119 $secondDisplayValue = $options ? $options[$secondValue] : $secondValue;
5120
5121 $this->_qill[$grouping][]
5122 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5123 }
5124 else {
5125 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5126 $displayValue = $options ? $options[$value] : $value;
5127 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5128 }
5129 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
5130
5131 return;
5132 }
5133
5134 if ($name == $fieldName) {
5135 $op = '=';
5136 $phrase = '=';
5137
5138 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5139
5140 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
5141 $displayValue = $options ? $options[$value] : $value;
5142 $this->_qill[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5143 }
5144 }
5145
5146 /**
5147 * Given the field name, operator, value & its data type
5148 * builds the where Clause for the query
5149 * used for handling 'IS NULL'/'IS NOT NULL' operators
5150 *
5151 * @param string $field
5152 * Fieldname.
5153 * @param string $op
5154 * Operator.
5155 * @param string $value
5156 * Value.
5157 * @param string $dataType
5158 * Data type of the field.
5159 *
5160 * @return string
5161 * Where clause for the query.
5162 */
5163 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5164 $op = trim($op);
5165 $clause = "$field $op";
5166
5167 switch ($op) {
5168 case 'IS NULL':
5169 case 'IS NOT NULL':
5170 return $clause;
5171
5172 case 'IS EMPTY':
5173 $clause = " (NULLIF($field, '') IS NULL) ";
5174 return $clause;
5175
5176 case 'IS NOT EMPTY':
5177 $clause = " (NULLIF($field, '') IS NOT NULL) ";
5178 return $clause;
5179
5180 case 'IN':
5181 case 'NOT IN':
5182 if (!empty($value) && is_array($value) && !array_key_exists($op, $value)) {
5183 $value = array($op => $value);
5184 }
5185
5186 default:
5187 if (empty($dataType)) {
5188 $dataType = 'String';
5189 }
5190 if (is_array($value)) {
5191 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5192 // widely used and consistent across the codebase
5193 // adding this here won't accept the search functions which don't submit an array
5194 if (($queryString = CRM_Core_DAO::createSqlFilter($field, $value, $dataType)) != FALSE) {
5195
5196 return $queryString;
5197 }
5198
5199 // 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))
5200 // but we got only array(2,5) from the form.
5201 // We could get away with keeping this in 4.6 if we make it such that it throws an enotice in 4.7 so
5202 // people have to de-slopify it.
5203 if (!empty($value[0])) {
5204 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReport;
5205 if (($queryString = CRM_Core_DAO::createSqlFilter($field, array($op => $value), $dataType)) != FALSE) {
5206 return $queryString;
5207 }
5208 }
5209 else {
5210 $op = 'IN';
5211 $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReportUsingOldFormat;
5212 if (($queryString = CRM_Core_DAO::createSqlFilter($field, array($op => array_keys($value)), $dataType)) != FALSE) {
5213 return $queryString;
5214 }
5215 }
5216 }
5217
5218 $value = CRM_Utils_Type::escape($value, $dataType);
5219 // if we don't have a dataType we should assume
5220 if ($dataType == 'String' || $dataType == 'Text') {
5221 $value = "'" . strtolower($value) . "'";
5222 }
5223 return "$clause $value";
5224 }
5225 }
5226
5227 /**
5228 * @param bool $reset
5229 *
5230 * @return array
5231 */
5232 public function openedSearchPanes($reset = FALSE) {
5233 if (!$reset || empty($this->_whereTables)) {
5234 return self::$_openedPanes;
5235 }
5236
5237 // pane name to table mapper
5238 $panesMapper = array(
5239 ts('Contributions') => 'civicrm_contribution',
5240 ts('Memberships') => 'civicrm_membership',
5241 ts('Events') => 'civicrm_participant',
5242 ts('Relationships') => 'civicrm_relationship',
5243 ts('Activities') => 'civicrm_activity',
5244 ts('Pledges') => 'civicrm_pledge',
5245 ts('Cases') => 'civicrm_case',
5246 ts('Grants') => 'civicrm_grant',
5247 ts('Address Fields') => 'civicrm_address',
5248 ts('Notes') => 'civicrm_note',
5249 ts('Change Log') => 'civicrm_log',
5250 ts('Mailings') => 'civicrm_mailing_event_queue',
5251 );
5252 CRM_Contact_BAO_Query_Hook::singleton()->getPanesMapper($panesMapper);
5253
5254 foreach (array_keys($this->_whereTables) as $table) {
5255 if ($panName = array_search($table, $panesMapper)) {
5256 self::$_openedPanes[$panName] = TRUE;
5257 }
5258 }
5259
5260 return self::$_openedPanes;
5261 }
5262
5263 /**
5264 * @param $operator
5265 */
5266 public function setOperator($operator) {
5267 $validOperators = array('AND', 'OR');
5268 if (!in_array($operator, $validOperators)) {
5269 $operator = 'AND';
5270 }
5271 $this->_operator = $operator;
5272 }
5273
5274 /**
5275 * @return string
5276 */
5277 public function getOperator() {
5278 return $this->_operator;
5279 }
5280
5281 /**
5282 * @param $from
5283 * @param $where
5284 * @param $having
5285 */
5286 public function filterRelatedContacts(&$from, &$where, &$having) {
5287 static $_rTypeProcessed = NULL;
5288 static $_rTypeFrom = NULL;
5289 static $_rTypeWhere = NULL;
5290
5291 if (!$_rTypeProcessed) {
5292 $_rTypeProcessed = TRUE;
5293
5294 // create temp table with contact ids
5295 $tableName = CRM_Core_DAO::createTempTableName('civicrm_transform', TRUE);
5296 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5297 CRM_Core_DAO::executeQuery($sql);
5298
5299 $sql = "
5300 REPLACE INTO $tableName ( contact_id )
5301 SELECT contact_a.id
5302 $from
5303 $where
5304 $having
5305 ";
5306 CRM_Core_DAO::executeQuery($sql);
5307
5308 $qillMessage = ts('Contacts with a Relationship Type of: ');
5309 $rTypes = CRM_Core_PseudoConstant::relationshipType();
5310
5311 if (is_numeric($this->_displayRelationshipType)) {
5312 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType]['label_a_b'];
5313 $_rTypeFrom = "
5314 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5315 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5316 ";
5317 $_rTypeWhere = "
5318 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5319 AND displayRelType.is_active = 1
5320 ";
5321 }
5322 else {
5323 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType);
5324 if ($dirOne == 'a') {
5325 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5326 $_rTypeFrom .= "
5327 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5328 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5329 ";
5330 }
5331 else {
5332 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5333 $_rTypeFrom .= "
5334 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5335 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5336 ";
5337 }
5338 $_rTypeWhere = "
5339 WHERE displayRelType.relationship_type_id = $relType
5340 AND displayRelType.is_active = 1
5341 ";
5342 }
5343 $this->_qill[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5344 }
5345
5346 if (!empty($this->_permissionWhereClause)) {
5347 $_rTypeWhere .= "AND $this->_permissionWhereClause";
5348 }
5349
5350 if (strpos($from, $_rTypeFrom) === FALSE) {
5351 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5352 // this happens when we have an event_type in the quert (CRM-7969)
5353 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5354 $from .= $_rTypeFrom;
5355 $where = $_rTypeWhere;
5356 }
5357
5358 $having = NULL;
5359 }
5360
5361 /**
5362 * @param $op
5363 *
5364 * @return bool
5365 */
5366 public static function caseImportant($op) {
5367 return
5368 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ? FALSE : TRUE;
5369 }
5370
5371 /**
5372 * @param $returnProperties
5373 * @param $prefix
5374 *
5375 * @return bool
5376 */
5377 public static function componentPresent(&$returnProperties, $prefix) {
5378 foreach ($returnProperties as $name => $dontCare) {
5379 if (substr($name, 0, strlen($prefix)) == $prefix) {
5380 return TRUE;
5381 }
5382 }
5383 return FALSE;
5384 }
5385
5386 /**
5387 * Builds the necessary structures for all fields that are similar to option value lookups.
5388 *
5389 * @param string $name
5390 * the name of the field.
5391 * @param string $op
5392 * the sql operator, this function should handle ALL SQL operators.
5393 * @param string $value
5394 * depends on the operator and who's calling the query builder.
5395 * @param int $grouping
5396 * the index where to place the where clause.
5397 * @param $selectValues
5398 * The key value pairs for this element. This allows us to use this function for things besides option-value pairs.
5399 * @param array $field
5400 * an array that contains various properties of the field identified by $name.
5401 * @param string $label
5402 * The label for this field element.
5403 * @param string $dataType
5404 * The data type for this element.
5405 * @param bool $useIDsOnly
5406 *
5407 * @return void
5408 * adds the where clause and qill to the query object
5409 */
5410 public function optionValueQuery(
5411 $name,
5412 $op,
5413 $value,
5414 $grouping,
5415 $selectValues,
5416 $field,
5417 $label,
5418 $dataType = 'String',
5419 $useIDsOnly = FALSE
5420 ) {
5421
5422 if (!empty($selectValues) && !is_array($value) && !empty($selectValues[$value])) {
5423 $qill = $selectValues[$value];
5424 }
5425 else {
5426 $qill = $value;
5427 }
5428
5429 $pseudoFields = array(
5430 'email_greeting',
5431 'postal_greeting',
5432 'addressee',
5433 'gender_id',
5434 'prefix_id',
5435 'suffix_id',
5436 'communication_style_id',
5437 );
5438
5439 if (is_numeric($value)) {
5440 $qill = $selectValues[(int ) $value];
5441 }
5442 elseif ($op == 'IN' || $op == 'NOT IN') {
5443 if (is_array($value)) {
5444 $intVals = array();
5445 $newValues = array();
5446 foreach ($value as $k => $v) {
5447 $intVals[$k] = (int) $k;
5448 $newValues[] = $selectValues[(int) $k];
5449 }
5450
5451 $value = (in_array($name, $pseudoFields)) ? $intVals : $newValues;
5452 $qill = implode(', ', $newValues);
5453 }
5454 }
5455 elseif (!array_key_exists($value, $selectValues)) {
5456 // its a string, lets get the int value
5457 $value = array_search($value, $selectValues);
5458 }
5459 if ($useIDsOnly) {
5460 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5461 if ($tableName == 'civicrm_contact') {
5462 $wc = "contact_a.$fieldName";
5463 }
5464 else {
5465 $wc = "$tableName.id";
5466 }
5467 }
5468 else {
5469 $wc = self::caseImportant($op) ? "LOWER({$field['where']})" : "{$field['where']}";
5470 }
5471
5472 if (in_array($name, $pseudoFields)) {
5473 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5474 $wc = "contact_a.{$name}_id";
5475 }
5476 $dataType = 'Positive';
5477 $value = (!$value) ? 0 : $value;
5478 }
5479
5480 $this->_qill[$grouping][] = $label . " $op '$qill'";
5481 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' || $op == 'RLIKE')) ? '=' : $op;
5482 $this->_where[$grouping][] = self::buildClause($wc, $op, $value, $dataType);
5483 }
5484
5485 /**
5486 * Check and explode a user defined numeric string into an array
5487 * this was the protocol used by search builder in the old old days before we had
5488 * super nice js widgets to do the hard work
5489 *
5490 * @param string $string
5491 * @param string $dataType
5492 * The dataType we should check for the values, default integer.
5493 *
5494 * @return bool|array
5495 * false if string does not match the pattern
5496 * array of numeric values if string does match the pattern
5497 */
5498 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5499 $string = trim($string);
5500 if (substr($string, 0, 1) != '(' || substr($string, -1, 1) != ')') {
5501 Return FALSE;
5502 }
5503
5504 $string = substr($string, 1, -1);
5505 $values = explode(',', $string);
5506 if (empty($values)) {
5507 return FALSE;
5508 }
5509
5510 $returnValues = array();
5511 foreach ($values as $v) {
5512 if ($dataType == 'Integer' && !is_numeric($v)) {
5513 return FALSE;
5514 }
5515 elseif ($dataType == 'String' && !is_string($v)) {
5516 return FALSE;
5517 }
5518 $returnValues[] = trim($v);
5519 }
5520
5521 if (empty($returnValues)) {
5522 return FALSE;
5523 }
5524
5525 return $returnValues;
5526 }
5527
5528 /**
5529 * Convert the pseudo constants id's to their names
5530 *
5531 * @param CRM_Core_DAO $dao
5532 * @param bool $return
5533 *
5534 * @return array|NULL
5535 */
5536 public function convertToPseudoNames(&$dao, $return = FALSE) {
5537 if (empty($this->_pseudoConstantsSelect)) {
5538 return NULL;
5539 }
5540 $values = array();
5541 foreach ($this->_pseudoConstantsSelect as $key => $value) {
5542 if (!empty($this->_pseudoConstantsSelect[$key]['sorting'])) {
5543 continue;
5544 }
5545
5546 if (property_exists($dao, $value['idCol'])) {
5547 $val = $dao->$value['idCol'];
5548
5549 if (CRM_Utils_System::isNull($val)) {
5550 $dao->$key = NULL;
5551 }
5552 elseif ($baoName = CRM_Utils_Array::value('bao', $value, NULL)) {
5553 //preserve id value
5554 $idColumn = "{$key}_id";
5555 $dao->$idColumn = $val;
5556
5557 if ($key == 'state_province_name') {
5558 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant::stateProvinceAbbreviation($val);
5559 }
5560 else {
5561 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant::getLabel($baoName, $value['pseudoField'], $val);
5562 }
5563 }
5564 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5565 $dao->$key = CRM_Core_PseudoConstant::stateProvinceAbbreviation($val);
5566 }
5567 // FIX ME: we should potentially move this to component Query and write a wrapper function that
5568 // handles pseudoconstant fixes for all component
5569 elseif (in_array($value['pseudoField'], array('participant_status', 'participant_role'))) {
5570 $pseudoOptions = $viewValues = array();
5571 $pseudoOptions = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', $value['pseudoField'], array('flip' => 1));
5572 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $val) as $k => $v) {
5573 $viewValues[] = $pseudoOptions[$v];
5574 }
5575 $dao->$key = implode(', ', $viewValues);
5576 }
5577 else {
5578 $labels = CRM_Core_OptionGroup::values($value['pseudoField']);
5579 $dao->$key = $labels[$val];
5580 }
5581
5582 // return converted values in array format
5583 if ($return) {
5584 if (strpos($key, '-') !== FALSE) {
5585 $keyVal = explode('-', $key);
5586 $current = &$values;
5587 $lastElement = array_pop($keyVal);
5588 foreach ($keyVal as $v) {
5589 if (!array_key_exists($v, $current)) {
5590 $current[$v] = array();
5591 }
5592 $current = &$current[$v];
5593 }
5594 $current[$lastElement] = $dao->$key;
5595 }
5596 else {
5597 $values[$key] = $dao->$key;
5598 }
5599 }
5600 }
5601 }
5602 return $values;
5603 }
5604
5605 /**
5606 * Include pseudo fields LEFT JOIN.
5607 * @param string|array $sort can be a object or string
5608 *
5609 * @return array|NULL
5610 */
5611 public function includePseudoFieldsJoin($sort) {
5612 if (!$sort || empty($this->_pseudoConstantsSelect)) {
5613 return NULL;
5614 }
5615 $sort = is_string($sort) ? $sort : $sort->orderBy();
5616 $present = array();
5617
5618 foreach ($this->_pseudoConstantsSelect as $name => $value) {
5619 if (!empty($value['table'])) {
5620 $regex = "/({$value['table']}\.|{$name})/";
5621 if (preg_match($regex, $sort)) {
5622 $this->_elemnt[$value['element']] = 1;
5623 $this->_select[$value['element']] = $value['select'];
5624 $this->_pseudoConstantsSelect[$name]['sorting'] = 1;
5625 $present[$value['table']] = $value['join'];
5626 }
5627 }
5628 }
5629 $presentSimpleFrom = $present;
5630
5631 if (array_key_exists('civicrm_worldregion', $this->_whereTables) &&
5632 array_key_exists('civicrm_country', $presentSimpleFrom)
5633 ) {
5634 unset($presentSimpleFrom['civicrm_country']);
5635 }
5636 if (array_key_exists('civicrm_worldregion', $this->_tables) &&
5637 array_key_exists('civicrm_country', $present)
5638 ) {
5639 unset($present['civicrm_country']);
5640 }
5641
5642 $presentClause = $presentSimpleFromClause = NULL;
5643 if (!empty($present)) {
5644 $presentClause = implode(' ', $present);
5645 }
5646 if (!empty($presentSimpleFrom)) {
5647 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5648 }
5649
5650 $this->_fromClause = $this->_fromClause . $presentClause;
5651 $this->_simpleFromClause = $this->_simpleFromClause . $presentSimpleFromClause;
5652
5653 return array($presentClause, $presentSimpleFromClause);
5654 }
5655
5656 /**
5657 * Build qill for field.
5658 *
5659 * Qill refers to the query detail visible on the UI.
5660 *
5661 * @param $daoName
5662 * @param $fieldName
5663 * @param $fieldValue
5664 * @param $op
5665 * @param array $pseduoExtraParam
5666 *
5667 * @return array
5668 */
5669 public static function buildQillForFieldValue($daoName = NULL, $fieldName, $fieldValue, $op, $pseduoExtraParam = array()) {
5670 $qillOperators = CRM_Core_SelectValues::getSearchBuilderOperators();
5671
5672 if ($fieldName == 'activity_type_id') {
5673 $pseduoOptions = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
5674 }
5675 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
5676 $pseduoOptions = CRM_Event_BAO_Event::getEvents(0, $fieldValue, TRUE, TRUE, TRUE);
5677 }
5678 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
5679 $pseduoOptions = CRM_Core_PseudoConstant::group();
5680 }
5681 elseif ($daoName) {
5682 $pseduoOptions = CRM_Core_PseudoConstant::get($daoName, $fieldName, $pseduoExtraParam = array());
5683 }
5684
5685 //API usually have fieldValue format as array(operator => array(values)),
5686 //so we need to separate operator out of fieldValue param
5687 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
5688 $op = key($fieldValue);
5689 $fieldValue = $fieldValue[$op];
5690 }
5691
5692 if (is_array($fieldValue)) {
5693 $qillString = array();
5694 if (!empty($pseduoOptions)) {
5695 foreach ((array) $fieldValue as $val) {
5696 $qillString[] = CRM_Utils_Array::value($val, $pseduoOptions, $val);
5697 }
5698 $fieldValue = implode(', ', $qillString);
5699 }
5700 else {
5701 $fieldValue = implode(', ', $fieldValue);
5702 }
5703 }
5704 elseif (!empty($pseduoOptions) && array_key_exists($fieldValue, $pseduoOptions)) {
5705 $fieldValue = $pseduoOptions[$fieldValue];
5706 }
5707
5708 return array(CRM_Utils_Array::value($op, $qillOperators, $op), $fieldValue);
5709 }
5710
5711 }