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