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