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