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