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