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