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