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