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