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