forked from civicrm/civicrm-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuery.php
7250 lines (6562 loc) · 248 KB
/
Query.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
/**
* This is the heart of the search query building mechanism.
*/
class CRM_Contact_BAO_Query {
/**
* The various search modes.
*
* As of February 2017, entries not present for 4, 32, 64, 1024.
*
* MODE_ALL seems to be out of sync with the available constants;
* if this is intentionally excluding MODE_MAILING then that may
* bear documenting?
*
* Likewise if there's reason for the missing modes (4, 32, 64 etc).
*
* @var int
*/
const
NO_RETURN_PROPERTIES = 'CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES',
MODE_CONTACTS = 1,
MODE_CONTRIBUTE = 2,
// There is no 4,
MODE_MEMBER = 8,
MODE_EVENT = 16,
MODE_CONTACTSRELATED = 32,
// no 64.
MODE_GRANT = 128,
MODE_PLEDGEBANK = 256,
MODE_PLEDGE = 512,
// There is no 1024,
MODE_CASE = 2048,
MODE_ACTIVITY = 4096,
MODE_CAMPAIGN = 8192,
MODE_MAILING = 16384,
MODE_ALL = 17407;
/**
* Constants for search operators
*/
const
SEARCH_OPERATOR_AND = 'AND',
SEARCH_OPERATOR_OR = 'OR';
/**
* The default set of return properties.
*
* @var array
*/
public static $_defaultReturnProperties;
/**
* The default set of hier return properties.
*
* @var array
*/
public static $_defaultHierReturnProperties;
/**
* The set of input params.
*
* @var array
*/
public $_params;
public $_cfIDs;
public $_paramLookup;
public $_sort;
/**
* The set of output params
*
* @var array
*/
public $_returnProperties;
/**
* The select clause
*
* @var array
*/
public $_select;
/**
* The name of the elements that are in the select clause
* used to extract the values.
*
* @var array
*/
public $_element;
/**
* The tables involved in the query.
*
* @var array
*/
public $_tables;
/**
* The table involved in the where clause.
*
* @var array
*/
public $_whereTables;
/**
* Array of WHERE clause components.
*
* @var array
*/
public $_where;
/**
* The WHERE clause as a string.
*
* @var string
*/
public $_whereClause;
/**
* Additional WHERE clause for permissions.
*
* @var string
*/
public $_permissionWhereClause;
/**
* The from string
*
* @var string
*/
public $_fromClause;
/**
* Additional permission from clause
*
* @var string
*/
public $_permissionFromClause;
/**
* The from clause for the simple select and alphabetical
* select
*
* @var string
*/
public $_simpleFromClause;
/**
* The having values
*
* @var array
*/
public $_having;
/**
* The english language version of the query
*
* @var array
*/
public $_qill;
/**
* All the fields that could potentially be involved in
* this query
*
* @var array
*/
public $_fields;
/**
* Fields hacked for legacy reasons.
*
* Generally where a field has a option group defining it's options we add them to
* the fields array as pseudofields - eg for gender we would add the key 'gender' to fields
* using CRM_Core_DAO::appendPseudoConstantsToFields($fields);
*
* The rendered results would hold an id in the gender_id field and the label in the pseudo 'Gender'
* field. The heading for the pseudofield would come form the the option group name & for the id field
* from the xml.
*
* These fields are handled in a more legacy way - ie overwriting 'gender_id' with the label on output
* via the convertToPseudoNames function. Ideally we would convert them but they would then need to be fixed
* in some other places & there are also some issues around the name (ie. Gender currently has the label in the
* schema 'Gender' so adding a second 'Gender' field to search builder & export would be confusing and the standard is
* not fully agreed here.
*
* @var array
*/
protected $legacyHackedFields = [
'gender_id' => 'gender',
'prefix_id' => 'individual_prefix',
'suffix_id' => 'individual_suffix',
'communication_style_id' => 'communication_style',
];
/**
* Are we in search mode.
*
* @var bool
*/
public $_search = TRUE;
/**
* Should we skip permission checking.
*
* @var bool
*/
public $_skipPermission = FALSE;
/**
* Should we skip adding of delete clause.
*
* @var bool
*/
public $_skipDeleteClause = FALSE;
/**
* Are we in strict mode (use equality over LIKE)
*
* @var bool
*/
public $_strict = FALSE;
/**
* What operator to use to group the clauses.
*
* @var string
*/
public $_operator = 'AND';
public $_mode = 1;
/**
* Should we only search on primary location.
*
* @var bool
*/
public $_primaryLocation = TRUE;
/**
* Are contact ids part of the query.
*
* @var bool
*/
public $_includeContactIds = FALSE;
/**
* Should we use the smart group cache.
*
* @var bool
*/
public $_smartGroupCache = TRUE;
/**
* Should we display contacts with a specific relationship type.
*
* @var string
*/
public $_displayRelationshipType;
/**
* Reference to the query object for custom values.
*
* @var Object
*/
public $_customQuery;
/**
* Should we enable the distinct clause, used if we are including
* more than one group
*
* @var bool
*/
public $_useDistinct = FALSE;
/**
* Should we just display one contact record
* @var bool
*/
public $_useGroupBy = FALSE;
/**
* The relationship type direction
*
* @var array
*/
public static $_relType;
/**
* The activity role
*
* @var array
*/
public static $_activityRole;
/**
* Consider the component activity type
* during activity search.
*
* @var array
*/
public static $_considerCompActivities;
/**
* Consider with contact activities only,
* during activity search.
*
* @var array
*/
public static $_withContactActivitiesOnly;
/**
* Use distinct component clause for component searches
*
* @var string
*/
public $_distinctComponentClause;
public $_rowCountClause;
/**
* Use groupBy component clause for component searches
*
* @var string
*/
public $_groupByComponentClause;
/**
* Track open panes, useful in advance search
*
* @var array
*/
public static $_openedPanes = [];
/**
* For search builder - which custom fields are location-dependent
* @var array
*/
public $_locationSpecificCustomFields = [];
/**
* The tables which have a dependency on location and/or address
*
* @var array
*/
public static $_dependencies = [
'civicrm_state_province' => 1,
'civicrm_country' => 1,
'civicrm_county' => 1,
'civicrm_address' => 1,
'civicrm_location_type' => 1,
];
/**
* List of location specific fields.
* @var array
*/
public static $_locationSpecificFields = [
'street_address',
'street_number',
'street_name',
'street_unit',
'supplemental_address_1',
'supplemental_address_2',
'supplemental_address_3',
'city',
'postal_code',
'postal_code_suffix',
'geo_code_1',
'geo_code_2',
'state_province',
'country',
'county',
'phone',
'email',
'im',
'address_name',
'master_id',
'location_type',
];
/**
* Remember if we handle either end of a number or date range
* so we can skip the other
* @var array
*/
protected $_rangeCache = [];
/**
* Set to true when $this->relationship is run to avoid adding twice.
*
* @var bool
*/
protected $_relationshipValuesAdded = FALSE;
/**
* Set to the name of the temp table if one has been created.
*
* @var string
*/
public static $_relationshipTempTable;
public $_pseudoConstantsSelect = [];
public $_groupUniqueKey;
public $_groupKeys = [];
/**
* Class constructor which also does all the work.
*
* @param array $params
* @param array $returnProperties
* @param array $fields
* @param bool $includeContactIds
* @param bool $strict
* @param bool|int $mode - mode the search is operating on
*
* @param bool $skipPermission
* @param bool $searchDescendentGroups
* @param bool $smartGroupCache
* @param null $displayRelationshipType
* @param string $operator
* @param string $apiEntity
* @param bool|null $primaryLocationOnly
*
* @throws \CRM_Core_Exception
*/
public function __construct(
$params = NULL, $returnProperties = NULL, $fields = NULL,
$includeContactIds = FALSE, $strict = FALSE, $mode = 1,
$skipPermission = FALSE, $searchDescendentGroups = TRUE,
$smartGroupCache = TRUE, $displayRelationshipType = NULL,
$operator = 'AND',
$apiEntity = NULL,
$primaryLocationOnly = NULL
) {
if ($primaryLocationOnly === NULL) {
$primaryLocationOnly = Civi::settings()->get('searchPrimaryDetailsOnly');
}
$this->_primaryLocation = $primaryLocationOnly;
$this->_params = &$params;
if ($this->_params == NULL) {
$this->_params = [];
}
if ($returnProperties === self::NO_RETURN_PROPERTIES) {
$this->_returnProperties = [];
}
elseif (empty($returnProperties)) {
$this->_returnProperties = self::defaultReturnProperties($mode);
}
else {
$this->_returnProperties = &$returnProperties;
}
$this->_includeContactIds = $includeContactIds;
$this->_strict = $strict;
$this->_mode = $mode;
$this->_skipPermission = $skipPermission;
$this->_smartGroupCache = $smartGroupCache;
$this->_displayRelationshipType = $displayRelationshipType;
$this->setOperator($operator);
if ($fields) {
$this->_fields = &$fields;
$this->_search = FALSE;
$this->_skipPermission = TRUE;
}
else {
$this->_fields = CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE, TRUE, FALSE, !$skipPermission);
// The legacy hacked fields will output as a string rather than their underlying type.
foreach (array_keys($this->legacyHackedFields) as $fieldName) {
$this->_fields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
}
$relationMetadata = CRM_Contact_BAO_Relationship::fields();
$relationFields = array_intersect_key($relationMetadata, array_fill_keys(['relationship_start_date', 'relationship_end_date'], 1));
// No good option other than hard-coding metadata for this 'special' field in.
$relationFields['relation_active_period_date'] = [
'name' => 'relation_active_period_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Active Period'),
'table_name' => 'civicrm_relationship',
'where' => 'civicrm_relationship.start_date',
'where_end' => 'civicrm_relationship.end_date',
'html' => ['type' => 'SelectDate', 'formatType' => 'activityDateTime'],
];
$this->_fields = array_merge($relationFields, $this->_fields);
$fields = CRM_Core_Component::getQueryFields(!$this->_skipPermission);
unset($fields['note']);
$this->_fields = array_merge($this->_fields, $fields);
// add activity fields
$this->_fields = array_merge($this->_fields, CRM_Activity_BAO_Activity::exportableFields());
$this->_fields = array_merge($this->_fields, CRM_Activity_BAO_Activity::exportableFields('Case'));
// Add hack as no unique name is defined for the field but the search form is in denial.
$this->_fields['activity_priority_id'] = $this->_fields['priority_id'];
// add any fields provided by hook implementers
$extFields = CRM_Contact_BAO_Query_Hook::singleton()->getFields();
$this->_fields = array_merge($this->_fields, $extFields);
}
// basically do all the work once, and then reuse it
$this->initialize($apiEntity);
}
/**
* Function which actually does all the work for the constructor.
*
* @param string $apiEntity
* The api entity being called.
* This sort-of duplicates $mode in a confusing way. Probably not by design.
*
* @throws \CRM_Core_Exception
*/
public function initialize($apiEntity = NULL) {
$this->_select = [];
$this->_element = [];
$this->_tables = [];
$this->_whereTables = [];
$this->_where = [];
$this->_qill = [];
$this->_cfIDs = [];
$this->_paramLookup = [];
$this->_having = [];
$this->_customQuery = NULL;
// reset cached static variables - CRM-5803
self::$_activityRole = NULL;
self::$_considerCompActivities = NULL;
self::$_withContactActivitiesOnly = NULL;
$this->_select['contact_id'] = 'contact_a.id as contact_id';
$this->_element['contact_id'] = 1;
$this->_tables['civicrm_contact'] = 1;
if (!empty($this->_params)) {
$this->buildParamsLookup();
}
$this->_whereTables = $this->_tables;
$this->selectClause($apiEntity);
if (!empty($this->_cfIDs)) {
// @todo This function is the select function but instead of running 'select' it
// is running the whole query.
$this->_customQuery = new CRM_Core_BAO_CustomQuery($this->_cfIDs, TRUE, $this->_locationSpecificCustomFields);
$this->_customQuery->query();
$this->_select = array_merge($this->_select, $this->_customQuery->_select);
$this->_element = array_merge($this->_element, $this->_customQuery->_element);
$this->_tables = array_merge($this->_tables, $this->_customQuery->_tables);
}
$isForcePrimaryOnly = !empty($apiEntity);
$this->_whereClause = $this->whereClause($isForcePrimaryOnly);
if (array_key_exists('civicrm_contribution', $this->_whereTables)) {
$component = 'contribution';
}
if (array_key_exists('civicrm_membership', $this->_whereTables)) {
$component = 'membership';
}
if (isset($component) && !$this->_skipPermission) {
// Unit test coverage in api_v3_FinancialTypeACLTest::testGetACLContribution.
$clauses = [];
if ($component === 'contribution') {
$clauses = array_filter(CRM_Contribute_BAO_Contribution::getSelectWhereClause());
}
if ($component === 'membership') {
$clauses = array_filter(CRM_Member_BAO_Membership::getSelectWhereClause());
}
if ($clauses) {
$this->_whereClause .= ' AND ' . implode(' AND ', $clauses);
}
}
$this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode, $apiEntity);
$this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode);
$this->openedSearchPanes(TRUE);
}
/**
* Function for same purpose as convertFormValues.
*
* Like convert form values this function exists to pre-Process parameters from the form.
*
* It is unclear why they are different functions & likely relates to advances search
* versus search builder.
*
* The direction we are going is having the form convert values to a standardised format &
* moving away from weird & wonderful where clause switches.
*
* Fix and handle contact deletion nicely.
*
* this code is primarily for search builder use case where different clauses can specify if they want deleted.
*
* @see https://issues.civicrm.org/jira/browse/CRM-11971
*/
public function buildParamsLookup() {
$trashParamExists = FALSE;
$paramByGroup = [];
foreach ($this->_params as $k => $param) {
if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
$trashParamExists = TRUE;
}
if (!empty($param[3])) {
$paramByGroup[$param[3]][$k] = $param;
}
}
if ($trashParamExists) {
$this->_skipDeleteClause = TRUE;
//cycle through group sets and explicitly add trash param if not set
foreach ($paramByGroup as $setID => $set) {
if (
!in_array(['contact_is_deleted', '=', '1', $setID, '0'], $this->_params) &&
!in_array(['contact_is_deleted', '=', '0', $setID, '0'], $this->_params)
) {
$this->_params[] = [
'contact_is_deleted',
'=',
'0',
$setID,
'0',
];
}
}
}
foreach ($this->_params as $value) {
if (empty($value[0])) {
continue;
}
$cfID = CRM_Core_BAO_CustomField::getKeyID(str_replace(['_relative', '_low', '_high', '_to', '_high'], '', $value[0]));
if ($cfID) {
if (!array_key_exists($cfID, $this->_cfIDs)) {
$this->_cfIDs[$cfID] = [];
}
// Set wildcard value based on "and/or" selection
foreach ($this->_params as $key => $param) {
if ($param[0] == $value[0] . '_operator') {
$value[4] = $param[2] == 'or';
break;
}
}
$this->_cfIDs[$cfID][] = $value;
}
if (!array_key_exists($value[0], $this->_paramLookup)) {
$this->_paramLookup[$value[0]] = [];
}
if ($value[0] !== 'group') {
// Just trying to unravel how group interacts here! This whole function is weird.
$this->_paramLookup[$value[0]][] = $value;
}
}
}
/**
* Some composite fields do not appear in the fields array hack to make them part of the query.
*
* @param $apiEntity
* The api entity being called.
* This sort-of duplicates $mode in a confusing way. Probably not by design.
*/
public function addSpecialFields($apiEntity) {
static $special = ['contact_type', 'contact_sub_type', 'sort_name', 'display_name'];
// if get called via Contact.get API having address_id as return parameter
if ($apiEntity === 'Contact') {
$special[] = 'address_id';
}
foreach ($special as $name) {
if (!empty($this->_returnProperties[$name])) {
if ($name === 'address_id') {
$this->_tables['civicrm_address'] = 1;
$this->_select['address_id'] = 'civicrm_address.id as address_id';
$this->_element['address_id'] = 1;
}
else {
$this->_select[$name] = "contact_a.{$name} as $name";
$this->_element[$name] = 1;
}
}
}
}
/**
* Given a list of conditions in params and a list of desired
* return Properties generate the required select and from
* clauses. Note that since the where clause introduces new
* tables, the initial attempt also retrieves all variables used
* in the params list
*
* @param string $apiEntity
* The api entity being called.
* This sort-of duplicates $mode in a confusing way. Probably not by design.
*/
public function selectClause($apiEntity = NULL) {
// @todo Tidy up this. This arises because 1) we are ignoring the $mode & adding a new
// param ($apiEntity) instead - presumably an oversight & 2 because
// contact is not implemented as a component.
$this->addSpecialFields($apiEntity);
foreach ($this->_fields as $name => $field) {
// skip component fields
// there are done by the alter query below
// and need not be done on every field
// @todo remove these & handle using metadata - only obscure fields
// that are hack-added should need to be excluded from the main loop.
if (
(substr($name, 0, 12) === 'participant_') ||
(substr($name, 0, 7) === 'pledge_') ||
(substr($name, 0, 5) === 'case_')
) {
continue;
}
// redirect to activity select clause
if (
(substr($name, 0, 9) === 'activity_') ||
($name === 'parent_id')
) {
CRM_Activity_BAO_Query::select($this);
}
// if this is a hierarchical name, we ignore it
$names = explode('-', $name);
if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
continue;
}
// make an exception for special cases, to add the field in select clause
$makeException = FALSE;
//special handling for groups/tags
if (in_array($name, ['groups', 'tags', 'notes'])
&& isset($this->_returnProperties[substr($name, 0, -1)])
) {
// @todo instead of setting make exception to get us into
// an if clause that has handling for these fields buried with in it
// move the handling to here.
$makeException = TRUE;
}
// since note has 3 different options we need special handling
// note / note_subject / note_body
if ($name === 'notes') {
foreach (['note', 'note_subject', 'note_body'] as $noteField) {
if (isset($this->_returnProperties[$noteField])) {
$makeException = TRUE;
break;
}
}
}
$cfID = CRM_Core_BAO_CustomField::getKeyID($name);
if (
!empty($this->_paramLookup[$name])
|| !empty($this->_returnProperties[$name])
|| $this->pseudoConstantNameIsInReturnProperties($field, $name)
|| $makeException
) {
if ($cfID) {
// add to cfIDs array if not present
if (!array_key_exists($cfID, $this->_cfIDs)) {
$this->_cfIDs[$cfID] = [];
}
}
elseif (isset($field['where'])) {
[$tableName, $fieldName] = explode('.', $field['where'], 2);
if (isset($tableName)) {
if (!empty(self::$_dependencies[$tableName])) {
$this->_tables['civicrm_address'] = 1;
$this->_select['address_id'] = 'civicrm_address.id as address_id';
$this->_element['address_id'] = 1;
}
if ($tableName === 'im_provider' || $tableName === 'email_greeting' ||
$tableName === 'postal_greeting' || $tableName === 'addressee'
) {
if ($tableName === 'im_provider') {
CRM_Core_OptionValue::select($this);
}
if (in_array($tableName,
['email_greeting', 'postal_greeting', 'addressee'])) {
$this->_element["{$name}_id"] = 1;
$this->_select["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
$this->_pseudoConstantsSelect[$name] = ['pseudoField' => $tableName, 'idCol' => "{$name}_id"];
$this->_pseudoConstantsSelect[$name]['select'] = "{$name}.{$fieldName} as $name";
$this->_pseudoConstantsSelect[$name]['element'] = $name;
if ($tableName === 'email_greeting') {
// @todo bad join.
$this->_pseudoConstantsSelect[$name]['join']
= " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
$this->_pseudoConstantsSelect[$name]['join'] .=
" 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 ) ";
}
elseif ($tableName === 'postal_greeting') {
// @todo bad join.
$this->_pseudoConstantsSelect[$name]['join']
= " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
$this->_pseudoConstantsSelect[$name]['join'] .=
" 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 ) ";
}
elseif ($tableName == 'addressee') {
// @todo bad join.
$this->_pseudoConstantsSelect[$name]['join']
= " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
$this->_pseudoConstantsSelect[$name]['join'] .=
" LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
}
$this->_pseudoConstantsSelect[$name]['table'] = $tableName;
//get display
$greetField = "{$name}_display";
$this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}";
$this->_element[$greetField] = 1;
//get custom
$greetField = "{$name}_custom";
$this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}";
$this->_element[$greetField] = 1;
}
}
else {
if (!in_array($tableName, ['civicrm_state_province', 'civicrm_country', 'civicrm_county'])) {
$this->_tables[$tableName] = 1;
}
// also get the id of the tableName
$tName = substr($tableName, 8);
if (in_array($tName, ['country', 'state_province', 'county'])) {
if ($tName == 'state_province') {
$this->_pseudoConstantsSelect['state_province_name'] = [
'pseudoField' => "{$tName}",
'idCol' => "{$tName}_id",
'bao' => 'CRM_Core_BAO_Address',
'table' => "civicrm_{$tName}",
'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
];
$this->_pseudoConstantsSelect[$tName] = [
'pseudoField' => 'state_province_abbreviation',
'idCol' => "{$tName}_id",
'table' => "civicrm_{$tName}",
'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
];
}
else {
$this->_pseudoConstantsSelect[$name] = [
'pseudoField' => "{$tName}_id",
'idCol' => "{$tName}_id",
'bao' => 'CRM_Core_BAO_Address',
'table' => "civicrm_{$tName}",
'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
];
}
$this->_select["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
$this->_element["{$tName}_id"] = 1;
}
elseif ($tName != 'contact') {
$this->_select["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
$this->_element["{$tName}_id"] = 1;
}
//special case for phone
if ($name == 'phone') {
$this->_select['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
$this->_element['phone_type_id'] = 1;
}
// if IM then select provider_id also
// to get "IM Service Provider" in a file to be exported, CRM-3140
if ($name == 'im') {
$this->_select['provider_id'] = "civicrm_im.provider_id as provider_id";
$this->_element['provider_id'] = 1;
}
if ($tName == 'contact' && $fieldName == 'organization_name') {
// special case, when current employer is set for Individual contact
$this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
}
elseif ($tName == 'contact' && $fieldName === 'id') {
// Handled elsewhere, explicitly ignore. Possibly for all tables...
}
elseif (in_array($tName, ['country', 'county'])) {
$this->_pseudoConstantsSelect[$name]['select'] = "{$field['where']} as `$name`";
$this->_pseudoConstantsSelect[$name]['element'] = $name;
}
elseif ($tName == 'state_province') {
$this->_pseudoConstantsSelect[$tName]['select'] = "{$field['where']} as `$name`";
$this->_pseudoConstantsSelect[$tName]['element'] = $name;
}
elseif (strpos($name, 'contribution_soft_credit') !== FALSE) {
if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled($this->_params)) {
$this->_select[$name] = "{$field['where']} as `$name`";
}
}
elseif ($this->pseudoConstantNameIsInReturnProperties($field, $name)) {
$this->addPseudoconstantFieldToSelect($name);
}
else {
$this->_select[$name] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$name`");
}
if (!in_array($tName, ['state_province', 'country', 'county'])) {
$this->_element[$name] = 1;
}
}
}
}
elseif ($name === 'tags') {
//@todo move this handling outside the big IF & ditch $makeException
$this->_useGroupBy = TRUE;
$this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
$this->_element[$name] = 1;
$this->_tables['civicrm_tag'] = 1;
$this->_tables['civicrm_entity_tag'] = 1;
}
elseif ($name === 'groups') {
//@todo move this handling outside the big IF & ditch $makeException
$this->_useGroupBy = TRUE;
// Duplicates will be created here but better to sort them out in php land.
$this->_select[$name] = "
CONCAT_WS(',',
GROUP_CONCAT(DISTINCT IF(civicrm_group_contact.status = 'Added', civicrm_group_contact.group_id, '')),
GROUP_CONCAT(DISTINCT civicrm_group_contact_cache.group_id)
)
as `groups`";
$this->_element[$name] = 1;
$this->_tables['civicrm_group_contact'] = 1;
$this->_tables['civicrm_group_contact_cache'] = 1;
$this->_pseudoConstantsSelect["{$name}"] = [
'pseudoField' => "groups",
'idCol' => 'groups',
];
}
elseif ($name === 'notes') {
//@todo move this handling outside the big IF & ditch $makeException
// if note field is subject then return subject else body of the note
$noteColumn = 'note';
if (isset($noteField) && $noteField === 'note_subject') {
$noteColumn = 'subject';
}
$this->_useGroupBy = TRUE;
$this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
$this->_element[$name] = 1;
$this->_tables['civicrm_note'] = 1;
}
elseif ($name === 'current_employer') {
$this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
$this->_element[$name] = 1;
}
}
if ($cfID && !empty($field['is_search_range'])) {
// this is a custom field with range search enabled, so we better check for two/from values
if (!empty($this->_paramLookup[$name . '_from'])) {
if (!array_key_exists($cfID, $this->_cfIDs)) {
$this->_cfIDs[$cfID] = [];
}
foreach ($this->_paramLookup[$name . '_from'] as $pID => $p) {
// search in the cdID array for the same grouping
$fnd = FALSE;
foreach ($this->_cfIDs[$cfID] as $cID => $c) {
if ($c[3] == $p[3]) {
$this->_cfIDs[$cfID][$cID][2]['from'] = $p[2];
$fnd = TRUE;
}
}
if (!$fnd) {
$p[2] = ['from' => $p[2]];
$this->_cfIDs[$cfID][] = $p;
}
}
}