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