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