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