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