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