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