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