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