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