3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
13 * CiviCRM APIv3 utility functions.
15 * @package CiviCRM_APIv3
19 * Initialize CiviCRM - should be run at the start of each API function.
21 function _civicrm_api3_initialize() {
22 require_once 'CRM/Core/ClassLoader.php';
23 CRM_Core_ClassLoader
::singleton()->register();
24 CRM_Core_Config
::singleton();
28 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking.
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.
37 * @throws \API_Exception
39 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = []) {
41 foreach ($keyoptions as $key) {
44 civicrm_api3_verify_mandatory($params, $daoName, $keys);
48 * Check mandatory fields are included.
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).
55 * List of required fields. A value can be an array denoting that either this or that is required.
56 * @param bool $verifyDAO
58 * @throws \API_Exception
60 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = [], $verifyDAO = TRUE) {
63 if (!empty($params['id'])) {
67 if (!in_array('version', $keys)) {
68 // required from v3 onwards
72 foreach ($keys as $key) {
76 foreach ($key as $subkey) {
77 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
78 $optionset[] = $subkey;
81 // As long as there is one match we don't need to return anything.
85 if (empty($match) && !empty($optionset)) {
86 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
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')) {
97 if (!empty($unmatched)) {
98 throw new API_Exception('Mandatory key(s) missing from params array: ' . implode(", ", $unmatched), 'mandatory_missing', ["fields" => $unmatched]);
103 * Create error array.
110 function civicrm_api3_create_error($msg, $data = []) {
111 $data['is_error'] = 1;
112 $data['error_message'] = $msg;
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'];
129 * Format array in result output style.
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.
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
145 * @throws \CiviCRM_API3_Exception
147 function civicrm_api3_create_success($values = 1, $params = [], $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = []) {
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'];
159 if (!empty($item['financial_type_id'])) {
160 // 4.3 legacy handling.
161 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
163 if (!empty($item['contribution_cancel_date'])) {
164 // 5.16 legacy handling.
165 $values[$key]['cancel_date'] = $item['contribution_cancel_date'];
167 if (!empty($item['next_sched_contribution_date'])) {
168 // 4.4 legacy handling
169 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
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);
178 elseif ($action !== 'getfields') {
179 $apiFields = civicrm_api($entity, 'getfields', ['version' => 3] +
$params);
186 if ($action !== 'getfields' && isset($apiFields['values']) && is_array($apiFields['values'])) {
187 $allFields = array_keys($apiFields['values']);
189 $paramFields = array_keys($params);
190 $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), [
209 $result['undefined_fields'] = array_merge($undefined);
213 $result['version'] = 3;
214 if (is_array($values)) {
215 $result['count'] = (int) count($values);
217 // Convert value-separated strings to array
218 if ($action !== 'getfields') {
219 _civicrm_api3_separate_values($values);
222 if ($result['count'] == 1) {
223 list($result['id']) = array_keys($values);
225 elseif (!empty($values['id']) && is_int($values['id'])) {
226 $result['id'] = $values['id'];
230 $result['count'] = !empty($values) ?
1 : 0;
233 if (is_array($values) && isset($params['sequential']) &&
234 $params['sequential'] == 1
236 $result['values'] = array_values($values);
239 $result['values'] = $values;
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',
247 $result['metadata']['fields'] = $fields['values'];
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.'];
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.'];
261 // Metadata-level deprecations or wholesale entity deprecations.
262 if ($entity === 'Entity' ||
$action === 'getactions' ||
is_string($deprecated)) {
263 $result['deprecated'] = $deprecated;
265 // Action-specific deprecations
266 elseif (!empty($deprecated[$action])) {
267 $result['deprecated'] = $deprecated[$action];
270 return array_merge($result, $extraReturnValues);
274 * Load the DAO of the entity.
280 function _civicrm_api3_load_DAO($entity) {
281 $dao = _civicrm_api3_get_DAO($entity);
290 * Return the DAO of the function or Entity.
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"
297 * @return CRM_Core_DAO|string
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);
306 $name = _civicrm_api_get_camel_name($name);
308 if ($name === 'Individual' ||
$name === 'Household' ||
$name === 'Organization') {
312 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
314 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
315 if ($name === 'MailingEventQueue') {
316 return 'CRM_Mailing_Event_DAO_Queue';
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';
323 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
324 if ($name === 'AclRole') {
325 return 'CRM_ACL_DAO_EntityRole';
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';
333 // FIXME: DAO names should follow CamelCase convention
334 if ($name === 'Im' ||
$name === 'Acl' ||
$name === 'Pcp') {
335 $name = strtoupper($name);
338 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
339 if ($dao ||
!$name) {
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";
348 $daoFn = '_civicrm_api3_' . _civicrm_api_get_entity_name_from_camel($name) . '_DAO';
349 if (function_exists($daoFn)) {
357 * Return the BAO name of the function or Entity.
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"
364 * @return string|null
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';
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';
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';
381 if ($name === 'Payment') {
382 $name = 'FinancialTrxn';
384 $dao = _civicrm_api3_get_DAO($name);
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;
395 * Recursive function to explode value-separated strings into arrays.
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);
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), ',');
410 elseif (strpos($value, $sp) !== FALSE) {
411 $value = explode($sp, trim($value, $sp));
418 * This is a legacy wrapper for api_store_values.
420 * It checks suitable fields using getfields rather than DAO->fields.
422 * Getfields has handling for how to deal with unique names which dao->fields doesn't
424 * Note this is used by BAO type create functions - eg. contribution
426 * @param string $entity
427 * @param array $params
428 * @param array $values
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);
439 * @param array $fields
440 * @param array $params
441 * @param array $values
445 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
448 $keys = array_intersect_key($params, $fields);
449 foreach ($keys as $name => $value) {
450 if ($name !== 'id') {
451 $values[$name] = $value;
459 * Returns field names of the given entity fields.
462 * @param array $fields
463 * Fields array to retrieve the field names for.
466 function _civicrm_api3_field_names($fields) {
467 CRM_Core_Error
::deprecatedFunctionWarning('array_column');
469 foreach ($fields as $key => $value) {
470 if (!empty($value['name'])) {
471 $result[] = $value['name'];
478 * Get function for query object api.
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
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.
487 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
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.
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!).
504 * @throws API_Exception
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'];
512 unset($params['id']);
514 $options = _civicrm_api3_get_options_from_params($params, TRUE);
516 $inputParams = array_merge(
517 CRM_Utils_Array
::value('input_params', $options, []),
518 CRM_Utils_Array
::value('input_params', $additional_options, [])
520 $returnProperties = array_merge(
521 CRM_Utils_Array
::value('return', $options, []),
522 CRM_Utils_Array
::value('return', $additional_options, [])
524 if (empty($returnProperties)) {
525 $returnProperties = $defaultReturnProperties;
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)) {
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']);
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;
552 $returnProperties = NULL;
555 if (substr($sort, 0, 2) == 'id') {
556 $sort = $lowercase_entity . "_" . $sort;
559 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
561 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
563 list($entities) = CRM_Contact_BAO_Query
::apiQuery(
582 * Get dao query object based on input params.
584 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
587 * @param array $params
588 * @param string $mode
589 * @param string $entity
592 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
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);
605 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
606 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
608 empty($params['check_permissions']),
609 TRUE, TRUE, NULL, 'AND', 'NULL', TRUE
611 list($select, $from, $where, $having) = $query->query();
613 $sql = "$select $from $where $having";
616 $sort = CRM_Utils_Type
::escape($sort, 'MysqlOrderBy');
617 $sql .= " ORDER BY $sort ";
619 if (!empty($rowCount)) {
620 $sql .= " LIMIT $offset, $rowCount ";
622 $dao = CRM_Core_DAO
::executeQuery($sql);
623 return [$dao, $query];
627 * Function transfers the filters being passed into the DAO onto the params object.
629 * @deprecated DAO based retrieval is being phased out.
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())'));
638 * @throws API_Exception
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"];
648 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
649 $fields = array_intersect(array_keys($allfields), array_keys($params));
651 $options = _civicrm_api3_get_options_from_params($params);
652 //apply options like sort
653 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
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);
664 foreach ($params as $paramkey => $paramvalue) {
665 if (strstr($paramkey, 'filter')) {
666 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
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);
686 $daoFieldName = $allfields[$field]['name'];
687 if (empty($daoFieldName)) {
688 throw new API_Exception("Failed to determine field name for \"$field\"");
690 $dao->{$daoFieldName} = $params[$field];
693 $dao->$field = $params[$field];
697 if (!empty($extraSql['where'])) {
698 foreach ($extraSql['where'] as $table => $sqlWhere) {
699 foreach ($sqlWhere as $where) {
700 $dao->whereAdd($where);
704 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
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);
714 // Not already matched on the field names.
715 $unmatchedFields = array_diff(
716 array_keys($options['return']),
720 $returnUniqueMatched = array_intersect(
722 // But a match for the field keys.
723 array_flip($allfields)
725 foreach ($returnUniqueMatched as $uniqueVal) {
726 $dao->selectAdd($allfields[$uniqueVal]);
729 $dao->setApiFilter($params);
733 * Apply filters (e.g. high, low) to DAO object (prior to find).
735 * @param string $filterField
736 * Field name of filter.
737 * @param string $filterValue
738 * Field value of filter.
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 )");
747 if (strstr($filterField, 'low')) {
748 $fieldName = substr($filterField, 0, -4);
749 $dao->whereAdd("($fieldName >= $filterValue )");
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');
762 * Get sort, limit etc options from the params - supporting old & new formats.
764 * Get returnProperties for legacy
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
772 * @param string $entity
773 * @param string $action
775 * @throws API_Exception
777 * options extracted from params
779 function _civicrm_api3_get_options_from_params($params, $queryObject = FALSE, $entity = '', $action = '') {
780 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
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;
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);
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;
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);
806 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
807 $returnProperties = array_fill_keys($returnProperties, 1);
810 if ($entity && $action == 'get') {
811 if (!empty($returnProperties['id'])) {
812 $returnProperties[$lowercase_entity . '_id'] = 1;
813 unset($returnProperties['id']);
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 : [],
825 $options['sort'] = NULL;
827 if (!is_array($sort)) {
828 $sort = array_map('trim', explode(',', $sort));
830 foreach ($sort as $s) {
831 if ($s === '(1)' || CRM_Utils_Rule
::mysqlOrderBy($s)) {
832 if ($entity && $action === 'get') {
833 switch (trim(strtolower($s))) {
837 $s = str_replace('id', $lowercase_entity . '_id', $s);
843 throw new API_Exception("Unknown field specified for sort. Cannot order by '$s'");
846 $options['sort'] = implode(', ', $finalSort);
849 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
850 throw new API_Exception('invalid string in sort options');
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
859 $legacyreturnProperties = [];
861 'sort', 'offset', 'rowCount', 'options', 'return',
862 'version', 'prettyprint', 'check_permissions', 'sequential',
864 foreach ($params as $n => $v) {
865 if (substr($n, 0, 7) === 'return.') {
866 $legacyreturnProperties[substr($n, 7)] = $v;
868 elseif ($n === 'id') {
869 $inputParams[$lowercase_entity . '_id'] = $v;
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');
878 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
879 $options['input_params'] = $inputParams;
884 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
886 * @param array $params
887 * Params array as passed into civicrm_api.
892 * @throws \API_Exception
893 * @throws \CRM_Core_Exception
895 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
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']);
902 if (!empty($options['sort'])) {
903 $options['sort'] = CRM_Utils_Type
::escape($options['sort'], 'MysqlOrderBy');
904 $dao->orderBy($options['sort']);
910 * Build fields array.
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
915 * @param CRM_Core_DAO $bao
916 * @param bool $unique
920 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
921 $fields = $bao->fields();
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']);
933 foreach ($fields as $field) {
934 $dbFields[$field['name']] = $field;
940 * Build fields array.
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
945 * @param CRM_Core_DAO $bao
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);
954 return $uniqueFields;
958 * Converts an DAO object to an array.
960 * @param CRM_Core_DAO $dao
962 * @param array $params
963 * @param bool $uniqueFields
964 * @param string $entity
965 * @param bool $autoFind
969 * @throws \API_Exception
971 * @deprecated - DAO based retrieval is being phased out.
974 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
976 if (isset($params['options']) && !empty($params['options']['is_count'])) {
977 return $dao->count();
982 if ($autoFind && !$dao->find()) {
986 if (isset($dao->count
)) {
990 $fields = array_keys(_civicrm_api3_build_fields_array($dao, FALSE));
991 while ($dao->fetch()) {
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;
1001 $result[$dao->id
] = $tmp;
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
);
1012 * Determine if custom fields need to be retrieved.
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
1017 * @param string $entity
1018 * Entity name in CamelCase.
1019 * @param array $params
1022 * @throws \API_Exception
1024 * @todo filter so only required fields are queried
1026 function _civicrm_api3_custom_fields_are_required($entity, $params) {
1027 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
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')) {
1039 * Converts an object to an array.
1041 * @param object $dao
1042 * (reference) object to convert.
1043 * @param array $values
1044 * (reference) array.
1045 * @param array|bool $uniqueFields
1047 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
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;
1058 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1065 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1066 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1070 * Format custom parameters.
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.
1079 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1080 $values['custom'] = [];
1081 $checkCheckBoxField = FALSE;
1083 if (in_array($extends, ['Household', 'Individual', 'Organization'])) {
1084 $entity = 'Contact';
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;
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);
1101 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1102 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1109 * Format parameters for create action.
1111 * @param array $params
1114 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1115 $nonGenericEntities = ['Contact', 'Individual', 'Household', 'Organization'];
1117 $customFieldEntities = array_diff_key(CRM_Core_SelectValues
::customGroupExtends(), array_fill_keys($nonGenericEntities, 1));
1118 if (!array_key_exists($entity, $customFieldEntities)) {
1122 _civicrm_api3_custom_format_params($params, $values, $entity);
1123 $params = array_merge($params, $values);
1127 * We can't rely on downstream to add separators to checkboxes so we'll check here.
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
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
1136 * The resulting array should look like
1142 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
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
1147 * @param mixed $checkboxFieldValue
1148 * @param string $customFieldLabel
1149 * @param string $entity
1151 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1153 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1154 // We can assume it's pre-formatted.
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.
1163 $options = $options['values'];
1165 if (is_array($checkboxFieldValue)) {
1166 foreach ($checkboxFieldValue as $key => $value) {
1167 if (!array_key_exists($key, $options)) {
1168 $validValue = FALSE;
1172 // we have been passed an array that is already in the 'odd' custom field format
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);
1182 if (is_string($checkboxFieldValue)) {
1183 $possibleValue = $checkboxFieldValue;
1185 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1186 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1189 elseif (is_array($checkboxFieldValue)) {
1190 // so this time around we are considering the values in the array
1191 $possibleValues = $checkboxFieldValue;
1192 $formatValue = TRUE;
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);
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 ','
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)
1210 elseif (array_key_exists(trim($possibleValue), $options)) {
1211 $possibleValues[$index] = trim($possibleValue);
1214 $formatValue = FALSE;
1218 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1223 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1225 * @param string|CRM_Core_DAO $bao_name
1227 * @param array $params
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)
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);
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']);
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'];
1256 $query->select
= array_keys(array_filter($options['return']));
1257 $query->orderBy
= $options['sort'];
1258 $query->isFillUniqueFields
= $uniqueFields;
1260 $query->limit
= $options['limit'];
1261 $query->offset
= $options['offset'];
1262 $query->merge($sql);
1263 $result = $query->run();
1266 if ($returnAsSuccess) {
1267 return civicrm_api3_create_success($result, $params, $entity, 'get');
1273 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
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.
1282 * @throws API_Exception
1283 * @throws \Civi\API\Exception\UnauthorizedException
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);
1291 $ids = [$entity => CRM_Utils_Array
::value('id', $params)];
1295 if (method_exists($bao_name, 'create')) {
1297 $fct_name = $bao_name . '::' . $fct;
1298 $bao = call_user_func_array([$bao_name, $fct], $args);
1300 elseif (method_exists($bao_name, 'add')) {
1302 $fct_name = $bao_name . '::' . $fct;
1303 $bao = call_user_func_array([$bao_name, $fct], $args);
1306 $fct_name = '_civicrm_api3_basic_create_fallback';
1307 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1310 if (is_null($bao)) {
1311 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
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);
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
);
1330 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1331 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1336 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1338 * @param string|CRM_Core_DAO $bao_name
1339 * @param array $params
1341 * @throws API_Exception
1343 * @return CRM_Core_DAO|NULL
1344 * An instance of the BAO
1346 function _civicrm_api3_basic_create_fallback($bao_name, $params) {
1347 return $bao_name::writeRecord($params);
1351 * Function to do a 'standard' api del.
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.
1355 * @param string|CRM_Core_DAO $bao_name
1356 * @param array $params
1361 * @throws API_Exception
1362 * @throws \Civi\API\Exception\UnauthorizedException
1363 * @throws \CiviCRM_API3_Exception
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'];
1373 $bao = call_user_func_array([$bao_name, 'del'], $args);
1374 if ($bao !== FALSE) {
1375 return civicrm_api3_create_success();
1377 throw new API_Exception('Could not delete entity id ' . $params['id']);
1379 throw new API_Exception('Could not delete entity id ' . $params['id']);
1382 $bao_name::deleteRecord($params);
1383 return civicrm_api3_create_success();
1388 * Get custom data for the given entity & Add it to the returnArray.
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)
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.
1407 * @throws \CRM_Core_Exception
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,
1421 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1);
1423 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1425 foreach ($groupTree as $set) {
1426 $fieldInfo +
= $set['fields'];
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;
1434 //not standard - but some api did this so guess we should keep - cheap as chips
1435 $returnArray[$key] = $val;
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');
1447 * Used by the Validate API.
1449 * @param string $entity
1450 * @param string $action
1451 * @param array $params
1453 * @return array $errors
1454 * @throws \CiviCRM_API3_Exception
1456 function _civicrm_api3_validate($entity, $action, $params) {
1458 $fields = civicrm_api3($entity, 'getfields', ['sequential' => 1, 'api_action' => $action]);
1459 $fields = $fields['values'];
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',
1471 // Select only the fields which have been input as a param.
1473 foreach ($fields as $values) {
1474 if (array_key_exists($values['name'], $params)) {
1475 $finalfields[] = $values;
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'];
1485 _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params);
1487 catch (Exception
$e) {
1488 $errors[$fieldName] = [
1489 'message' => $e->getMessage(),
1490 'code' => 'incorrect_value',
1499 * Used by the Validate API.
1501 * @param array $fieldInfo
1502 * @param string $entity
1503 * @param array $params
1505 * @throws API_Exception
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);
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);
1521 case CRM_Utils_Type
::T_TEXT
:
1522 case CRM_Utils_Type
::T_STRING
:
1523 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1526 case CRM_Utils_Type
::T_MONEY
:
1527 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
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]);
1539 * Validate fields being passed into API.
1541 * This function relies on the getFields function working accurately
1542 * for the given API.
1544 * As of writing only date was implemented.
1546 * @param string $entity
1547 * @param string $action
1548 * @param array $params
1550 * @param array $fields
1551 * Response from getfields all variables are the same as per civicrm_api.
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);
1566 $fields = array_intersect_key($fields, $params);
1567 if (!empty($chainApiParams)) {
1568 $fields = array_merge($fields, $chainApiParams);
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);
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]];
1585 $dateParams = &$params;
1587 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
1590 case CRM_Utils_Type
::T_TEXT
:
1591 case CRM_Utils_Type
::T_STRING
:
1592 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
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) {
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]);
1611 * Validate foreign key values of fields being passed into API.
1613 * This function relies on the getFields function working accurately
1614 * for the given API.
1616 * @param string $entity
1617 * @param string $action
1618 * @param array $params
1620 * @param array $fields
1621 * Response from getfields all variables are the same as per civicrm_api.
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);
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.");
1638 if (!empty($fieldInfo['api.unique'])) {
1639 $params['entity'] = $entity;
1640 _civicrm_api3_validate_unique_key($params, $fieldName);
1646 * Validate date fields being passed into API.
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
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
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.
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) {
1671 if ($fieldValue === 'null' && empty($fieldInfo['api.required'])) {
1672 // This is the wierd & wonderful way PEAR sets null.
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']);
1680 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1681 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1685 $params[$fieldName][$op] = $fieldValue;
1688 $params[$fieldName] = $fieldValue;
1693 * Convert date into BAO friendly date.
1695 * We accept 'whatever strtotime accepts'
1697 * @param string $dateValue
1698 * @param string $fieldName
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);
1711 if (strtotime($dateValue) === FALSE) {
1712 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1714 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1715 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1719 * Validate foreign constraint fields being passed into API.
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
1728 * @throws \API_Exception
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];
1739 $dao->selectAdd('id');
1740 if (!$dao->find()) {
1741 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1746 * Validate foreign constraint fields being passed into API.
1748 * @param array $params
1749 * Params from civicrm_api.
1750 * @param string $fieldName
1751 * Uniquename of field being checked.
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) {
1760 $existing = civicrm_api($params['entity'], 'get', [
1761 'version' => $params['version'],
1762 $fieldName => $fieldValue,
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']);
1772 * Generic implementation of the "replace" action.
1774 * Replace the old set of entities (matching some given keys) with a new set of
1775 * entities (matching the same keys).
1777 * @note This will verify that 'values' is present, but it does not directly verify
1778 * any other parameters.
1780 * @param string $entity
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.
1789 function _civicrm_api3_generic_replace($entity, $params) {
1791 $transaction = new CRM_Core_Transaction();
1793 if (!is_array($params['values'])) {
1794 throw new Exception("Mandatory key(s) missing from params array: values");
1797 // Extract the keys -- somewhat scary, don't think too hard about it
1798 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1800 // Lookup pre-existing records
1801 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1802 if (civicrm_error($preexisting)) {
1803 $transaction->rollback();
1804 return $preexisting;
1807 // Save the new/updated records
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();
1818 foreach ($create['values'] as $entity_id => $entity_value) {
1819 $creates[$entity_id] = $entity_value;
1823 // Remove stale records
1824 $staleIDs = array_diff(
1825 array_keys($preexisting['values']),
1826 array_keys($creates)
1828 foreach ($staleIDs as $staleID) {
1829 $delete = civicrm_api($entity, 'delete', [
1830 'version' => $params['version'],
1833 if (civicrm_error($delete)) {
1834 $transaction->rollback();
1839 return civicrm_api3_create_success($creates, $params);
1841 catch (PEAR_Exception
$e) {
1842 $transaction->rollback();
1843 return civicrm_api3_create_error($e->getMessage());
1845 catch (Exception
$e) {
1846 $transaction->rollback();
1847 return civicrm_api3_create_error($e->getMessage());
1852 * Replace base parameters.
1854 * @param array $params
1858 function _civicrm_api3_generic_replace_base_params($params) {
1859 $baseParams = $params;
1860 unset($baseParams['values']);
1861 unset($baseParams['sequential']);
1862 unset($baseParams['options']);
1867 * Returns fields allowable by api.
1870 * String Entity to query.
1871 * @param bool $unique
1872 * Index by unique fields?.
1873 * @param array $params
1877 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = []) {
1885 $dao = _civicrm_api3_get_DAO($entity);
1889 $fields = $dao::fields();
1890 $supportedFields = $dao::getSupportedFields();
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);
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]);
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]);
1914 if ($name == $field['name']) {
1917 if (array_key_exists($field['name'], $fields)) {
1918 $field['error'] = 'name conflict';
1919 // it should never happen, but better safe than sorry
1922 $fields[$field['name']] = $field;
1923 $fields[$field['name']]['uniqueName'] = $name;
1924 unset($fields[$name]);
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']);
1932 $field['FKApiName'] = $FKApi;
1936 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1941 * Return an array of fields for a given entity.
1943 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1946 * @param array $params
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;
1956 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1959 // we could / should probably test for other subtypes here - e.g. activity_type_id
1960 CRM_Utils_Array
::value('contact_sub_type', $params),
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';
1976 $value['type'] = CRM_Utils_Array
::value($value['data_type'], CRM_Core_BAO_CustomField
::dataToType());
1977 $ret['custom_' . $key] = $value;
1983 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
1985 * If multiple aliases the last takes precedence
1987 * Function also swaps unique fields for non-unique fields & vice versa.
1989 * @param $apiRequest
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];
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]);
2008 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
2009 && isset($apiRequest['params'][$values['name']])
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']]);
2017 if (!isset($apiRequest['params'][$field])
2019 && $field != $uniqueName
2020 && array_key_exists($uniqueName, $apiRequest['params'])
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
2030 * Validate integer fields being passed into API.
2032 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
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
2042 * @throws API_Exception
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) {
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"]);
2057 elseif (is_numeric($realContactId)) {
2058 $fieldValue = $realContactId;
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.
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];
2073 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op, $additional_lookup_params);
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"]);
2083 // Check our field length
2084 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
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']]
2093 $params[$fieldName][$op] = $fieldValue;
2096 $params[$fieldName] = $fieldValue;
2101 * Helper function to determine country_id given the myriad of values for country_id or country that are supported
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'];
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);
2119 if (!empty($country->id
)) {
2120 $country_id = $country->id
;
2124 elseif (!empty($params['country'])) {
2125 if (is_numeric($params['country'])) {
2126 $country_id = $params['country'];
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);
2136 if (!empty($country->id
)) {
2137 $country_id = $country->id
;
2141 return !empty($country_id) ?
$country_id : NULL;
2145 * Determine a contact ID using a string expression.
2147 * @param string $contactIdExpr
2148 * E.g. "user_contact_id" or "@user:username".
2150 * @return int|null|'unknown-user'
2151 * @throws \CRM_Core_Exception
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();
2158 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
2159 $config = CRM_Core_Config
::singleton();
2161 $ufID = $config->userSystem
->getUfId($matches[1]);
2163 return 'unknown-user';
2166 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
2168 return 'unknown-user';
2177 * Validate html (check for scripting attack).
2179 * @param array $params
2180 * @param string $fieldName
2181 * @param array $fieldInfo
2183 * @throws API_Exception
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')) {
2193 * Validate string fields being passed into API.
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
2203 * @throws API_Exception
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)) {
2212 if (!is_array($fieldValue)) {
2213 $fieldValue = (string) $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");
2226 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2227 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op);
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]
2237 $params[$fieldName][$op] = $fieldValue;
2240 $params[$fieldName] = $fieldValue;
2245 * Validate & swap out any pseudoconstants / options.
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
2252 * @param array $additional_lookup_params
2254 * @throws \API_Exception
2256 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo, $op = '=', $additional_lookup_params = []) {
2257 if (in_array($op, ['>', '<', '>=', '<=', 'LIKE', 'NOT LIKE'])) {
2261 $options = $fieldInfo['options'] ??
NULL;
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'];
2268 $options_lookup_params = [
2270 'field' => $fieldInfo['name'],
2271 'context' => 'validate',
2273 if (!empty($additional_lookup_params)) {
2274 $options_lookup_params = array_merge($additional_lookup_params, $options_lookup_params);
2276 $options = civicrm_api($entity, 'getoptions', $options_lookup_params);
2278 $options = CRM_Utils_Array
::value('values', $options, []);
2281 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2283 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2284 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
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));
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
2298 CRM_Utils_Array
::implodePadded($fieldValue);
2302 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName, CRM_Utils_Array
::value('api.required', $fieldInfo));
2307 * Validate & swap a single option value for a field.
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.
2317 * @throws API_Exception
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) {
2326 // Hack for Profile formatting fields
2327 if ($fieldName === 'field_name' && (strpos($value, 'formatting') === 0)) {
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) {
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.
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);
2356 if ($newValue === FALSE) {
2357 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, ['error_field' => $fieldName]);
2363 * Returns the canonical name of a field.
2366 * api entity name (string should already be standardized - no camelCase).
2368 * any variation of a field's name (name, unique_name, api.alias).
2370 * @param string $action
2372 * @return bool|string
2373 * FieldName or FALSE if the field does not exist
2375 function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') {
2379 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2382 if ($fieldName === (CRM_Core_DAO_AllCoreTables
::convertEntityNameToLower($entity) . '_id')) {
2385 $result = civicrm_api($entity, 'getfields', [
2387 'action' => $action,
2389 $meta = $result['values'];
2390 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2391 $fieldName = $fieldName . '_id';
2393 if (isset($meta[$fieldName])) {
2394 return $meta[$fieldName]['name'];
2396 foreach ($meta as $info) {
2397 if ($fieldName == $info['name'] ||
$fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2398 return $info['name'];
2400 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, [])) !== FALSE) {
2401 return $info['name'];
2404 // Create didn't work, try with get
2405 if ($action == 'create') {
2406 return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get');
2412 * Check if the function is deprecated.
2414 * @param string $entity
2415 * @param array $result
2417 * @return string|array|null
2419 function _civicrm_api3_deprecation_check($entity, $result = []) {
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);
2430 * Get the actual field value.
2432 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2433 * So this function returns the actual field value.
2435 * @param array $params
2436 * @param string $fieldName
2437 * @param string $type
2441 function _civicrm_api3_field_value_check(&$params, $fieldName, $type = NULL) {
2442 $fieldValue = $params[$fieldName] ??
NULL;
2445 if (!empty($fieldValue) && is_array($fieldValue) &&
2446 (array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators()) ||
2447 $type == 'String' && strstr(key($fieldValue), 'EMPTY'))
2449 $op = key($fieldValue);
2450 $fieldValue = $fieldValue[$op] ??
NULL;
2452 return [$fieldValue, $op];
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.
2461 * @param array $params
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.
2471 * @throws \API_Exception
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;
2482 foreach ($records as $record) {
2483 if ($idCol != 'id') {
2484 $record['id'] = $record[$idCol];
2487 foreach ($params as $k => $v) {
2491 if (in_array($k, $filterableFields) && $record[$k] != $v) {
2497 if ($currentOffset >= $offset) {
2498 $matches[$record[$idCol]] = $record;
2500 if ($limit && count($matches) >= $limit) {
2507 $return = CRM_Utils_Array
::value('return', $options, []);
2508 if (!empty($return)) {
2510 $matches = CRM_Utils_Array
::filterColumns($matches, array_keys($return));
2513 return civicrm_api3_create_success($matches, $params);
2517 * @param string $bao_name
2518 * @param array $params
2519 * @throws \Civi\API\Exception\UnauthorizedException
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',
2530 'CRM_Core_BAO_Website',
2531 'CRM_Core_BAO_OpenID',
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');
2542 * Check if an entity has been modified since the last known modified_date
2544 * @param string $modifiedDate Last knowm modified_date
2545 * @param int $id Id of record to check
2546 * @param string $entity API Entity
2549 * @throws \CiviCRM_API3_Exception
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)) {