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