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