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