Merge pull request #19505 from mattwire/remotememrelated
[civicrm-core.git] / api / v3 / utils.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * CiviCRM APIv3 utility functions.
14 *
15 * @package CiviCRM_APIv3
16 */
17
18 /**
19 * Initialize CiviCRM - should be run at the start of each API function.
20 */
21 function _civicrm_api3_initialize() {
22 require_once 'CRM/Core/ClassLoader.php';
23 CRM_Core_ClassLoader::singleton()->register();
24 CRM_Core_Config::singleton();
25 }
26
27 /**
28 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking.
29 *
30 * @param array $params
31 * Array of fields to check.
32 * @param array $daoName
33 * String DAO to check for required fields (create functions only).
34 * @param array $keyoptions
35 * List of required fields options. One of the options is required.
36 *
37 * @throws \API_Exception
38 */
39 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = []) {
40 $keys = [[]];
41 foreach ($keyoptions as $key) {
42 $keys[0][] = $key;
43 }
44 civicrm_api3_verify_mandatory($params, $daoName, $keys);
45 }
46
47 /**
48 * Check mandatory fields are included.
49 *
50 * @param array $params
51 * Array of fields to check.
52 * @param array $daoName
53 * String DAO to check for required fields (create functions only).
54 * @param array $keys
55 * List of required fields. A value can be an array denoting that either this or that is required.
56 * @param bool $verifyDAO
57 *
58 * @throws \API_Exception
59 */
60 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = [], $verifyDAO = TRUE) {
61 $unmatched = [];
62
63 if (!empty($params['id'])) {
64 $keys = ['version'];
65 }
66 else {
67 if (!in_array('version', $keys)) {
68 // required from v3 onwards
69 $keys[] = 'version';
70 }
71 }
72 foreach ($keys as $key) {
73 if (is_array($key)) {
74 $match = 0;
75 $optionset = [];
76 foreach ($key as $subkey) {
77 if (!array_key_exists($subkey, $params) || empty($params[$subkey])) {
78 $optionset[] = $subkey;
79 }
80 else {
81 // As long as there is one match we don't need to return anything.
82 $match = 1;
83 }
84 }
85 if (empty($match) && !empty($optionset)) {
86 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
87 }
88 }
89 else {
90 // Disallow empty values except for the number zero.
91 // TODO: create a utility for this since it's needed in many places.
92 if (!array_key_exists($key, $params) || (empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
93 $unmatched[] = $key;
94 }
95 }
96 }
97 if (!empty($unmatched)) {
98 throw new API_Exception('Mandatory key(s) missing from params array: ' . implode(", ", $unmatched), 'mandatory_missing', ["fields" => $unmatched]);
99 }
100 }
101
102 /**
103 * Create error array.
104 *
105 * @param string $msg
106 * @param array $data
107 *
108 * @return array
109 */
110 function civicrm_api3_create_error($msg, $data = []) {
111 $data['is_error'] = 1;
112 $data['error_message'] = $msg;
113
114 // we will show sql to privileged user only (not sure of a specific
115 // security hole here but seems sensible - perhaps should apply to the trace as well?)
116 if (isset($data['sql'])) {
117 if (CRM_Core_Permission::check('Administer CiviCRM') || CIVICRM_UF === 'UnitTests') {
118 // Isn't this redundant?
119 $data['debug_information'] = $data['sql'];
120 }
121 else {
122 unset($data['sql']);
123 }
124 }
125 return $data;
126 }
127
128 /**
129 * Format array in result output style.
130 *
131 * @param array|int $values values generated by API operation (the result)
132 * @param array $params
133 * Parameters passed into API call.
134 * @param string $entity
135 * The entity being acted on.
136 * @param string $action
137 * The action passed to the API.
138 * @param object $dao
139 * DAO object to be freed here.
140 * @param array $extraReturnValues
141 * Additional values to be added to top level of result array(.
142 * - this param is currently used for legacy behaviour support
143 *
144 * @return array
145 * @throws \CiviCRM_API3_Exception
146 */
147 function civicrm_api3_create_success($values = 1, $params = [], $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = []) {
148 $result = [];
149 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
150 // TODO: This shouldn't be necessary but this fn sometimes gets called with lowercase entity
151 $entity = _civicrm_api_get_camel_name($entity);
152 $result['is_error'] = 0;
153 //lets set the ['id'] field if it's not set & we know what the entity is
154 if (is_array($values) && $entity && $action !== 'getfields') {
155 foreach ($values as $key => $item) {
156 if (empty($item['id']) && !empty($item[$lowercase_entity . '_id'])) {
157 $values[$key]['id'] = $item[$lowercase_entity . '_id'];
158 }
159 if (!empty($item['financial_type_id'])) {
160 // 4.3 legacy handling.
161 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
162 }
163 if (!empty($item['contribution_cancel_date'])) {
164 // 5.16 legacy handling.
165 $values[$key]['cancel_date'] = $item['contribution_cancel_date'];
166 }
167 if (!empty($item['next_sched_contribution_date'])) {
168 // 4.4 legacy handling
169 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
170 }
171 }
172 }
173
174 if (is_array($params) && $entity && !empty($params['debug'])) {
175 if (is_string($action) && $action !== 'getfields') {
176 $apiFields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => $action] + $params);
177 }
178 elseif ($action !== 'getfields') {
179 $apiFields = civicrm_api($entity, 'getfields', ['version' => 3] + $params);
180 }
181 else {
182 $apiFields = FALSE;
183 }
184
185 $allFields = [];
186 if ($action !== 'getfields' && isset($apiFields['values']) && is_array($apiFields['values'])) {
187 $allFields = array_keys($apiFields['values']);
188 }
189 $paramFields = array_keys($params);
190 $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), [
191 'action',
192 'entity',
193 'debug',
194 'version',
195 'check_permissions',
196 'IDS_request_uri',
197 'IDS_user_agent',
198 'return',
199 'sequential',
200 'rowCount',
201 'option_offset',
202 'option_limit',
203 'custom',
204 'option_sort',
205 'options',
206 'prettyprint',
207 ]);
208 if ($undefined) {
209 $result['undefined_fields'] = array_merge($undefined);
210 }
211 }
212
213 $result['version'] = 3;
214 if (is_array($values)) {
215 $result['count'] = (int) count($values);
216
217 // Convert value-separated strings to array
218 if ($action !== 'getfields') {
219 _civicrm_api3_separate_values($values);
220 }
221
222 if ($result['count'] == 1) {
223 list($result['id']) = array_keys($values);
224 }
225 elseif (!empty($values['id']) && is_int($values['id'])) {
226 $result['id'] = $values['id'];
227 }
228 }
229 else {
230 $result['count'] = !empty($values) ? 1 : 0;
231 }
232
233 if (is_array($values) && isset($params['sequential']) &&
234 $params['sequential'] == 1
235 ) {
236 $result['values'] = array_values($values);
237 }
238 else {
239 $result['values'] = $values;
240 }
241 if (!empty($params['options']['metadata'])) {
242 // We've made metadata an array but only supporting 'fields' atm.
243 if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
244 $fields = civicrm_api3($entity, 'getfields', [
245 'action' => substr($action, 0, 3) == 'get' ? 'get' : 'create',
246 ]);
247 $result['metadata']['fields'] = $fields['values'];
248 }
249 }
250 // Report deprecations.
251 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
252 // Always report "setvalue" action as deprecated.
253 if (!is_string($deprecated) && ($action === 'getactions' || $action === 'setvalue')) {
254 $deprecated = ((array) $deprecated) + ['setvalue' => 'The "setvalue" action is deprecated. Use "create" with an id instead.'];
255 }
256 // Always report "update" action as deprecated.
257 if (!is_string($deprecated) && ($action === 'getactions' || $action === 'update')) {
258 $deprecated = ((array) $deprecated) + ['update' => 'The "update" action is deprecated. Use "create" with an id instead.'];
259 }
260 if ($deprecated) {
261 // Metadata-level deprecations or wholesale entity deprecations.
262 if ($entity === 'Entity' || $action === 'getactions' || is_string($deprecated)) {
263 $result['deprecated'] = $deprecated;
264 }
265 // Action-specific deprecations
266 elseif (!empty($deprecated[$action])) {
267 $result['deprecated'] = $deprecated[$action];
268 }
269 }
270 return array_merge($result, $extraReturnValues);
271 }
272
273 /**
274 * Load the DAO of the entity.
275 *
276 * @param $entity
277 *
278 * @return bool
279 */
280 function _civicrm_api3_load_DAO($entity) {
281 $dao = _civicrm_api3_get_DAO($entity);
282 if (empty($dao)) {
283 return FALSE;
284 }
285 $d = new $dao();
286 return $d;
287 }
288
289 /**
290 * Return the DAO of the function or Entity.
291 *
292 * @param string $name
293 * Either a function of the api (civicrm_{entity}_create or the entity name.
294 * return the DAO name to manipulate this function
295 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
296 *
297 * @return CRM_Core_DAO|string
298 */
299 function _civicrm_api3_get_DAO($name) {
300 if (strpos($name, 'civicrm_api3') !== FALSE) {
301 $last = strrpos($name, '_');
302 // len ('civicrm_api3_') == 13
303 $name = substr($name, 13, $last - 13);
304 }
305
306 $name = _civicrm_api_get_camel_name($name);
307
308 if ($name === 'Individual' || $name === 'Household' || $name === 'Organization') {
309 $name = 'Contact';
310 }
311
312 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
313
314 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
315 if ($name === 'MailingEventQueue') {
316 return 'CRM_Mailing_Event_DAO_Queue';
317 }
318 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
319 // but am not confident mailing_recipients is tested so have not tackled.
320 if ($name === 'MailingRecipients') {
321 return 'CRM_Mailing_DAO_Recipients';
322 }
323 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
324 if ($name === 'AclRole') {
325 return 'CRM_ACL_DAO_EntityRole';
326 }
327 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
328 // But this would impact SMS extensions so need to coordinate
329 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
330 if ($name === 'SmsProvider') {
331 return 'CRM_SMS_DAO_Provider';
332 }
333 // FIXME: DAO names should follow CamelCase convention
334 if ($name === 'Im' || $name === 'Acl' || $name === 'Pcp') {
335 $name = strtoupper($name);
336 }
337
338 $dao = CRM_Core_DAO_AllCoreTables::getFullName($name);
339 if ($dao || !$name) {
340 return $dao;
341 }
342
343 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
344 if (file_exists("api/v3/$name.php")) {
345 include_once "api/v3/$name.php";
346 }
347
348 $daoFn = '_civicrm_api3_' . _civicrm_api_get_entity_name_from_camel($name) . '_DAO';
349 if (function_exists($daoFn)) {
350 return $daoFn();
351 }
352
353 return NULL;
354 }
355
356 /**
357 * Return the BAO name of the function or Entity.
358 *
359 * @param string $name
360 * Is either a function of the api (civicrm_{entity}_create or the entity name.
361 * return the DAO name to manipulate this function
362 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
363 *
364 * @return string|null
365 */
366 function _civicrm_api3_get_BAO($name) {
367 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
368 if ($name === 'PrintLabel') {
369 return 'CRM_Badge_BAO_Layout';
370 }
371 if ($name === 'Order') {
372 // Order basically maps to contribution at the top level but
373 // has enhanced access to other entities.
374 $name = 'Contribution';
375 }
376 if ($name === 'Dedupe') {
377 // Dedupe is a pseudoentity for PrevNextCache - but accessing dedupe related info
378 // not the other cache info like search results (which could in fact be in Redis or another cache engine)
379 $name = 'PrevNextCache';
380 }
381 if ($name === 'Payment') {
382 $name = 'FinancialTrxn';
383 }
384 $dao = _civicrm_api3_get_DAO($name);
385 if (!$dao) {
386 return NULL;
387 }
388 $bao = str_replace("DAO", "BAO", $dao);
389 $file = strtr($bao, '_', '/') . '.php';
390 // Check if this entity actually has a BAO. Fall back on the DAO if not.
391 return stream_resolve_include_path($file) ? $bao : $dao;
392 }
393
394 /**
395 * Recursive function to explode value-separated strings into arrays.
396 *
397 * @param $values
398 */
399 function _civicrm_api3_separate_values(&$values) {
400 $sp = CRM_Core_DAO::VALUE_SEPARATOR;
401 foreach ($values as $key => & $value) {
402 if (is_array($value)) {
403 _civicrm_api3_separate_values($value);
404 }
405 elseif (is_string($value)) {
406 // This is to honor the way case API was originally written.
407 if ($key === 'case_type_id') {
408 $value = trim(str_replace($sp, ',', $value), ',');
409 }
410 elseif (strpos($value, $sp) !== FALSE) {
411 $value = explode($sp, trim($value, $sp));
412 }
413 }
414 }
415 }
416
417 /**
418 * This is a legacy wrapper for api_store_values.
419 *
420 * It checks suitable fields using getfields rather than DAO->fields.
421 *
422 * Getfields has handling for how to deal with unique names which dao->fields doesn't
423 *
424 * Note this is used by BAO type create functions - eg. contribution
425 *
426 * @param string $entity
427 * @param array $params
428 * @param array $values
429 */
430 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
431 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'create']);
432 $fields = $fields['values'];
433 _civicrm_api3_store_values($fields, $params, $values);
434 }
435
436 /**
437 * Store values.
438 *
439 * @param array $fields
440 * @param array $params
441 * @param array $values
442 *
443 * @return Bool
444 */
445 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
446 $valueFound = FALSE;
447
448 $keys = array_intersect_key($params, $fields);
449 foreach ($keys as $name => $value) {
450 if ($name !== 'id') {
451 $values[$name] = $value;
452 $valueFound = TRUE;
453 }
454 }
455 return $valueFound;
456 }
457
458 /**
459 * Returns field names of the given entity fields.
460 *
461 * @deprecated
462 * @param array $fields
463 * Fields array to retrieve the field names for.
464 * @return array
465 */
466 function _civicrm_api3_field_names($fields) {
467 CRM_Core_Error::deprecatedFunctionWarning('array_column');
468 $result = [];
469 foreach ($fields as $key => $value) {
470 if (!empty($value['name'])) {
471 $result[] = $value['name'];
472 }
473 }
474 return $result;
475 }
476
477 /**
478 * Get function for query object api.
479 *
480 * The API supports 2 types of get request. The more complex uses the BAO query object.
481 * This is a generic function for those functions that call it
482 *
483 * At the moment only called by contact we should extend to contribution &
484 * others that use the query object. Note that this function passes permission information in.
485 * The others don't
486 *
487 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
488 * 2 variants call
489 *
490 * @param $entity
491 * @param array $params
492 * As passed into api get or getcount function.
493 * @param array $additional_options
494 * Array of options (so we can modify the filter).
495 * @param bool $getCount
496 * Are we just after the count.
497 * @param int $mode
498 * This basically correlates to the component.
499 * @param null|array $defaultReturnProperties
500 * Default return properties for the entity
501 * (used if return not set - but don't do that - set return!).
502 *
503 * @return array
504 * @throws API_Exception
505 */
506 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = [], $getCount = NULL, $mode = 1, $defaultReturnProperties = NULL) {
507 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
508 // Convert id to e.g. contact_id
509 if (empty($params[$lowercase_entity . '_id']) && isset($params['id'])) {
510 $params[$lowercase_entity . '_id'] = $params['id'];
511 }
512 unset($params['id']);
513
514 $options = _civicrm_api3_get_options_from_params($params, TRUE);
515
516 $inputParams = array_merge(
517 CRM_Utils_Array::value('input_params', $options, []),
518 CRM_Utils_Array::value('input_params', $additional_options, [])
519 );
520 $returnProperties = array_merge(
521 CRM_Utils_Array::value('return', $options, []),
522 CRM_Utils_Array::value('return', $additional_options, [])
523 );
524 if (empty($returnProperties)) {
525 $returnProperties = $defaultReturnProperties;
526 }
527 if (!empty($params['check_permissions'])) {
528 // we will filter query object against getfields
529 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'get']);
530 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
531 $fields['values'][$lowercase_entity . '_id'] = [];
532 $varsToFilter = ['returnProperties', 'inputParams'];
533 foreach ($varsToFilter as $varToFilter) {
534 if (!is_array($$varToFilter)) {
535 continue;
536 }
537 //I was going to throw an exception rather than silently filter out - but
538 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
539 //so we are silently ignoring parts of their request
540 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
541 $$varToFilter = array_intersect_key($$varToFilter, $fields['values']);
542 }
543 }
544 $options = array_merge($options, $additional_options);
545 $sort = $options['sort'] ?? NULL;
546 $offset = $options['offset'] ?? NULL;
547 $limit = $options['limit'] ?? NULL;
548 $smartGroupCache = $params['smartGroupCache'] ?? NULL;
549
550 if ($getCount) {
551 $limit = NULL;
552 $returnProperties = NULL;
553 }
554
555 if (substr($sort, 0, 2) == 'id') {
556 $sort = $lowercase_entity . "_" . $sort;
557 }
558
559 $newParams = CRM_Contact_BAO_Query::convertFormValues($inputParams);
560
561 $skipPermissions = !empty($params['check_permissions']) ? 0 : 1;
562
563 list($entities) = CRM_Contact_BAO_Query::apiQuery(
564 $newParams,
565 $returnProperties,
566 NULL,
567 $sort,
568 $offset,
569 $limit,
570 $smartGroupCache,
571 $getCount,
572 $skipPermissions,
573 $mode,
574 $entity,
575 TRUE
576 );
577
578 return $entities;
579 }
580
581 /**
582 * Get dao query object based on input params.
583 *
584 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
585 * 2 variants call
586 *
587 * @param array $params
588 * @param string $mode
589 * @param string $entity
590 *
591 * @return array
592 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
593 */
594 function _civicrm_api3_get_query_object($params, $mode, $entity) {
595 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
596 $sort = $options['sort'] ?? NULL;
597 $offset = $options['offset'] ?? NULL;
598 $rowCount = $options['limit'] ?? NULL;
599 $inputParams = CRM_Utils_Array::value('input_params', $options, []);
600 $returnProperties = $options['return'] ?? NULL;
601 if (empty($returnProperties)) {
602 $returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties($mode);
603 }
604
605 $newParams = CRM_Contact_BAO_Query::convertFormValues($inputParams, 0, FALSE, $entity);
606 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
607 FALSE, FALSE, $mode,
608 empty($params['check_permissions']),
609 TRUE, TRUE, NULL, 'AND', 'NULL', TRUE
610 );
611 list($select, $from, $where, $having) = $query->query();
612
613 $sql = "$select $from $where $having";
614
615 if (!empty($sort)) {
616 $sort = CRM_Utils_Type::escape($sort, 'MysqlOrderBy');
617 $sql .= " ORDER BY $sort ";
618 }
619 if (!empty($rowCount)) {
620 $sql .= " LIMIT $offset, $rowCount ";
621 }
622 $dao = CRM_Core_DAO::executeQuery($sql);
623 return [$dao, $query];
624 }
625
626 /**
627 * Function transfers the filters being passed into the DAO onto the params object.
628 *
629 * @deprecated DAO based retrieval is being phased out.
630 *
631 * @param CRM_Core_DAO $dao
632 * @param array $params
633 * @param bool $unique
634 * @param array $extraSql
635 * API specific queries eg for event isCurrent would be converted to
636 * $extraSql['where'] = array('civicrm_event' => array('(start_date >= CURDATE() || end_date >= CURDATE())'));
637 *
638 * @throws API_Exception
639 * @throws Exception
640 */
641 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $extraSql = []) {
642 $entity = _civicrm_api_get_entity_name_from_dao($dao);
643 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
644 if (!empty($params[$lowercase_entity . "_id"]) && empty($params['id'])) {
645 //if entity_id is set then treat it as ID (will be overridden by id if set)
646 $params['id'] = $params[$lowercase_entity . "_id"];
647 }
648 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
649 $fields = array_intersect(array_keys($allfields), array_keys($params));
650
651 $options = _civicrm_api3_get_options_from_params($params);
652 //apply options like sort
653 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
654
655 //accept filters like filter.activity_date_time_high
656 // std is now 'filters' => ..
657 if (strstr(implode(',', array_keys($params)), 'filter')) {
658 if (isset($params['filters']) && is_array($params['filters'])) {
659 foreach ($params['filters'] as $paramkey => $paramvalue) {
660 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
661 }
662 }
663 else {
664 foreach ($params as $paramkey => $paramvalue) {
665 if (strstr($paramkey, 'filter')) {
666 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
667 }
668 }
669 }
670 }
671 if (!$fields) {
672 $fields = [];
673 }
674
675 foreach ($fields as $field) {
676 if (is_array($params[$field])) {
677 //get the actual fieldname from db
678 $fieldName = $allfields[$field]['name'];
679 $where = CRM_Core_DAO::createSqlFilter($fieldName, $params[$field], 'String');
680 if (!empty($where)) {
681 $dao->whereAdd($where);
682 }
683 }
684 else {
685 if ($unique) {
686 $daoFieldName = $allfields[$field]['name'];
687 if (empty($daoFieldName)) {
688 throw new API_Exception("Failed to determine field name for \"$field\"");
689 }
690 $dao->{$daoFieldName} = $params[$field];
691 }
692 else {
693 $dao->$field = $params[$field];
694 }
695 }
696 }
697 if (!empty($extraSql['where'])) {
698 foreach ($extraSql['where'] as $table => $sqlWhere) {
699 foreach ($sqlWhere as $where) {
700 $dao->whereAdd($where);
701 }
702 }
703 }
704 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
705 $dao->selectAdd();
706 // Ensure 'id' is included.
707 $options['return']['id'] = TRUE;
708 $allfields = _civicrm_api3_get_unique_name_array($dao);
709 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
710 foreach ($returnMatched as $returnValue) {
711 $dao->selectAdd($returnValue);
712 }
713
714 // Not already matched on the field names.
715 $unmatchedFields = array_diff(
716 array_keys($options['return']),
717 $returnMatched
718 );
719
720 $returnUniqueMatched = array_intersect(
721 $unmatchedFields,
722 // But a match for the field keys.
723 array_flip($allfields)
724 );
725 foreach ($returnUniqueMatched as $uniqueVal) {
726 $dao->selectAdd($allfields[$uniqueVal]);
727 }
728 }
729 $dao->setApiFilter($params);
730 }
731
732 /**
733 * Apply filters (e.g. high, low) to DAO object (prior to find).
734 *
735 * @param string $filterField
736 * Field name of filter.
737 * @param string $filterValue
738 * Field value of filter.
739 * @param object $dao
740 * DAO object.
741 */
742 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
743 if (strstr($filterField, 'high')) {
744 $fieldName = substr($filterField, 0, -5);
745 $dao->whereAdd("($fieldName <= $filterValue )");
746 }
747 if (strstr($filterField, 'low')) {
748 $fieldName = substr($filterField, 0, -4);
749 $dao->whereAdd("($fieldName >= $filterValue )");
750 }
751 if ($filterField == 'is_current' && $filterValue == 1) {
752 $todayStart = date('Ymd000000', strtotime('now'));
753 $todayEnd = date('Ymd235959', strtotime('now'));
754 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
755 if (property_exists($dao, 'is_active')) {
756 $dao->whereAdd('is_active = 1');
757 }
758 }
759 }
760
761 /**
762 * Get sort, limit etc options from the params - supporting old & new formats.
763 *
764 * Get returnProperties for legacy
765 *
766 * @param array $params
767 * Params array as passed into civicrm_api.
768 * @param bool $queryObject
769 * Is this supporting a queryObject api (e.g contact) - if so we support more options.
770 * for legacy report & return a unique fields array
771 *
772 * @param string $entity
773 * @param string $action
774 *
775 * @throws API_Exception
776 * @return array
777 * options extracted from params
778 */
779 function _civicrm_api3_get_options_from_params($params, $queryObject = FALSE, $entity = '', $action = '') {
780 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
781 $is_count = FALSE;
782
783 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
784 $sort = $params['option_sort'] ?? $params['option.sort'] ?? $params['sort'] ?? 0;
785 $offset = $params['option_offset'] ?? $params['option.offset'] ?? $params['offset'] ?? 0;
786
787 $limit = CRM_Utils_Array::value('rowCount', $params, 25);
788 $limit = CRM_Utils_Array::value('option.limit', $params, $limit);
789 $limit = CRM_Utils_Array::value('option_limit', $params, $limit);
790
791 if (isset($params['options']) && is_array($params['options'])) {
792 // is count is set by generic getcount not user
793 $is_count = $params['options']['is_count'] ?? FALSE;
794 $offset = $params['options']['offset'] ?? $offset;
795 $limit = CRM_Utils_Array::value('limit', $params['options'], $limit);
796 $sort = $params['options']['sort'] ?? $sort;
797 }
798
799 $returnProperties = [];
800 // handle the format return =sort_name,display_name...
801 if (array_key_exists('return', $params)) {
802 if (is_array($params['return'])) {
803 $returnProperties = array_fill_keys($params['return'], 1);
804 }
805 else {
806 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
807 $returnProperties = array_fill_keys($returnProperties, 1);
808 }
809 }
810 if ($entity && $action == 'get') {
811 if (!empty($returnProperties['id'])) {
812 $returnProperties[$lowercase_entity . '_id'] = 1;
813 unset($returnProperties['id']);
814 }
815 }
816
817 $options = [
818 'offset' => CRM_Utils_Rule::integer($offset) ? $offset : NULL,
819 'limit' => (!$is_count && CRM_Utils_Rule::integer($limit)) ? $limit : NULL,
820 'is_count' => $is_count,
821 'return' => !empty($returnProperties) ? $returnProperties : [],
822 ];
823
824 $finalSort = [];
825 $options['sort'] = NULL;
826 if (!empty($sort)) {
827 if (!is_array($sort)) {
828 $sort = array_map('trim', explode(',', $sort));
829 }
830 foreach ($sort as $s) {
831 if ($s === '(1)' || CRM_Utils_Rule::mysqlOrderBy($s)) {
832 if ($entity && $action === 'get') {
833 switch (trim(strtolower($s))) {
834 case 'id':
835 case 'id desc':
836 case 'id asc':
837 $s = str_replace('id', $lowercase_entity . '_id', $s);
838 }
839 }
840 $finalSort[] = $s;
841 }
842 else {
843 throw new API_Exception("Unknown field specified for sort. Cannot order by '$s'");
844 }
845 }
846 $options['sort'] = implode(', ', $finalSort);
847 }
848
849 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
850 throw new API_Exception('invalid string in sort options');
851 }
852
853 if (!$queryObject) {
854 return $options;
855 }
856 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
857 // if the query object is being used this should be used
858 $inputParams = [];
859 $legacyreturnProperties = [];
860 $otherVars = [
861 'sort', 'offset', 'rowCount', 'options', 'return',
862 'version', 'prettyprint', 'check_permissions', 'sequential',
863 ];
864 foreach ($params as $n => $v) {
865 if (substr($n, 0, 7) === 'return.') {
866 $legacyreturnProperties[substr($n, 7)] = $v;
867 }
868 elseif ($n === 'id') {
869 $inputParams[$lowercase_entity . '_id'] = $v;
870 }
871 elseif (!in_array($n, $otherVars)) {
872 $inputParams[$n] = $v;
873 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
874 throw new API_Exception('invalid string');
875 }
876 }
877 }
878 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
879 $options['input_params'] = $inputParams;
880 return $options;
881 }
882
883 /**
884 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
885 *
886 * @param array $params
887 * Params array as passed into civicrm_api.
888 * @param object $dao
889 * DAO object.
890 * @param $entity
891 *
892 * @throws \API_Exception
893 * @throws \CRM_Core_Exception
894 */
895 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
896
897 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
898 if (!$options['is_count']) {
899 if (!empty($options['limit'])) {
900 $dao->limit((int) $options['offset'], (int) $options['limit']);
901 }
902 if (!empty($options['sort'])) {
903 $options['sort'] = CRM_Utils_Type::escape($options['sort'], 'MysqlOrderBy');
904 $dao->orderBy($options['sort']);
905 }
906 }
907 }
908
909 /**
910 * Build fields array.
911 *
912 * This is the array of fields as it relates to the given DAO
913 * returns unique fields as keys by default but if set but can return by DB fields
914 *
915 * @param CRM_Core_DAO $bao
916 * @param bool $unique
917 *
918 * @return array
919 */
920 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
921 $fields = $bao->fields();
922 if ($unique) {
923 if (empty($fields['id'])) {
924 $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
925 if (isset($fields[$lowercase_entity . '_id'])) {
926 $fields['id'] = $fields[$lowercase_entity . '_id'];
927 unset($fields[$lowercase_entity . '_id']);
928 }
929 }
930 return $fields;
931 }
932
933 foreach ($fields as $field) {
934 $dbFields[$field['name']] = $field;
935 }
936 return $dbFields;
937 }
938
939 /**
940 * Build fields array.
941 *
942 * This is the array of fields as it relates to the given DAO
943 * returns unique fields as keys by default but if set but can return by DB fields
944 *
945 * @param CRM_Core_DAO $bao
946 *
947 * @return array
948 */
949 function _civicrm_api3_get_unique_name_array(&$bao) {
950 $fields = $bao->fields();
951 foreach ($fields as $field => $values) {
952 $uniqueFields[$field] = CRM_Utils_Array::value('name', $values, $field);
953 }
954 return $uniqueFields;
955 }
956
957 /**
958 * Converts an DAO object to an array.
959 *
960 * @param CRM_Core_DAO $dao
961 * Object to convert.
962 * @param array $params
963 * @param bool $uniqueFields
964 * @param string $entity
965 * @param bool $autoFind
966 *
967 * @return array
968 *
969 * @throws \API_Exception
970 *
971 * @deprecated - DAO based retrieval is being phased out.
972 *
973 */
974 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
975 $result = [];
976 if (isset($params['options']) && !empty($params['options']['is_count'])) {
977 return $dao->count();
978 }
979 if (empty($dao)) {
980 return [];
981 }
982 if ($autoFind && !$dao->find()) {
983 return [];
984 }
985
986 if (isset($dao->count)) {
987 return $dao->count;
988 }
989
990 $fields = array_keys(_civicrm_api3_build_fields_array($dao, FALSE));
991 while ($dao->fetch()) {
992 $tmp = [];
993 foreach ($fields as $key) {
994 if (property_exists($dao, $key)) {
995 // not sure on that one
996 if ($dao->$key !== NULL) {
997 $tmp[$key] = $dao->$key;
998 }
999 }
1000 }
1001 $result[$dao->id] = $tmp;
1002
1003 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
1004 _civicrm_api3_custom_data_get($result[$dao->id], $params['check_permissions'], $entity, $dao->id);
1005 }
1006 }
1007
1008 return $result;
1009 }
1010
1011 /**
1012 * Determine if custom fields need to be retrieved.
1013 *
1014 * We currently retrieve all custom fields or none at this level so if we know the entity
1015 * && it can take custom fields & there is the string 'custom' in their return request we get them all, they are filtered on the way out
1016 *
1017 * @param string $entity
1018 * Entity name in CamelCase.
1019 * @param array $params
1020 *
1021 * @return bool
1022 * @throws \API_Exception
1023 *
1024 * @todo filter so only required fields are queried
1025 */
1026 function _civicrm_api3_custom_fields_are_required($entity, $params) {
1027 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery::$extendsMap)) {
1028 return FALSE;
1029 }
1030 $options = _civicrm_api3_get_options_from_params($params);
1031 // We check for possibility of 'custom' => 1 as well as specific custom fields.
1032 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
1033 if (stristr($returnString, 'custom')) {
1034 return TRUE;
1035 }
1036 }
1037
1038 /**
1039 * Converts an object to an array.
1040 *
1041 * @param object $dao
1042 * (reference) object to convert.
1043 * @param array $values
1044 * (reference) array.
1045 * @param array|bool $uniqueFields
1046 */
1047 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
1048
1049 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
1050 foreach ($fields as $key => $value) {
1051 if (property_exists($dao, $key)) {
1052 $values[$key] = $dao->$key ?? NULL;
1053 }
1054 }
1055 }
1056
1057 /**
1058 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1059 *
1060 * @param $dao
1061 * @param $values
1062 *
1063 * @return array
1064 */
1065 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1066 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1067 }
1068
1069 /**
1070 * Format custom parameters.
1071 *
1072 * @param array $params
1073 * @param array $values
1074 * @param string $extends
1075 * Entity that this custom field extends (e.g. contribution, event, contact).
1076 * @param string $entityId
1077 * ID of entity per $extends.
1078 */
1079 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1080 $values['custom'] = [];
1081 $checkCheckBoxField = FALSE;
1082 $entity = $extends;
1083 if (in_array($extends, ['Household', 'Individual', 'Organization'])) {
1084 $entity = 'Contact';
1085 }
1086
1087 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'create']);
1088 if (!$fields['is_error']) {
1089 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1090 $fields = $fields['values'];
1091 $checkCheckBoxField = TRUE;
1092 }
1093
1094 foreach ($params as $key => $value) {
1095 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField::getKeyID($key, TRUE);
1096 if ($customFieldID && (!is_null($value))) {
1097 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1098 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1099 }
1100
1101 CRM_Core_BAO_CustomField::formatCustomField($customFieldID, $values['custom'],
1102 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1103 );
1104 }
1105 }
1106 }
1107
1108 /**
1109 * Format parameters for create action.
1110 *
1111 * @param array $params
1112 * @param $entity
1113 */
1114 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1115 $nonGenericEntities = ['Contact', 'Individual', 'Household', 'Organization'];
1116
1117 $customFieldEntities = array_diff_key(CRM_Core_SelectValues::customGroupExtends(), array_fill_keys($nonGenericEntities, 1));
1118 if (!array_key_exists($entity, $customFieldEntities)) {
1119 return;
1120 }
1121 $values = [];
1122 _civicrm_api3_custom_format_params($params, $values, $entity);
1123 $params = array_merge($params, $values);
1124 }
1125
1126 /**
1127 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1128 *
1129 * We should look at pushing to BAO function
1130 * and / or validate function but this is a safe place for now as it has massive test coverage & we can keep the change very specific
1131 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1132 *
1133 * We will only alter the value if we are sure that changing it will make it correct - if it appears wrong but does not appear to have a clear fix we
1134 * don't touch - lots of very cautious code in here
1135 *
1136 * The resulting array should look like
1137 * array(
1138 * 'key' => 1,
1139 * 'key1' => 1,
1140 * );
1141 *
1142 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1143 *
1144 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1145 * be fixed in future
1146 *
1147 * @param mixed $checkboxFieldValue
1148 * @param string $customFieldLabel
1149 * @param string $entity
1150 */
1151 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1152
1153 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO::VALUE_SEPARATOR)) {
1154 // We can assume it's pre-formatted.
1155 return;
1156 }
1157 $options = civicrm_api($entity, 'getoptions', ['field' => $customFieldLabel, 'version' => 3]);
1158 if (!empty($options['is_error'])) {
1159 // The check is precautionary - can probably be removed later.
1160 return;
1161 }
1162
1163 $options = $options['values'];
1164 $validValue = TRUE;
1165 if (is_array($checkboxFieldValue)) {
1166 foreach ($checkboxFieldValue as $key => $value) {
1167 if (!array_key_exists($key, $options)) {
1168 $validValue = FALSE;
1169 }
1170 }
1171 if ($validValue) {
1172 // we have been passed an array that is already in the 'odd' custom field format
1173 return;
1174 }
1175 }
1176
1177 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1178 // if the array only has one item we'll treat it like any other string
1179 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1180 $possibleValue = reset($checkboxFieldValue);
1181 }
1182 if (is_string($checkboxFieldValue)) {
1183 $possibleValue = $checkboxFieldValue;
1184 }
1185 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1186 $checkboxFieldValue = CRM_Core_DAO::VALUE_SEPARATOR . $possibleValue . CRM_Core_DAO::VALUE_SEPARATOR;
1187 return;
1188 }
1189 elseif (is_array($checkboxFieldValue)) {
1190 // so this time around we are considering the values in the array
1191 $possibleValues = $checkboxFieldValue;
1192 $formatValue = TRUE;
1193 }
1194 elseif (stristr($checkboxFieldValue, ',')) {
1195 $formatValue = TRUE;
1196 //lets see if we should separate it - we do this near the end so we
1197 // ensure we have already checked that the comma is not part of a legitimate match
1198 // and of course, we don't make any changes if we don't now have matches
1199 $possibleValues = explode(',', $checkboxFieldValue);
1200 }
1201 else {
1202 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1203 return;
1204 }
1205
1206 foreach ($possibleValues as $index => $possibleValue) {
1207 if (array_key_exists($possibleValue, $options)) {
1208 // do nothing - we will leave formatValue set to true unless another value is not found (which would cause us to ignore the whole value set)
1209 }
1210 elseif (array_key_exists(trim($possibleValue), $options)) {
1211 $possibleValues[$index] = trim($possibleValue);
1212 }
1213 else {
1214 $formatValue = FALSE;
1215 }
1216 }
1217 if ($formatValue) {
1218 $checkboxFieldValue = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $possibleValues) . CRM_Core_DAO::VALUE_SEPARATOR;
1219 }
1220 }
1221
1222 /**
1223 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1224 *
1225 * @param string|CRM_Core_DAO $bao_name
1226 * Name of BAO.
1227 * @param array $params
1228 * Params from api.
1229 * @param bool $returnAsSuccess
1230 * Return in api success format.
1231 * @param string $entity
1232 * @param CRM_Utils_SQL_Select|NULL $sql
1233 * Extra SQL bits to add to the query. For filtering current events, this might be:
1234 * CRM_Utils_SQL_Select::fragment()->where('(start_date >= CURDATE() || end_date >= CURDATE())');
1235 * @param bool $uniqueFields
1236 * Should unique field names be returned (for backward compatibility)
1237 *
1238 * @return array
1239 */
1240 function _civicrm_api3_basic_get($bao_name, $params, $returnAsSuccess = TRUE, $entity = "", $sql = NULL, $uniqueFields = FALSE) {
1241 $entity = $entity ?: CRM_Core_DAO_AllCoreTables::getBriefName($bao_name);
1242 $options = _civicrm_api3_get_options_from_params($params);
1243
1244 // Skip query if table doesn't exist yet due to pending upgrade
1245 if (!$bao_name::tableHasBeenAdded()) {
1246 \Civi::log()->warning("Could not read from {$entity} before table has been added. Upgrade required.", ['civi.tag' => 'upgrade_needed']);
1247 $result = [];
1248 }
1249 else {
1250 $query = new \Civi\API\Api3SelectQuery($entity, $params['check_permissions'] ?? FALSE);
1251 $query->where = $params;
1252 if ($options['is_count']) {
1253 $query->select = ['count_rows'];
1254 }
1255 else {
1256 $query->select = array_keys(array_filter($options['return']));
1257 $query->orderBy = $options['sort'];
1258 $query->isFillUniqueFields = $uniqueFields;
1259 }
1260 $query->limit = $options['limit'];
1261 $query->offset = $options['offset'];
1262 $query->merge($sql);
1263 $result = $query->run();
1264 }
1265
1266 if ($returnAsSuccess) {
1267 return civicrm_api3_create_success($result, $params, $entity, 'get');
1268 }
1269 return $result;
1270 }
1271
1272 /**
1273 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1274 *
1275 * @param string $bao_name
1276 * Name of BAO Class.
1277 * @param array $params
1278 * Parameters passed into the api call.
1279 * @param string $entity
1280 * Entity - pass in if entity is non-standard & required $ids array.
1281 *
1282 * @throws API_Exception
1283 * @throws \Civi\API\Exception\UnauthorizedException
1284 * @return array
1285 */
1286 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1287 _civicrm_api3_check_edit_permissions($bao_name, $params);
1288 _civicrm_api3_format_params_for_create($params, $entity);
1289 $args = array(&$params);
1290 if ($entity) {
1291 $ids = [$entity => CRM_Utils_Array::value('id', $params)];
1292 $args[] = &$ids;
1293 }
1294
1295 if (method_exists($bao_name, 'create')) {
1296 $fct = 'create';
1297 $fct_name = $bao_name . '::' . $fct;
1298 $bao = call_user_func_array([$bao_name, $fct], $args);
1299 }
1300 elseif (method_exists($bao_name, 'add')) {
1301 $fct = 'add';
1302 $fct_name = $bao_name . '::' . $fct;
1303 $bao = call_user_func_array([$bao_name, $fct], $args);
1304 }
1305 else {
1306 $fct_name = '_civicrm_api3_basic_create_fallback';
1307 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1308 }
1309
1310 if (is_null($bao)) {
1311 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1312 }
1313 elseif (is_a($bao, 'CRM_Core_Error')) {
1314 //some weird circular thing means the error takes itself as an argument
1315 $msg = $bao->getMessages($bao);
1316 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1317 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1318 // so we need to reset the error object here to avoid getting concatenated errors
1319 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1320 CRM_Core_Error::singleton()->reset();
1321 throw new API_Exception($msg);
1322 }
1323 else {
1324 // If we have custom fields the BAO may have taken care of it or we may have to.
1325 // $extendsMap provides a pretty good hard-coded list of BAOs that take care of the custom data.
1326 if (isset($params['custom']) && empty(CRM_Core_BAO_CustomQuery::$extendsMap[$entity])) {
1327 CRM_Core_BAO_CustomValueTable::store($params['custom'], CRM_Core_DAO_AllCoreTables::getTableForClass(CRM_Core_DAO_AllCoreTables::getFullName($entity)), $bao->id);
1328 }
1329 $values = [];
1330 _civicrm_api3_object_to_array($bao, $values[$bao->id]);
1331 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1332 }
1333 }
1334
1335 /**
1336 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1337 *
1338 * @param string|CRM_Core_DAO $bao_name
1339 * @param array $params
1340 *
1341 * @throws API_Exception
1342 *
1343 * @return CRM_Core_DAO|NULL
1344 * An instance of the BAO
1345 */
1346 function _civicrm_api3_basic_create_fallback($bao_name, $params) {
1347 return $bao_name::writeRecord($params);
1348 }
1349
1350 /**
1351 * Function to do a 'standard' api del.
1352 *
1353 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1354 *
1355 * @param string|CRM_Core_DAO $bao_name
1356 * @param array $params
1357 *
1358 * @return array
1359 * API result array
1360 *
1361 * @throws API_Exception
1362 * @throws \Civi\API\Exception\UnauthorizedException
1363 * @throws \CiviCRM_API3_Exception
1364 */
1365 function _civicrm_api3_basic_delete($bao_name, &$params) {
1366 civicrm_api3_verify_mandatory($params, NULL, ['id']);
1367 _civicrm_api3_check_edit_permissions($bao_name, ['id' => $params['id']]);
1368 if (method_exists($bao_name, 'del')) {
1369 $args = [&$params['id']];
1370 $dao = new $bao_name();
1371 $dao->id = $params['id'];
1372 if ($dao->find()) {
1373 $bao = call_user_func_array([$bao_name, 'del'], $args);
1374 if ($bao !== FALSE) {
1375 return civicrm_api3_create_success();
1376 }
1377 throw new API_Exception('Could not delete entity id ' . $params['id']);
1378 }
1379 throw new API_Exception('Could not delete entity id ' . $params['id']);
1380 }
1381 else {
1382 $bao_name::deleteRecord($params);
1383 return civicrm_api3_create_success();
1384 }
1385 }
1386
1387 /**
1388 * Get custom data for the given entity & Add it to the returnArray.
1389 *
1390 * This looks like 'custom_123' = 'custom string' AND
1391 * 'custom_123_1' = 'custom string'
1392 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1393 *
1394 * @param array $returnArray
1395 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1396 * @param $checkPermission
1397 * @param string $entity
1398 * E.g membership, event.
1399 * @param int $entity_id
1400 * @param int $groupID
1401 * Per CRM_Core_BAO_CustomGroup::getTree.
1402 * @param int $subType
1403 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1404 * @param string $subName
1405 * Subtype of entity.
1406 *
1407 * @throws \CRM_Core_Exception
1408 */
1409 function _civicrm_api3_custom_data_get(&$returnArray, $checkPermission, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1410 $groupTree = CRM_Core_BAO_CustomGroup::getTree($entity,
1411 NULL,
1412 $entity_id,
1413 $groupID,
1414 NULL,
1415 $subName,
1416 TRUE,
1417 NULL,
1418 TRUE,
1419 $checkPermission
1420 );
1421 $groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1);
1422 $customValues = [];
1423 CRM_Core_BAO_CustomGroup::setDefaults($groupTree, $customValues);
1424 $fieldInfo = [];
1425 foreach ($groupTree as $set) {
1426 $fieldInfo += $set['fields'];
1427 }
1428 if (!empty($customValues)) {
1429 foreach ($customValues as $key => $val) {
1430 // per standard - return custom_fieldID
1431 $id = CRM_Core_BAO_CustomField::getKeyID($key);
1432 $returnArray['custom_' . $id] = $val;
1433
1434 //not standard - but some api did this so guess we should keep - cheap as chips
1435 $returnArray[$key] = $val;
1436
1437 // Shim to restore legacy behavior of ContactReference custom fields
1438 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] === 'ContactReference') {
1439 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1440 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1441 }
1442 }
1443 }
1444 }
1445
1446 /**
1447 * Used by the Validate API.
1448 *
1449 * @param string $entity
1450 * @param string $action
1451 * @param array $params
1452 *
1453 * @return array $errors
1454 * @throws \CiviCRM_API3_Exception
1455 */
1456 function _civicrm_api3_validate($entity, $action, $params) {
1457 $errors = [];
1458 $fields = civicrm_api3($entity, 'getfields', ['sequential' => 1, 'api_action' => $action]);
1459 $fields = $fields['values'];
1460
1461 // Check for required fields.
1462 foreach ($fields as $values) {
1463 if (!empty($values['api.required']) && empty($params[$values['name']])) {
1464 $errors[$values['name']] = [
1465 'message' => 'Mandatory key(s) missing from params array: ' . $values['name'],
1466 'code' => 'mandatory_missing',
1467 ];
1468 }
1469 }
1470
1471 // Select only the fields which have been input as a param.
1472 $finalfields = [];
1473 foreach ($fields as $values) {
1474 if (array_key_exists($values['name'], $params)) {
1475 $finalfields[] = $values;
1476 }
1477 }
1478
1479 // This derives heavily from the function "_civicrm_api3_validate_fields".
1480 // However, the difference is that try-catch blocks are nested in the loop, making it
1481 // possible for us to get all errors in one go.
1482 foreach ($finalfields as $fieldInfo) {
1483 $fieldName = $fieldInfo['name'];
1484 try {
1485 _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params);
1486 }
1487 catch (Exception $e) {
1488 $errors[$fieldName] = [
1489 'message' => $e->getMessage(),
1490 'code' => 'incorrect_value',
1491 ];
1492 }
1493 }
1494
1495 return [$errors];
1496 }
1497
1498 /**
1499 * Used by the Validate API.
1500 * @param $fieldName
1501 * @param array $fieldInfo
1502 * @param string $entity
1503 * @param array $params
1504 *
1505 * @throws API_Exception
1506 * @throws Exception
1507 */
1508 function _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params) {
1509 switch (CRM_Utils_Array::value('type', $fieldInfo)) {
1510 case CRM_Utils_Type::T_INT:
1511 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1512 break;
1513
1514 case CRM_Utils_Type::T_DATE:
1515 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
1516 case CRM_Utils_Type::T_TIMESTAMP:
1517 //field is of type date or datetime
1518 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1519 break;
1520
1521 case CRM_Utils_Type::T_TEXT:
1522 case CRM_Utils_Type::T_STRING:
1523 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1524 break;
1525
1526 case CRM_Utils_Type::T_MONEY:
1527 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1528
1529 foreach ((array) $fieldValue as $fieldvalue) {
1530 if (!CRM_Utils_Rule::money($fieldvalue) && !empty($fieldvalue)) {
1531 throw new Exception($fieldName . ' is not a valid amount: ' . $params[$fieldName]);
1532 }
1533 }
1534 break;
1535 }
1536 }
1537
1538 /**
1539 * Validate fields being passed into API.
1540 *
1541 * This function relies on the getFields function working accurately
1542 * for the given API.
1543 *
1544 * As of writing only date was implemented.
1545 *
1546 * @param string $entity
1547 * @param string $action
1548 * @param array $params
1549 * -.
1550 * @param array $fields
1551 * Response from getfields all variables are the same as per civicrm_api.
1552 *
1553 * @throws Exception
1554 */
1555 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields) {
1556 //CRM-15792 handle datetime for custom fields below code handles chain api call
1557 $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params)));
1558 if (!empty($chainApikeys) && is_array($chainApikeys)) {
1559 foreach ($chainApikeys as $key => $value) {
1560 if (is_array($params[$key])) {
1561 $chainApiParams = array_intersect_key($fields, $params[$key]);
1562 $customFields = array_fill_keys(array_keys($params[$key]), $key);
1563 }
1564 }
1565 }
1566 $fields = array_intersect_key($fields, $params);
1567 if (!empty($chainApiParams)) {
1568 $fields = array_merge($fields, $chainApiParams);
1569 }
1570 foreach ($fields as $fieldName => $fieldInfo) {
1571 switch (CRM_Utils_Array::value('type', $fieldInfo)) {
1572 case CRM_Utils_Type::T_INT:
1573 //field is of type integer
1574 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1575 break;
1576
1577 case CRM_Utils_Type::T_DATE:
1578 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
1579 case CRM_Utils_Type::T_TIMESTAMP:
1580 //field is of type date or datetime
1581 if (!empty($customFields) && array_key_exists($fieldName, $customFields)) {
1582 $dateParams = &$params[$customFields[$fieldName]];
1583 }
1584 else {
1585 $dateParams = &$params;
1586 }
1587 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
1588 break;
1589
1590 case CRM_Utils_Type::T_TEXT:
1591 case CRM_Utils_Type::T_STRING:
1592 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1593 break;
1594
1595 case CRM_Utils_Type::T_MONEY:
1596 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1597 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
1598 break;
1599 }
1600 foreach ((array) $fieldValue as $fieldvalue) {
1601 if (!CRM_Utils_Rule::money($fieldvalue) && !empty($fieldvalue)) {
1602 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1603 }
1604 }
1605 break;
1606 }
1607 }
1608 }
1609
1610 /**
1611 * Validate foreign key values of fields being passed into API.
1612 *
1613 * This function relies on the getFields function working accurately
1614 * for the given API.
1615 *
1616 * @param string $entity
1617 * @param string $action
1618 * @param array $params
1619 *
1620 * @param array $fields
1621 * Response from getfields all variables are the same as per civicrm_api.
1622 *
1623 * @throws Exception
1624 */
1625 function _civicrm_api3_validate_foreign_keys($entity, $action, &$params, $fields) {
1626 // intensive checks - usually only called after DB level fail
1627 foreach ($fields as $fieldName => $fieldInfo) {
1628 if (!empty($fieldInfo['FKClassName'])) {
1629 if (!empty($params[$fieldName])) {
1630 foreach ((array) $params[$fieldName] as $fieldValue) {
1631 _civicrm_api3_validate_constraint($fieldValue, $fieldName, $fieldInfo, $entity);
1632 }
1633 }
1634 elseif (!empty($fieldInfo['required'])) {
1635 throw new Exception("DB Constraint Violation - $fieldName should possibly be marked as mandatory for $entity,$action API. If so, please raise a bug report.");
1636 }
1637 }
1638 if (!empty($fieldInfo['api.unique'])) {
1639 $params['entity'] = $entity;
1640 _civicrm_api3_validate_unique_key($params, $fieldName);
1641 }
1642 }
1643 }
1644
1645 /**
1646 * Validate date fields being passed into API.
1647 *
1648 * It currently converts both unique fields and DB field names to a mysql date.
1649 * @todo - probably the unique field handling & the if exists handling is now done before this
1650 * function is reached in the wrapper - can reduce this code down to assume we
1651 * are only checking the passed in field
1652 *
1653 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1654 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1655 *
1656 * @param array $params
1657 * Params from civicrm_api.
1658 * @param string $fieldName
1659 * Uniquename of field being checked.
1660 * @param array $fieldInfo
1661 * Array of fields from getfields function.
1662 *
1663 * @throws Exception
1664 */
1665 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1666 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1667 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
1668 return;
1669 }
1670
1671 if ($fieldValue === 'null' && empty($fieldInfo['api.required'])) {
1672 // This is the wierd & wonderful way PEAR sets null.
1673 return;
1674 }
1675
1676 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1677 if (!empty($params[$fieldInfo['name']])) {
1678 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1679 }
1680 if ((CRM_Utils_Array::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1681 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1682 }
1683
1684 if (!empty($op)) {
1685 $params[$fieldName][$op] = $fieldValue;
1686 }
1687 else {
1688 $params[$fieldName] = $fieldValue;
1689 }
1690 }
1691
1692 /**
1693 * Convert date into BAO friendly date.
1694 *
1695 * We accept 'whatever strtotime accepts'
1696 *
1697 * @param string $dateValue
1698 * @param string $fieldName
1699 * @param $fieldType
1700 *
1701 * @throws Exception
1702 * @return mixed
1703 */
1704 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1705 if (is_array($dateValue)) {
1706 foreach ($dateValue as $key => $value) {
1707 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1708 }
1709 return $dateValue;
1710 }
1711 if (strtotime($dateValue) === FALSE) {
1712 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1713 }
1714 $format = ($fieldType == CRM_Utils_Type::T_DATE) ? 'Ymd000000' : 'YmdHis';
1715 return CRM_Utils_Date::processDate($dateValue, NULL, FALSE, $format);
1716 }
1717
1718 /**
1719 * Validate foreign constraint fields being passed into API.
1720 *
1721 * @param mixed $fieldValue
1722 * @param string $fieldName
1723 * Unique name of field being checked.
1724 * @param array $fieldInfo
1725 * Array of fields from getfields function.
1726 * @param string $entity
1727 *
1728 * @throws \API_Exception
1729 */
1730 function _civicrm_api3_validate_constraint($fieldValue, $fieldName, $fieldInfo, $entity) {
1731 $daoName = $fieldInfo['FKClassName'];
1732 $fieldInfo = [$fieldName => $fieldInfo];
1733 $params = [$fieldName => $fieldValue];
1734 _civicrm_api3_validate_fields($entity, NULL, $params, $fieldInfo);
1735 /* @var CRM_Core_DAO $dao*/
1736 $dao = new $daoName();
1737 $dao->id = $params[$fieldName];
1738 $dao->selectAdd();
1739 $dao->selectAdd('id');
1740 if (!$dao->find()) {
1741 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1742 }
1743 }
1744
1745 /**
1746 * Validate foreign constraint fields being passed into API.
1747 *
1748 * @param array $params
1749 * Params from civicrm_api.
1750 * @param string $fieldName
1751 * Uniquename of field being checked.
1752 *
1753 * @throws Exception
1754 */
1755 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1756 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1757 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
1758 return;
1759 }
1760 $existing = civicrm_api($params['entity'], 'get', [
1761 'version' => $params['version'],
1762 $fieldName => $fieldValue,
1763 ]);
1764 // an entry already exists for this unique field
1765 if ($existing['count'] == 1) {
1766 // question - could this ever be a security issue?
1767 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1768 }
1769 }
1770
1771 /**
1772 * Generic implementation of the "replace" action.
1773 *
1774 * Replace the old set of entities (matching some given keys) with a new set of
1775 * entities (matching the same keys).
1776 *
1777 * @note This will verify that 'values' is present, but it does not directly verify
1778 * any other parameters.
1779 *
1780 * @param string $entity
1781 * Entity name.
1782 * @param array $params
1783 * Params from civicrm_api, including:.
1784 * - 'values': an array of records to save
1785 * - all other items: keys which identify new/pre-existing records.
1786 *
1787 * @return array|int
1788 */
1789 function _civicrm_api3_generic_replace($entity, $params) {
1790
1791 $transaction = new CRM_Core_Transaction();
1792 try {
1793 if (!is_array($params['values'])) {
1794 throw new Exception("Mandatory key(s) missing from params array: values");
1795 }
1796
1797 // Extract the keys -- somewhat scary, don't think too hard about it
1798 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1799
1800 // Lookup pre-existing records
1801 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1802 if (civicrm_error($preexisting)) {
1803 $transaction->rollback();
1804 return $preexisting;
1805 }
1806
1807 // Save the new/updated records
1808 $creates = [];
1809 foreach ($params['values'] as $replacement) {
1810 // Sugar: Don't force clients to duplicate the 'key' data
1811 $replacement = array_merge($baseParams, $replacement);
1812 $action = (isset($replacement['id']) || isset($replacement[$entity . '_id'])) ? 'update' : 'create';
1813 $create = civicrm_api($entity, $action, $replacement);
1814 if (civicrm_error($create)) {
1815 $transaction->rollback();
1816 return $create;
1817 }
1818 foreach ($create['values'] as $entity_id => $entity_value) {
1819 $creates[$entity_id] = $entity_value;
1820 }
1821 }
1822
1823 // Remove stale records
1824 $staleIDs = array_diff(
1825 array_keys($preexisting['values']),
1826 array_keys($creates)
1827 );
1828 foreach ($staleIDs as $staleID) {
1829 $delete = civicrm_api($entity, 'delete', [
1830 'version' => $params['version'],
1831 'id' => $staleID,
1832 ]);
1833 if (civicrm_error($delete)) {
1834 $transaction->rollback();
1835 return $delete;
1836 }
1837 }
1838
1839 return civicrm_api3_create_success($creates, $params);
1840 }
1841 catch (PEAR_Exception $e) {
1842 $transaction->rollback();
1843 return civicrm_api3_create_error($e->getMessage());
1844 }
1845 catch (Exception $e) {
1846 $transaction->rollback();
1847 return civicrm_api3_create_error($e->getMessage());
1848 }
1849 }
1850
1851 /**
1852 * Replace base parameters.
1853 *
1854 * @param array $params
1855 *
1856 * @return array
1857 */
1858 function _civicrm_api3_generic_replace_base_params($params) {
1859 $baseParams = $params;
1860 unset($baseParams['values']);
1861 unset($baseParams['sequential']);
1862 unset($baseParams['options']);
1863 return $baseParams;
1864 }
1865
1866 /**
1867 * Returns fields allowable by api.
1868 *
1869 * @param $entity
1870 * String Entity to query.
1871 * @param bool $unique
1872 * Index by unique fields?.
1873 * @param array $params
1874 *
1875 * @return array
1876 */
1877 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = []) {
1878 $unsetIfEmpty = [
1879 'dataPattern',
1880 'headerPattern',
1881 'default',
1882 'export',
1883 'import',
1884 ];
1885 $dao = _civicrm_api3_get_DAO($entity);
1886 if (empty($dao)) {
1887 return [];
1888 }
1889 $fields = $dao::fields();
1890 $supportedFields = $dao::getSupportedFields();
1891
1892 foreach ($fields as $name => $field) {
1893 // Denote as core field
1894 $fields[$name]['is_core_field'] = TRUE;
1895 // Set html attributes for text fields
1896 if (isset($field['html'])) {
1897 $fields[$name]['html'] += (array) $dao::makeAttribute($field);
1898 }
1899 // Delete field if not supported by current db schema (prevents errors when there are pending db updates)
1900 if (!isset($supportedFields[$field['name']])) {
1901 unset($fields[$name]);
1902 }
1903 }
1904
1905 // replace uniqueNames by the normal names as the key
1906 if (empty($unique)) {
1907 foreach ($fields as $name => &$field) {
1908 //getting rid of unused attributes
1909 foreach ($unsetIfEmpty as $attr) {
1910 if (empty($field[$attr])) {
1911 unset($field[$attr]);
1912 }
1913 }
1914 if ($name == $field['name']) {
1915 continue;
1916 }
1917 if (array_key_exists($field['name'], $fields)) {
1918 $field['error'] = 'name conflict';
1919 // it should never happen, but better safe than sorry
1920 continue;
1921 }
1922 $fields[$field['name']] = $field;
1923 $fields[$field['name']]['uniqueName'] = $name;
1924 unset($fields[$name]);
1925 }
1926 }
1927 // Translate FKClassName to the corresponding api
1928 foreach ($fields as $name => &$field) {
1929 if (!empty($field['FKClassName'])) {
1930 $FKApi = CRM_Core_DAO_AllCoreTables::getBriefName($field['FKClassName']);
1931 if ($FKApi) {
1932 $field['FKApiName'] = $FKApi;
1933 }
1934 }
1935 }
1936 $fields += _civicrm_api_get_custom_fields($entity, $params);
1937 return $fields;
1938 }
1939
1940 /**
1941 * Return an array of fields for a given entity.
1942 *
1943 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1944 *
1945 * @param $entity
1946 * @param array $params
1947 *
1948 * @return array
1949 */
1950 function _civicrm_api_get_custom_fields($entity, &$params) {
1951 $entity = _civicrm_api_get_camel_name($entity);
1952 if ($entity == 'Contact') {
1953 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1954 $entity = $params['contact_type'] ?? NULL;
1955 }
1956 $customfields = CRM_Core_BAO_CustomField::getFields($entity,
1957 FALSE,
1958 FALSE,
1959 // we could / should probably test for other subtypes here - e.g. activity_type_id
1960 CRM_Utils_Array::value('contact_sub_type', $params),
1961 NULL,
1962 FALSE,
1963 FALSE,
1964 FALSE
1965 );
1966
1967 $ret = [];
1968
1969 foreach ($customfields as $key => $value) {
1970 // Regular fields have a 'name' property
1971 $value['name'] = 'custom_' . $key;
1972 $value['title'] = $value['label'];
1973 if ($value['data_type'] == 'Date' && CRM_Utils_Array::value('time_format', $value, 0) > 0) {
1974 $value['data_type'] = 'DateTime';
1975 }
1976 $value['type'] = CRM_Utils_Array::value($value['data_type'], CRM_Core_BAO_CustomField::dataToType());
1977 $ret['custom_' . $key] = $value;
1978 }
1979 return $ret;
1980 }
1981
1982 /**
1983 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
1984 *
1985 * If multiple aliases the last takes precedence
1986 *
1987 * Function also swaps unique fields for non-unique fields & vice versa.
1988 *
1989 * @param $apiRequest
1990 * @param $fields
1991 */
1992 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1993 foreach ($fields as $field => $values) {
1994 $uniqueName = $values['uniqueName'] ?? NULL;
1995 if (!empty($values['api.aliases'])) {
1996 // if aliased field is not set we try to use field alias
1997 if (!isset($apiRequest['params'][$field])) {
1998 foreach ($values['api.aliases'] as $alias) {
1999 if (isset($apiRequest['params'][$alias])) {
2000 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
2001 }
2002 //unset original field nb - need to be careful with this as it may bring inconsistencies
2003 // out of the woodwork but will be implementing only as _spec function extended
2004 unset($apiRequest['params'][$alias]);
2005 }
2006 }
2007 }
2008 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
2009 && isset($apiRequest['params'][$values['name']])
2010 ) {
2011 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
2012 // note that it would make sense to unset the original field here but tests need to be in place first
2013 if ($field != 'domain_version') {
2014 unset($apiRequest['params'][$values['name']]);
2015 }
2016 }
2017 if (!isset($apiRequest['params'][$field])
2018 && $uniqueName
2019 && $field != $uniqueName
2020 && array_key_exists($uniqueName, $apiRequest['params'])
2021 ) {
2022 $apiRequest['params'][$field] = $apiRequest['params'][$values['uniqueName']] ?? NULL;
2023 // note that it would make sense to unset the original field here but tests need to be in place first
2024 }
2025 }
2026
2027 }
2028
2029 /**
2030 * Validate integer fields being passed into API.
2031 *
2032 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
2033 *
2034 * @param array $params
2035 * Params from civicrm_api.
2036 * @param string $fieldName
2037 * Uniquename of field being checked.
2038 * @param array $fieldInfo
2039 * Array of fields from getfields function.
2040 * @param string $entity
2041 *
2042 * @throws API_Exception
2043 */
2044 function _civicrm_api3_validate_integer(&$params, $fieldName, &$fieldInfo, $entity) {
2045 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2046 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
2047 return;
2048 }
2049
2050 if (!empty($fieldValue) || $fieldValue === '0' || $fieldValue === 0) {
2051 // if value = 'user_contact_id' (or similar), replace value with contact id
2052 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
2053 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
2054 if ('unknown-user' === $realContactId) {
2055 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, ['error_field' => $fieldName, "type" => "integer"]);
2056 }
2057 elseif (is_numeric($realContactId)) {
2058 $fieldValue = $realContactId;
2059 }
2060 elseif (is_null($realContactId) && empty($fieldInfo['api.required']) && $fieldValue === 'user_contact_id') {
2061 // If not mandatory this will be OK. If mandatory it should fail.
2062 $fieldValue = NULL;
2063 }
2064 }
2065 if (!empty($fieldInfo['pseudoconstant']) || !empty($fieldInfo['options'])) {
2066 $additional_lookup_params = [];
2067 if (strtolower($entity) == 'address' && $fieldName == 'state_province_id') {
2068 $country_id = _civicrm_api3_resolve_country_id($params);
2069 if (!empty($country_id)) {
2070 $additional_lookup_params = ['country_id' => $country_id];
2071 }
2072 }
2073 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op, $additional_lookup_params);
2074 }
2075
2076 // After swapping options, ensure we have an integer(s)
2077 foreach ((array) ($fieldValue) as $value) {
2078 if ($value && !is_numeric($value) && $value !== 'null' && $value !== NULL && !is_array($value)) {
2079 throw new API_Exception("$fieldName is not a valid integer", 2001, ['error_field' => $fieldName, "type" => "integer"]);
2080 }
2081 }
2082
2083 // Check our field length
2084 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
2085 ) {
2086 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
2087 2100, ['field' => $fieldName, "max_length" => $fieldInfo['maxlength']]
2088 );
2089 }
2090 }
2091
2092 if (!empty($op)) {
2093 $params[$fieldName][$op] = $fieldValue;
2094 }
2095 else {
2096 $params[$fieldName] = $fieldValue;
2097 }
2098 }
2099
2100 /**
2101 * Helper function to determine country_id given the myriad of values for country_id or country that are supported
2102 * @param $params
2103 *
2104 * @return int|null
2105 */
2106 function _civicrm_api3_resolve_country_id($params) {
2107 if (!empty($params['country_id'])) {
2108 if (is_numeric($params['country_id'])) {
2109 $country_id = $params['country_id'];
2110 }
2111 else {
2112 $country = new CRM_Core_DAO_Country();
2113 $country->name = $params['country_id'];
2114 if (!$country->find(TRUE)) {
2115 $country->name = NULL;
2116 $country->iso_code = $params['country_id'];
2117 $country->find(TRUE);
2118 }
2119 if (!empty($country->id)) {
2120 $country_id = $country->id;
2121 }
2122 }
2123 }
2124 elseif (!empty($params['country'])) {
2125 if (is_numeric($params['country'])) {
2126 $country_id = $params['country'];
2127 }
2128 else {
2129 $country = new CRM_Core_DAO_Country();
2130 $country->name = $params['country'];
2131 if (!$country->find(TRUE)) {
2132 $country->name = NULL;
2133 $country->iso_code = $params['country'];
2134 $country->find(TRUE);
2135 }
2136 if (!empty($country->id)) {
2137 $country_id = $country->id;
2138 }
2139 }
2140 }
2141 return !empty($country_id) ? $country_id : NULL;
2142 }
2143
2144 /**
2145 * Determine a contact ID using a string expression.
2146 *
2147 * @param string $contactIdExpr
2148 * E.g. "user_contact_id" or "@user:username".
2149 *
2150 * @return int|null|'unknown-user'
2151 * @throws \CRM_Core_Exception
2152 */
2153 function _civicrm_api3_resolve_contactID($contactIdExpr) {
2154 // If value = 'user_contact_id' replace value with logged in user id.
2155 if ($contactIdExpr == "user_contact_id") {
2156 return CRM_Core_Session::getLoggedInContactID();
2157 }
2158 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
2159 $config = CRM_Core_Config::singleton();
2160
2161 $ufID = $config->userSystem->getUfId($matches[1]);
2162 if (!$ufID) {
2163 return 'unknown-user';
2164 }
2165
2166 $contactID = CRM_Core_BAO_UFMatch::getContactId($ufID);
2167 if (!$contactID) {
2168 return 'unknown-user';
2169 }
2170
2171 return $contactID;
2172 }
2173 return NULL;
2174 }
2175
2176 /**
2177 * Validate html (check for scripting attack).
2178 *
2179 * @param array $params
2180 * @param string $fieldName
2181 * @param array $fieldInfo
2182 *
2183 * @throws API_Exception
2184 */
2185 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
2186 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2187 if (strpos($op, 'NULL') || strpos($op, 'EMPTY')) {
2188 return;
2189 }
2190 }
2191
2192 /**
2193 * Validate string fields being passed into API.
2194 *
2195 * @param array $params
2196 * Params from civicrm_api.
2197 * @param string $fieldName
2198 * Uniquename of field being checked.
2199 * @param array $fieldInfo
2200 * Array of fields from getfields function.
2201 * @param string $entity
2202 *
2203 * @throws API_Exception
2204 * @throws Exception
2205 */
2206 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2207 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName, 'String');
2208 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System::isNull($fieldValue)) {
2209 return;
2210 }
2211
2212 if (!is_array($fieldValue)) {
2213 $fieldValue = (string) $fieldValue;
2214 }
2215
2216 if ($fieldValue) {
2217 foreach ((array) $fieldValue as $key => $value) {
2218 if ($fieldName == 'currency') {
2219 //When using IN operator $fieldValue is a array of currency codes
2220 if (!CRM_Utils_Rule::currencyCode($value)) {
2221 throw new Exception("Currency not a valid code: $currency");
2222 }
2223 }
2224 }
2225 }
2226 if (!empty($fieldInfo['pseudoconstant']) || !empty($fieldInfo['options'])) {
2227 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op);
2228 }
2229 // Check our field length
2230 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2231 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2232 2100, ['field' => $fieldName]
2233 );
2234 }
2235
2236 if (!empty($op)) {
2237 $params[$fieldName][$op] = $fieldValue;
2238 }
2239 else {
2240 $params[$fieldName] = $fieldValue;
2241 }
2242 }
2243
2244 /**
2245 * Validate & swap out any pseudoconstants / options.
2246 *
2247 * @param mixed $fieldValue
2248 * @param string $entity : api entity name
2249 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2250 * @param array $fieldInfo : getfields meta-data
2251 * @param string $op
2252 * @param array $additional_lookup_params
2253 *
2254 * @throws \API_Exception
2255 */
2256 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo, $op = '=', $additional_lookup_params = []) {
2257 if (in_array($op, ['>', '<', '>=', '<=', 'LIKE', 'NOT LIKE'])) {
2258 return;
2259 }
2260
2261 $options = $fieldInfo['options'] ?? NULL;
2262
2263 if (!$options) {
2264 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2265 // We need to get the options from the entity the field relates to.
2266 $entity = $fieldInfo['entity'];
2267 }
2268 $options_lookup_params = [
2269 'version' => 3,
2270 'field' => $fieldInfo['name'],
2271 'context' => 'validate',
2272 ];
2273 if (!empty($additional_lookup_params)) {
2274 $options_lookup_params = array_merge($additional_lookup_params, $options_lookup_params);
2275 }
2276 $options = civicrm_api($entity, 'getoptions', $options_lookup_params);
2277
2278 $options = CRM_Utils_Array::value('values', $options, []);
2279 }
2280
2281 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2282 $implode = FALSE;
2283 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO::VALUE_SEPARATOR) !== FALSE) {
2284 $fieldValue = CRM_Utils_Array::explodePadded($fieldValue);
2285 $implode = TRUE;
2286 }
2287 // If passed multiple options, validate each.
2288 if (is_array($fieldValue)) {
2289 foreach ($fieldValue as &$value) {
2290 if (!is_array($value)) {
2291 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName, CRM_Utils_Array::value('api.required', $fieldInfo));
2292 }
2293 }
2294 // TODO: unwrap the call to implodePadded from the conditional and do it always
2295 // need to verify that this is safe and doesn't break anything though.
2296 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2297 if ($implode) {
2298 CRM_Utils_Array::implodePadded($fieldValue);
2299 }
2300 }
2301 else {
2302 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName, CRM_Utils_Array::value('api.required', $fieldInfo));
2303 }
2304 }
2305
2306 /**
2307 * Validate & swap a single option value for a field.
2308 *
2309 * @param string $value field value
2310 * @param array $options array of options for this field
2311 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2312 * @param bool $isRequired
2313 * Is this a required field or is 'null' an acceptable option. We allow 'null' last
2314 * in case we have the weird situation of it being a valid option in which case our
2315 * brains will probably explode.
2316 *
2317 * @throws API_Exception
2318 */
2319 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName, $isRequired) {
2320 // If option is a key, no need to translate
2321 // or if no options are avaiable for pseudoconstant 'table' property
2322 if (array_key_exists($value, $options) || !$options) {
2323 return;
2324 }
2325
2326 // Hack for Profile formatting fields
2327 if ($fieldName === 'field_name' && (strpos($value, 'formatting') === 0)) {
2328 return;
2329 }
2330
2331 // Translate value into key
2332 // Cast $value to string to avoid a bug in array_search
2333 $newValue = array_search((string) $value, $options);
2334 if ($newValue !== FALSE) {
2335 $value = $newValue;
2336 return;
2337 }
2338 // Case-insensitive matching
2339 $newValue = strtolower($value);
2340 $options = array_map("strtolower", $options);
2341 $newValue = array_search($newValue, $options);
2342 if ($newValue === FALSE) {
2343 if ($value === 'null' && !$isRequired) {
2344 // CiviMagic syntax for Nulling out the field - let it through.
2345 return;
2346 }
2347 // Legacy support for custom fields: If matching failed by name, fallback to label
2348 // @see https://lab.civicrm.org/dev/core/-/issues/1816
2349 if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($fieldName)) {
2350 $field = new CRM_Core_BAO_CustomField();
2351 $field->id = $customFieldId;
2352 $options = array_map("strtolower", $field->getOptions());
2353 $newValue = array_search(strtolower($value), $options);
2354 }
2355 }
2356 if ($newValue === FALSE) {
2357 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, ['error_field' => $fieldName]);
2358 }
2359 $value = $newValue;
2360 }
2361
2362 /**
2363 * Returns the canonical name of a field.
2364 *
2365 * @param $entity
2366 * api entity name (string should already be standardized - no camelCase).
2367 * @param $fieldName
2368 * any variation of a field's name (name, unique_name, api.alias).
2369 *
2370 * @param string $action
2371 *
2372 * @return bool|string
2373 * FieldName or FALSE if the field does not exist
2374 */
2375 function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') {
2376 if (!$fieldName) {
2377 return FALSE;
2378 }
2379 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2380 return $fieldName;
2381 }
2382 if ($fieldName === (CRM_Core_DAO_AllCoreTables::convertEntityNameToLower($entity) . '_id')) {
2383 return 'id';
2384 }
2385 $result = civicrm_api($entity, 'getfields', [
2386 'version' => 3,
2387 'action' => $action,
2388 ]);
2389 $meta = $result['values'];
2390 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2391 $fieldName = $fieldName . '_id';
2392 }
2393 if (isset($meta[$fieldName])) {
2394 return $meta[$fieldName]['name'];
2395 }
2396 foreach ($meta as $info) {
2397 if ($fieldName == $info['name'] || $fieldName == CRM_Utils_Array::value('uniqueName', $info)) {
2398 return $info['name'];
2399 }
2400 if (array_search($fieldName, CRM_Utils_Array::value('api.aliases', $info, [])) !== FALSE) {
2401 return $info['name'];
2402 }
2403 }
2404 // Create didn't work, try with get
2405 if ($action == 'create') {
2406 return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get');
2407 }
2408 return FALSE;
2409 }
2410
2411 /**
2412 * Check if the function is deprecated.
2413 *
2414 * @param string $entity
2415 * @param array $result
2416 *
2417 * @return string|array|null
2418 */
2419 function _civicrm_api3_deprecation_check($entity, $result = []) {
2420 if ($entity) {
2421 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
2422 $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation";
2423 if (function_exists($fnName)) {
2424 return $fnName($result);
2425 }
2426 }
2427 }
2428
2429 /**
2430 * Get the actual field value.
2431 *
2432 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2433 * So this function returns the actual field value.
2434 *
2435 * @param array $params
2436 * @param string $fieldName
2437 * @param string $type
2438 *
2439 * @return mixed
2440 */
2441 function _civicrm_api3_field_value_check(&$params, $fieldName, $type = NULL) {
2442 $fieldValue = $params[$fieldName] ?? NULL;
2443 $op = NULL;
2444
2445 if (!empty($fieldValue) && is_array($fieldValue) &&
2446 (array_search(key($fieldValue), CRM_Core_DAO::acceptedSQLOperators()) ||
2447 $type == 'String' && strstr(key($fieldValue), 'EMPTY'))
2448 ) {
2449 $op = key($fieldValue);
2450 $fieldValue = $fieldValue[$op] ?? NULL;
2451 }
2452 return [$fieldValue, $op];
2453 }
2454
2455 /**
2456 * A generic "get" API based on simple array data. This is comparable to
2457 * _civicrm_api3_basic_get but does not use DAO/BAO. This is useful for
2458 * small/mid-size data loaded from external JSON or XML documents.
2459 *
2460 * @param $entity
2461 * @param array $params
2462 * API parameters.
2463 * @param array $records
2464 * List of all records.
2465 * @param string $idCol
2466 * The property which defines the ID of a record
2467 * @param array $filterableFields
2468 * List of filterable fields.
2469 *
2470 * @return array
2471 * @throws \API_Exception
2472 */
2473 function _civicrm_api3_basic_array_get($entity, $params, $records, $idCol, $filterableFields) {
2474 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
2475 // TODO // $sort = CRM_Utils_Array::value('sort', $options, NULL);
2476 $offset = $options['offset'] ?? NULL;
2477 $limit = $options['limit'] ?? NULL;
2478
2479 $matches = [];
2480
2481 $currentOffset = 0;
2482 foreach ($records as $record) {
2483 if ($idCol != 'id') {
2484 $record['id'] = $record[$idCol];
2485 }
2486 $match = TRUE;
2487 foreach ($params as $k => $v) {
2488 if ($k == 'id') {
2489 $k = $idCol;
2490 }
2491 if (in_array($k, $filterableFields) && $record[$k] != $v) {
2492 $match = FALSE;
2493 break;
2494 }
2495 }
2496 if ($match) {
2497 if ($currentOffset >= $offset) {
2498 $matches[$record[$idCol]] = $record;
2499 }
2500 if ($limit && count($matches) >= $limit) {
2501 break;
2502 }
2503 $currentOffset++;
2504 }
2505 }
2506
2507 $return = CRM_Utils_Array::value('return', $options, []);
2508 if (!empty($return)) {
2509 $return['id'] = 1;
2510 $matches = CRM_Utils_Array::filterColumns($matches, array_keys($return));
2511 }
2512
2513 return civicrm_api3_create_success($matches, $params);
2514 }
2515
2516 /**
2517 * @param string $bao_name
2518 * @param array $params
2519 * @throws \Civi\API\Exception\UnauthorizedException
2520 */
2521 function _civicrm_api3_check_edit_permissions($bao_name, $params) {
2522 // For lack of something more clever, here's a whitelist of entities whos permissions
2523 // are inherited from a contact record.
2524 // Note, when adding here, also remember to modify _civicrm_api3_permissions()
2525 $contactEntities = [
2526 'CRM_Core_BAO_Email',
2527 'CRM_Core_BAO_Phone',
2528 'CRM_Core_BAO_Address',
2529 'CRM_Core_BAO_IM',
2530 'CRM_Core_BAO_Website',
2531 'CRM_Core_BAO_OpenID',
2532 ];
2533 if (!empty($params['check_permissions']) && in_array($bao_name, $contactEntities)) {
2534 $cid = !empty($params['contact_id']) ? $params['contact_id'] : CRM_Core_DAO::getFieldValue($bao_name, $params['id'], 'contact_id');
2535 if (!CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT)) {
2536 throw new \Civi\API\Exception\UnauthorizedException('Permission denied to modify contact record');
2537 }
2538 }
2539 }
2540
2541 /**
2542 * Check if an entity has been modified since the last known modified_date
2543 *
2544 * @param string $modifiedDate Last knowm modified_date
2545 * @param int $id Id of record to check
2546 * @param string $entity API Entity
2547 *
2548 * @return bool
2549 * @throws \CiviCRM_API3_Exception
2550 */
2551 function _civicrm_api3_compare_timestamps($modifiedDate, $id, $entity) {
2552 $currentDbInfo = civicrm_api3($entity, 'getsingle', ['id' => $id]);
2553 if (strtotime($currentDbInfo['modified_date']) <= strtotime($modifiedDate)) {
2554 return TRUE;
2555 }
2556 return FALSE;
2557 }