-
-
Notifications
You must be signed in to change notification settings - Fork 824
/
Copy pathutils.php
2461 lines (2300 loc) · 79.1 KB
/
utils.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
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* CiviCRM APIv3 utility functions.
*
* @package CiviCRM_APIv3
*/
/**
* Initialize CiviCRM - should be run at the start of each API function.
*/
function _civicrm_api3_initialize() {
require_once 'CRM/Core/ClassLoader.php';
CRM_Core_ClassLoader::singleton()->register();
CRM_Core_Config::singleton();
}
/**
* Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking.
*
* @param array $params
* Array of fields to check.
* @param array $daoName
* String DAO to check for required fields (create functions only).
* @param array $keyoptions
* List of required fields options. One of the options is required.
*/
function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = array()) {
$keys = array(array());
foreach ($keyoptions as $key) {
$keys[0][] = $key;
}
civicrm_api3_verify_mandatory($params, $daoName, $keys);
}
/**
* Check mandatory fields are included.
*
* @param array $params
* Array of fields to check.
* @param array $daoName
* String DAO to check for required fields (create functions only).
* @param array $keys
* List of required fields. A value can be an array denoting that either this or that is required.
* @param bool $verifyDAO
*
* @throws \API_Exception
*/
function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = array(), $verifyDAO = TRUE) {
$unmatched = array();
if ($daoName != NULL && $verifyDAO && empty($params['id'])) {
$unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
if (!is_array($unmatched)) {
$unmatched = array();
}
}
if (!empty($params['id'])) {
$keys = array('version');
}
else {
if (!in_array('version', $keys)) {
// required from v3 onwards
$keys[] = 'version';
}
}
foreach ($keys as $key) {
if (is_array($key)) {
$match = 0;
$optionset = array();
foreach ($key as $subkey) {
if (!array_key_exists($subkey, $params) || empty($params[$subkey])) {
$optionset[] = $subkey;
}
else {
// as long as there is one match then we don't need to rtn anything
$match = 1;
}
}
if (empty($match) && !empty($optionset)) {
$unmatched[] = "one of (" . implode(", ", $optionset) . ")";
}
}
else {
// Disallow empty values except for the number zero.
// TODO: create a utility for this since it's needed in many places
if (!array_key_exists($key, $params) || (empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
$unmatched[] = $key;
}
}
}
if (!empty($unmatched)) {
throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched), "mandatory_missing", array("fields" => $unmatched));
}
}
/**
* Create error array.
*
* @param string $msg
* @param array $data
*
* @return array
*/
function civicrm_api3_create_error($msg, $data = array()) {
$data['is_error'] = 1;
$data['error_message'] = $msg;
// we will show sql to privileged user only (not sure of a specific
// security hole here but seems sensible - perhaps should apply to the trace as well?)
if (isset($data['sql']) && CRM_Core_Permission::check('Administer CiviCRM')) {
// Isn't this redundant?
$data['debug_information'] = $data['sql'];
}
else {
unset($data['sql']);
}
return $data;
}
/**
* Format array in result output style.
*
* @param array|int $values values generated by API operation (the result)
* @param array $params
* Parameters passed into API call.
* @param string $entity
* The entity being acted on.
* @param string $action
* The action passed to the API.
* @param object $dao
* DAO object to be freed here.
* @param array $extraReturnValues
* Additional values to be added to top level of result array(.
* - this param is currently used for legacy behaviour support
*
* @return array
*/
function civicrm_api3_create_success($values = 1, $params = array(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
$result = array();
$lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
// TODO: This shouldn't be necessary but this fn sometimes gets called with lowercase entity
$entity = _civicrm_api_get_camel_name($entity);
$result['is_error'] = 0;
//lets set the ['id'] field if it's not set & we know what the entity is
if (is_array($values) && $entity && $action != 'getfields') {
foreach ($values as $key => $item) {
if (empty($item['id']) && !empty($item[$lowercase_entity . "_id"])) {
$values[$key]['id'] = $item[$lowercase_entity . "_id"];
}
if (!empty($item['financial_type_id'])) {
//4.3 legacy handling
$values[$key]['contribution_type_id'] = $item['financial_type_id'];
}
if (!empty($item['next_sched_contribution_date'])) {
// 4.4 legacy handling
$values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
}
}
}
if (is_array($params) && !empty($params['debug'])) {
if (is_string($action) && $action != 'getfields') {
$apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) + $params);
}
elseif ($action != 'getfields') {
$apiFields = civicrm_api($entity, 'getfields', array('version' => 3) + $params);
}
else {
$apiFields = FALSE;
}
$allFields = array();
if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array::value('values', $apiFields))) {
$allFields = array_keys($apiFields['values']);
}
$paramFields = array_keys($params);
$undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), array(
'action',
'entity',
'debug',
'version',
'check_permissions',
'IDS_request_uri',
'IDS_user_agent',
'return',
'sequential',
'rowCount',
'option_offset',
'option_limit',
'custom',
'option_sort',
'options',
'prettyprint',
));
if ($undefined) {
$result['undefined_fields'] = array_merge($undefined);
}
}
if (is_object($dao)) {
$dao->free();
}
$result['version'] = 3;
if (is_array($values)) {
$result['count'] = (int) count($values);
// Convert value-separated strings to array
if ($action != 'getfields') {
_civicrm_api3_separate_values($values);
}
if ($result['count'] == 1) {
list($result['id']) = array_keys($values);
}
elseif (!empty($values['id']) && is_int($values['id'])) {
$result['id'] = $values['id'];
}
}
else {
$result['count'] = !empty($values) ? 1 : 0;
}
if (is_array($values) && isset($params['sequential']) &&
$params['sequential'] == 1
) {
$result['values'] = array_values($values);
}
else {
$result['values'] = $values;
}
if (!empty($params['options']['metadata'])) {
// We've made metadata an array but only supporting 'fields' atm.
if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
$fields = civicrm_api3($entity, 'getfields', array(
'action' => substr($action, 0, 3) == 'get' ? 'get' : 'create',
));
$result['metadata']['fields'] = $fields['values'];
}
}
// Report deprecations.
$deprecated = _civicrm_api3_deprecation_check($entity, $result);
// Always report "setvalue" action as deprecated.
if (!is_string($deprecated) && ($action == 'getactions' || $action == 'setvalue')) {
$deprecated = ((array) $deprecated) + array('setvalue' => 'The "setvalue" action is deprecated. Use "create" with an id instead.');
}
// Always report "update" action as deprecated.
if (!is_string($deprecated) && ($action == 'getactions' || $action == 'update')) {
$deprecated = ((array) $deprecated) + array('update' => 'The "update" action is deprecated. Use "create" with an id instead.');
}
if ($deprecated) {
// Metadata-level deprecations or wholesale entity deprecations.
if ($entity == 'Entity' || $action == 'getactions' || is_string($deprecated)) {
$result['deprecated'] = $deprecated;
}
// Action-specific deprecations
elseif (!empty($deprecated[$action])) {
$result['deprecated'] = $deprecated[$action];
}
}
return array_merge($result, $extraReturnValues);
}
/**
* Load the DAO of the entity.
*
* @param $entity
*
* @return bool
*/
function _civicrm_api3_load_DAO($entity) {
$dao = _civicrm_api3_get_DAO($entity);
if (empty($dao)) {
return FALSE;
}
$d = new $dao();
return $d;
}
/**
* Return the DAO of the function or Entity.
*
* @param string $name
* Either a function of the api (civicrm_{entity}_create or the entity name.
* return the DAO name to manipulate this function
* eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
*
* @return mixed|string
*/
function _civicrm_api3_get_DAO($name) {
if (strpos($name, 'civicrm_api3') !== FALSE) {
$last = strrpos($name, '_');
// len ('civicrm_api3_') == 13
$name = substr($name, 13, $last - 13);
}
$name = _civicrm_api_get_camel_name($name);
if ($name == 'Individual' || $name == 'Household' || $name == 'Organization') {
$name = 'Contact';
}
// hack to deal with incorrectly named BAO/DAO - see CRM-10859
// FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
if ($name == 'MailingEventQueue') {
return 'CRM_Mailing_Event_DAO_Queue';
}
// FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
// but am not confident mailing_recipients is tested so have not tackled.
if ($name == 'MailingRecipients') {
return 'CRM_Mailing_DAO_Recipients';
}
// FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
if ($name == 'MailingComponent') {
return 'CRM_Mailing_DAO_Component';
}
// FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
if ($name == 'AclRole') {
return 'CRM_ACL_DAO_EntityRole';
}
// FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
// But this would impact SMS extensions so need to coordinate
// Probably best approach is to migrate them to use the api and decouple them from core BAOs
if ($name == 'SmsProvider') {
return 'CRM_SMS_DAO_Provider';
}
// FIXME: DAO names should follow CamelCase convention
if ($name == 'Im' || $name == 'Acl') {
$name = strtoupper($name);
}
$dao = CRM_Core_DAO_AllCoreTables::getFullName($name);
if ($dao || !$name) {
return $dao;
}
// Really weird apis can declare their own DAO name. Not sure if this is a good idea...
if (file_exists("api/v3/$name.php")) {
include_once "api/v3/$name.php";
}
$daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
if (function_exists($daoFn)) {
return $daoFn();
}
return NULL;
}
/**
* Return the BAO name of the function or Entity.
*
* @param string $name
* Is either a function of the api (civicrm_{entity}_create or the entity name.
* return the DAO name to manipulate this function
* eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
*
* @return mixed
*/
function _civicrm_api3_get_BAO($name) {
// FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
if ($name == 'PrintLabel') {
return 'CRM_Badge_BAO_Layout';
}
$dao = _civicrm_api3_get_DAO($name);
if (!$dao) {
return NULL;
}
$bao = str_replace("DAO", "BAO", $dao);
$file = strtr($bao, '_', '/') . '.php';
// Check if this entity actually has a BAO. Fall back on the DAO if not.
return stream_resolve_include_path($file) ? $bao : $dao;
}
/**
* Recursive function to explode value-separated strings into arrays.
*
* @param $values
*/
function _civicrm_api3_separate_values(&$values) {
$sp = CRM_Core_DAO::VALUE_SEPARATOR;
foreach ($values as $key => & $value) {
if (is_array($value)) {
_civicrm_api3_separate_values($value);
}
elseif (is_string($value)) {
// This is to honor the way case API was originally written.
if ($key == 'case_type_id') {
$value = trim(str_replace($sp, ',', $value), ',');
}
elseif (strpos($value, $sp) !== FALSE) {
$value = explode($sp, trim($value, $sp));
}
}
}
}
/**
* This is a legacy wrapper for api_store_values.
*
* It checks suitable fields using getfields rather than DAO->fields.
*
* Getfields has handling for how to deal with unique names which dao->fields doesn't
*
* Note this is used by BAO type create functions - eg. contribution
*
* @param string $entity
* @param array $params
* @param array $values
*/
function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
$fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
$fields = $fields['values'];
_civicrm_api3_store_values($fields, $params, $values);
}
/**
* Store values.
*
* @param array $fields
* @param array $params
* @param array $values
*
* @return Bool
*/
function _civicrm_api3_store_values(&$fields, &$params, &$values) {
$valueFound = FALSE;
$keys = array_intersect_key($params, $fields);
foreach ($keys as $name => $value) {
if ($name !== 'id') {
$values[$name] = $value;
$valueFound = TRUE;
}
}
return $valueFound;
}
/**
* Returns field names of the given entity fields.
*
* @param array $fields
* Fields array to retrieve the field names for.
* @return array
*/
function _civicrm_api3_field_names($fields) {
$result = array();
foreach ($fields as $key => $value) {
if (!empty($value['name'])) {
$result[] = $value['name'];
}
}
return $result;
}
/**
* Returns an array with database information for the custom fields of an
* entity.
*
* Something similar might already exist in CiviCRM. But I was not
* able to find it.
*
* @param string $entity
*
* @return array
* an array that maps the custom field ID's to table name and
* column name. E.g.:
* {
* '1' => array {
* 'table_name' => 'table_name_1',
* 'column_name' => 'column_name_1',
* 'data_type' => 'data_type_1',
* },
* }
*/
function _civicrm_api3_custom_fields_for_entity($entity) {
$result = array();
$query = "
SELECT f.id, f.label, f.data_type,
f.html_type, f.is_search_range,
f.option_group_id, f.custom_group_id,
f.column_name, g.table_name,
f.date_format,f.time_format
FROM civicrm_custom_field f
JOIN civicrm_custom_group g ON f.custom_group_id = g.id
WHERE g.is_active = 1
AND f.is_active = 1
AND g.extends = %1";
$params = array(
'1' => array($entity, 'String'),
);
$dao = CRM_Core_DAO::executeQuery($query, $params);
while ($dao->fetch()) {
$result[$dao->id] = array(
'table_name' => $dao->table_name,
'column_name' => $dao->column_name,
'data_type' => $dao->data_type,
);
}
$dao->free();
return $result;
}
/**
* Get function for query object api.
*
* The API supports 2 types of get request. The more complex uses the BAO query object.
* This is a generic function for those functions that call it
*
* At the moment only called by contact we should extend to contribution &
* others that use the query object. Note that this function passes permission information in.
* The others don't
*
* Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
* 2 variants call
*
* @param $entity
* @param array $params
* As passed into api get or getcount function.
* @param array $additional_options
* Array of options (so we can modify the filter).
* @param bool $getCount
* Are we just after the count.
* @param int $mode
* This basically correlates to the component.
* @param null|array $defaultReturnProperties
* Default return properties for the entity
* (used if return not set - but don't do that - set return!).
*
* @return array
* @throws API_Exception
*/
function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL, $mode = 1, $defaultReturnProperties = NULL) {
$lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
// Convert id to e.g. contact_id
if (empty($params[$lowercase_entity . '_id']) && isset($params['id'])) {
$params[$lowercase_entity . '_id'] = $params['id'];
}
unset($params['id']);
$options = _civicrm_api3_get_options_from_params($params, TRUE);
$inputParams = array_merge(
CRM_Utils_Array::value('input_params', $options, array()),
CRM_Utils_Array::value('input_params', $additional_options, array())
);
$returnProperties = array_merge(
CRM_Utils_Array::value('return', $options, array()),
CRM_Utils_Array::value('return', $additional_options, array())
);
if (empty($returnProperties)) {
$returnProperties = $defaultReturnProperties;
}
if (!empty($params['check_permissions'])) {
// we will filter query object against getfields
$fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
// we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
$fields['values'][$lowercase_entity . '_id'] = array();
$varsToFilter = array('returnProperties', 'inputParams');
foreach ($varsToFilter as $varToFilter) {
if (!is_array($$varToFilter)) {
continue;
}
//I was going to throw an exception rather than silently filter out - but
//would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
//so we are silently ignoring parts of their request
//$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
$$varToFilter = array_intersect_key($$varToFilter, $fields['values']);
}
}
$options = array_merge($options, $additional_options);
$sort = CRM_Utils_Array::value('sort', $options, NULL);
$offset = CRM_Utils_Array::value('offset', $options, NULL);
$limit = CRM_Utils_Array::value('limit', $options, NULL);
$smartGroupCache = CRM_Utils_Array::value('smartGroupCache', $params);
if ($getCount) {
$limit = NULL;
$returnProperties = NULL;
}
if (substr($sort, 0, 2) == 'id') {
$sort = $lowercase_entity . "_" . $sort;
}
$newParams = CRM_Contact_BAO_Query::convertFormValues($inputParams);
$skipPermissions = !empty($params['check_permissions']) ? 0 : 1;
list($entities) = CRM_Contact_BAO_Query::apiQuery(
$newParams,
$returnProperties,
NULL,
$sort,
$offset,
$limit,
$smartGroupCache,
$getCount,
$skipPermissions,
$mode
);
return $entities;
}
/**
* Get dao query object based on input params.
*
* Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
* 2 variants call
*
* @param array $params
* @param string $mode
* @param string $entity
*
* @return array
* [CRM_Core_DAO|CRM_Contact_BAO_Query]
*/
function _civicrm_api3_get_query_object($params, $mode, $entity) {
$options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
$sort = CRM_Utils_Array::value('sort', $options, NULL);
$offset = CRM_Utils_Array::value('offset', $options);
$rowCount = CRM_Utils_Array::value('limit', $options);
$inputParams = CRM_Utils_Array::value('input_params', $options, array());
$returnProperties = CRM_Utils_Array::value('return', $options, NULL);
if (empty($returnProperties)) {
$returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties($mode);
}
$newParams = CRM_Contact_BAO_Query::convertFormValues($inputParams, 0, FALSE, $entity);
$query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
FALSE, FALSE, $mode,
empty($params['check_permissions'])
);
list($select, $from, $where, $having) = $query->query();
$sql = "$select $from $where $having";
if (!empty($sort)) {
$sql .= " ORDER BY $sort ";
}
if (!empty($rowCount)) {
$sql .= " LIMIT $offset, $rowCount ";
}
$dao = CRM_Core_DAO::executeQuery($sql);
return array($dao, $query);
}
/**
* Function transfers the filters being passed into the DAO onto the params object.
*
* @deprecated DAO based retrieval is being phased out.
*
* @param CRM_Core_DAO $dao
* @param array $params
* @param bool $unique
* @param array $extraSql
* API specific queries eg for event isCurrent would be converted to
* $extraSql['where'] = array('civicrm_event' => array('(start_date >= CURDATE() || end_date >= CURDATE())'));
*
* @throws API_Exception
* @throws Exception
*/
function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $extraSql = array()) {
$entity = _civicrm_api_get_entity_name_from_dao($dao);
$lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
if (!empty($params[$lowercase_entity . "_id"]) && empty($params['id'])) {
//if entity_id is set then treat it as ID (will be overridden by id if set)
$params['id'] = $params[$lowercase_entity . "_id"];
}
$allfields = _civicrm_api3_build_fields_array($dao, $unique);
$fields = array_intersect(array_keys($allfields), array_keys($params));
$options = _civicrm_api3_get_options_from_params($params);
//apply options like sort
_civicrm_api3_apply_options_to_dao($params, $dao, $entity);
//accept filters like filter.activity_date_time_high
// std is now 'filters' => ..
if (strstr(implode(',', array_keys($params)), 'filter')) {
if (isset($params['filters']) && is_array($params['filters'])) {
foreach ($params['filters'] as $paramkey => $paramvalue) {
_civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
}
}
else {
foreach ($params as $paramkey => $paramvalue) {
if (strstr($paramkey, 'filter')) {
_civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
}
}
}
}
if (!$fields) {
$fields = array();
}
foreach ($fields as $field) {
if (is_array($params[$field])) {
//get the actual fieldname from db
$fieldName = $allfields[$field]['name'];
$where = CRM_Core_DAO::createSqlFilter($fieldName, $params[$field], 'String');
if (!empty($where)) {
$dao->whereAdd($where);
}
}
else {
if ($unique) {
$daoFieldName = $allfields[$field]['name'];
if (empty($daoFieldName)) {
throw new API_Exception("Failed to determine field name for \"$field\"");
}
$dao->{$daoFieldName} = $params[$field];
}
else {
$dao->$field = $params[$field];
}
}
}
if (!empty($extraSql['where'])) {
foreach ($extraSql['where'] as $table => $sqlWhere) {
foreach ($sqlWhere as $where) {
$dao->whereAdd($where);
}
}
}
if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
$dao->selectAdd();
// Ensure 'id' is included.
$options['return']['id'] = TRUE;
$allfields = _civicrm_api3_get_unique_name_array($dao);
$returnMatched = array_intersect(array_keys($options['return']), $allfields);
foreach ($returnMatched as $returnValue) {
$dao->selectAdd($returnValue);
}
// Not already matched on the field names.
$unmatchedFields = array_diff(
array_keys($options['return']),
$returnMatched
);
$returnUniqueMatched = array_intersect(
$unmatchedFields,
// But a match for the field keys.
array_flip($allfields)
);
foreach ($returnUniqueMatched as $uniqueVal) {
$dao->selectAdd($allfields[$uniqueVal]);
}
}
$dao->setApiFilter($params);
}
/**
* Apply filters (e.g. high, low) to DAO object (prior to find).
*
* @param string $filterField
* Field name of filter.
* @param string $filterValue
* Field value of filter.
* @param object $dao
* DAO object.
*/
function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
if (strstr($filterField, 'high')) {
$fieldName = substr($filterField, 0, -5);
$dao->whereAdd("($fieldName <= $filterValue )");
}
if (strstr($filterField, 'low')) {
$fieldName = substr($filterField, 0, -4);
$dao->whereAdd("($fieldName >= $filterValue )");
}
if ($filterField == 'is_current' && $filterValue == 1) {
$todayStart = date('Ymd000000', strtotime('now'));
$todayEnd = date('Ymd235959', strtotime('now'));
$dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
if (property_exists($dao, 'is_active')) {
$dao->whereAdd('is_active = 1');
}
}
}
/**
* Get sort, limit etc options from the params - supporting old & new formats.
*
* Get returnProperties for legacy
*
* @param array $params
* Params array as passed into civicrm_api.
* @param bool $queryObject
* Is this supporting a queryObject api (e.g contact) - if so we support more options.
* for legacy report & return a unique fields array
*
* @param string $entity
* @param string $action
*
* @throws API_Exception
* @return array
* options extracted from params
*/
function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
$lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
$is_count = FALSE;
$sort = CRM_Utils_Array::value('sort', $params, 0);
$sort = CRM_Utils_Array::value('option.sort', $params, $sort);
$sort = CRM_Utils_Array::value('option_sort', $params, $sort);
$offset = CRM_Utils_Array::value('offset', $params, 0);
$offset = CRM_Utils_Array::value('option.offset', $params, $offset);
// dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
$offset = CRM_Utils_Array::value('option_offset', $params, $offset);
$limit = CRM_Utils_Array::value('rowCount', $params, 25);
$limit = CRM_Utils_Array::value('option.limit', $params, $limit);
$limit = CRM_Utils_Array::value('option_limit', $params, $limit);
if (is_array(CRM_Utils_Array::value('options', $params))) {
// is count is set by generic getcount not user
$is_count = CRM_Utils_Array::value('is_count', $params['options']);
$offset = CRM_Utils_Array::value('offset', $params['options'], $offset);
$limit = CRM_Utils_Array::value('limit', $params['options'], $limit);
$sort = CRM_Utils_Array::value('sort', $params['options'], $sort);
}
$returnProperties = array();
// handle the format return =sort_name,display_name...
if (array_key_exists('return', $params)) {
if (is_array($params['return'])) {
$returnProperties = array_fill_keys($params['return'], 1);
}
else {
$returnProperties = explode(',', str_replace(' ', '', $params['return']));
$returnProperties = array_fill_keys($returnProperties, 1);
}
}
if ($entity && $action == 'get') {
if (!empty($returnProperties['id'])) {
$returnProperties[$lowercase_entity . '_id'] = 1;
unset($returnProperties['id']);
}
switch (trim(strtolower($sort))) {
case 'id':
case 'id desc':
case 'id asc':
$sort = str_replace('id', $lowercase_entity . '_id', $sort);
}
}
$options = array(
'offset' => CRM_Utils_Rule::integer($offset) ? $offset : NULL,
'sort' => CRM_Utils_Rule::string($sort) ? $sort : NULL,
'limit' => CRM_Utils_Rule::integer($limit) ? $limit : NULL,
'is_count' => $is_count,
'return' => !empty($returnProperties) ? $returnProperties : array(),
);
if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
throw new API_Exception('invalid string in sort options');
}
if (!$queryObject) {
return $options;
}
//here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
// if the query object is being used this should be used
$inputParams = array();
$legacyreturnProperties = array();
$otherVars = array(
'sort', 'offset', 'rowCount', 'options', 'return',
'version', 'prettyprint', 'check_permissions', 'sequential',
);
foreach ($params as $n => $v) {
if (substr($n, 0, 7) == 'return.') {
$legacyreturnProperties[substr($n, 7)] = $v;
}
elseif ($n == 'id') {
$inputParams[$lowercase_entity . '_id'] = $v;
}
elseif (in_array($n, $otherVars)) {
}
else {
$inputParams[$n] = $v;
if ($v && !is_array($v) && stristr($v, 'SELECT')) {
throw new API_Exception('invalid string');
}
}
}
$options['return'] = array_merge($returnProperties, $legacyreturnProperties);
$options['input_params'] = $inputParams;
return $options;
}
/**
* Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
*
* @param array $params
* Params array as passed into civicrm_api.
* @param object $dao
* DAO object.
* @param $entity
*/
function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
$options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
if (!$options['is_count']) {
if (!empty($options['limit'])) {
$dao->limit((int) $options['offset'], (int) $options['limit']);
}
if (!empty($options['sort'])) {
$dao->orderBy($options['sort']);
}
}
}
/**
* Build fields array.
*
* This is the array of fields as it relates to the given DAO
* returns unique fields as keys by default but if set but can return by DB fields
*
* @param CRM_Core_DAO $bao
* @param bool $unique
*
* @return array
*/
function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
$fields = $bao->fields();
if ($unique) {
if (empty($fields['id'])) {
$lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
$fields['id'] = $fields[$lowercase_entity . '_id'];
unset($fields[$lowercase_entity . '_id']);
}
return $fields;
}
foreach ($fields as $field) {
$dbFields[$field['name']] = $field;
}
return $dbFields;
}
/**
* Build fields array.
*
* This is the array of fields as it relates to the given DAO
* returns unique fields as keys by default but if set but can return by DB fields
*
* @param CRM_Core_DAO $bao
*
* @return array
*/
function _civicrm_api3_get_unique_name_array(&$bao) {
$fields = $bao->fields();
foreach ($fields as $field => $values) {
$uniqueFields[$field] = CRM_Utils_Array::value('name', $values, $field);
}
return $uniqueFields;
}
/**
* Converts an DAO object to an array.
*
* @deprecated - DAO based retrieval is being phased out.
*
* @param CRM_Core_DAO $dao
* Object to convert.
* @param array $params
* @param bool $uniqueFields
* @param string $entity
* @param bool $autoFind