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