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