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 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = []) {
39 foreach ($keyoptions as $key) {
42 civicrm_api3_verify_mandatory($params, $daoName, $keys);
46 * Check mandatory fields are included.
48 * @param array $params
49 * Array of fields to check.
50 * @param array $daoName
51 * String DAO to check for required fields (create functions only).
53 * List of required fields. A value can be an array denoting that either this or that is required.
54 * @param bool $verifyDAO
56 * @throws \API_Exception
58 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = [], $verifyDAO = TRUE) {
61 if (!empty($params['id'])) {
65 if (!in_array('version', $keys)) {
66 // required from v3 onwards
70 foreach ($keys as $key) {
74 foreach ($key as $subkey) {
75 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
76 $optionset[] = $subkey;
79 // As long as there is one match we don't need to return anything.
83 if (empty($match) && !empty($optionset)) {
84 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
88 // Disallow empty values except for the number zero.
89 // TODO: create a utility for this since it's needed in many places.
90 if (!array_key_exists($key, $params) ||
(empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
95 if (!empty($unmatched)) {
96 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched), "mandatory_missing", ["fields" => $unmatched]);
101 * Create error array.
108 function civicrm_api3_create_error($msg, $data = []) {
109 $data['is_error'] = 1;
110 $data['error_message'] = $msg;
112 // we will show sql to privileged user only (not sure of a specific
113 // security hole here but seems sensible - perhaps should apply to the trace as well?)
114 if (isset($data['sql'])) {
115 if (CRM_Core_Permission
::check('Administer CiviCRM') || CIVICRM_UF
== 'UnitTests') {
116 // Isn't this redundant?
117 $data['debug_information'] = $data['sql'];
127 * Format array in result output style.
129 * @param array|int $values values generated by API operation (the result)
130 * @param array $params
131 * Parameters passed into API call.
132 * @param string $entity
133 * The entity being acted on.
134 * @param string $action
135 * The action passed to the API.
137 * DAO object to be freed here.
138 * @param array $extraReturnValues
139 * Additional values to be added to top level of result array(.
140 * - this param is currently used for legacy behaviour support
144 function civicrm_api3_create_success($values = 1, $params = [], $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = []) {
146 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
147 // TODO: This shouldn't be necessary but this fn sometimes gets called with lowercase entity
148 $entity = _civicrm_api_get_camel_name($entity);
149 $result['is_error'] = 0;
150 //lets set the ['id'] field if it's not set & we know what the entity is
151 if (is_array($values) && $entity && $action != 'getfields') {
152 foreach ($values as $key => $item) {
153 if (empty($item['id']) && !empty($item[$lowercase_entity . "_id"])) {
154 $values[$key]['id'] = $item[$lowercase_entity . "_id"];
156 if (!empty($item['financial_type_id'])) {
157 // 4.3 legacy handling.
158 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
160 if (!empty($item['contribution_cancel_date'])) {
161 // 5.16 legacy handling.
162 $values[$key]['cancel_date'] = $item['contribution_cancel_date'];
164 if (!empty($item['next_sched_contribution_date'])) {
165 // 4.4 legacy handling
166 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
171 if (is_array($params) && !empty($params['debug'])) {
172 if (is_string($action) && $action != 'getfields') {
173 $apiFields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => $action] +
$params);
175 elseif ($action != 'getfields') {
176 $apiFields = civicrm_api($entity, 'getfields', ['version' => 3] +
$params);
183 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
184 $allFields = array_keys($apiFields['values']);
186 $paramFields = array_keys($params);
187 $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), [
206 $result['undefined_fields'] = array_merge($undefined);
210 $result['version'] = 3;
211 if (is_array($values)) {
212 $result['count'] = (int) count($values);
214 // Convert value-separated strings to array
215 if ($action != 'getfields') {
216 _civicrm_api3_separate_values($values);
219 if ($result['count'] == 1) {
220 list($result['id']) = array_keys($values);
222 elseif (!empty($values['id']) && is_int($values['id'])) {
223 $result['id'] = $values['id'];
227 $result['count'] = !empty($values) ?
1 : 0;
230 if (is_array($values) && isset($params['sequential']) &&
231 $params['sequential'] == 1
233 $result['values'] = array_values($values);
236 $result['values'] = $values;
238 if (!empty($params['options']['metadata'])) {
239 // We've made metadata an array but only supporting 'fields' atm.
240 if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
241 $fields = civicrm_api3($entity, 'getfields', [
242 'action' => substr($action, 0, 3) == 'get' ?
'get' : 'create',
244 $result['metadata']['fields'] = $fields['values'];
247 // Report deprecations.
248 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
249 // Always report "setvalue" action as deprecated.
250 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'setvalue')) {
251 $deprecated = ((array) $deprecated) +
['setvalue' => 'The "setvalue" action is deprecated. Use "create" with an id instead.'];
253 // Always report "update" action as deprecated.
254 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'update')) {
255 $deprecated = ((array) $deprecated) +
['update' => 'The "update" action is deprecated. Use "create" with an id instead.'];
258 // Metadata-level deprecations or wholesale entity deprecations.
259 if ($entity == 'Entity' ||
$action == 'getactions' ||
is_string($deprecated)) {
260 $result['deprecated'] = $deprecated;
262 // Action-specific deprecations
263 elseif (!empty($deprecated[$action])) {
264 $result['deprecated'] = $deprecated[$action];
267 return array_merge($result, $extraReturnValues);
271 * Load the DAO of the entity.
277 function _civicrm_api3_load_DAO($entity) {
278 $dao = _civicrm_api3_get_DAO($entity);
287 * Return the DAO of the function or Entity.
289 * @param string $name
290 * Either a function of the api (civicrm_{entity}_create or the entity name.
291 * return the DAO name to manipulate this function
292 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
294 * @return mixed|string
296 function _civicrm_api3_get_DAO($name) {
297 if (strpos($name, 'civicrm_api3') !== FALSE) {
298 $last = strrpos($name, '_');
299 // len ('civicrm_api3_') == 13
300 $name = substr($name, 13, $last - 13);
303 $name = _civicrm_api_get_camel_name($name);
305 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
309 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
311 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
312 if ($name == 'MailingEventQueue') {
313 return 'CRM_Mailing_Event_DAO_Queue';
315 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
316 // but am not confident mailing_recipients is tested so have not tackled.
317 if ($name == 'MailingRecipients') {
318 return 'CRM_Mailing_DAO_Recipients';
320 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
321 if ($name == 'AclRole') {
322 return 'CRM_ACL_DAO_EntityRole';
324 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
325 // But this would impact SMS extensions so need to coordinate
326 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
327 if ($name == 'SmsProvider') {
328 return 'CRM_SMS_DAO_Provider';
330 // FIXME: DAO names should follow CamelCase convention
331 if ($name == 'Im' ||
$name == 'Acl' ||
$name == 'Pcp') {
332 $name = strtoupper($name);
334 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
335 if ($dao ||
!$name) {
339 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
340 if (file_exists("api/v3/$name.php")) {
341 include_once "api/v3/$name.php";
344 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
345 if (function_exists($daoFn)) {
353 * Return the BAO name of the function or Entity.
355 * @param string $name
356 * Is either a function of the api (civicrm_{entity}_create or the entity name.
357 * return the DAO name to manipulate this function
358 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
360 * @return string|null
362 function _civicrm_api3_get_BAO($name) {
363 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
364 if ($name == 'PrintLabel') {
365 return 'CRM_Badge_BAO_Layout';
367 if ($name === 'Order') {
368 // Order basically maps to contribution at the top level but
369 // has enhanced access to other entities.
370 $name = 'Contribution';
372 if ($name === 'Dedupe') {
373 // Dedupe is a pseudoentity for PrevNextCache - but accessing dedupe related info
374 // not the other cache info like search results (which could in fact be in Redis or another cache engine)
375 $name = 'PrevNextCache';
377 if ($name === 'Payment') {
378 $name = 'FinancialTrxn';
380 $dao = _civicrm_api3_get_DAO($name);
384 $bao = str_replace("DAO", "BAO", $dao);
385 $file = strtr($bao, '_', '/') . '.php';
386 // Check if this entity actually has a BAO. Fall back on the DAO if not.
387 return stream_resolve_include_path($file) ?
$bao : $dao;
391 * Recursive function to explode value-separated strings into arrays.
395 function _civicrm_api3_separate_values(&$values) {
396 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
397 foreach ($values as $key => & $value) {
398 if (is_array($value)) {
399 _civicrm_api3_separate_values($value);
401 elseif (is_string($value)) {
402 // This is to honor the way case API was originally written.
403 if ($key == 'case_type_id') {
404 $value = trim(str_replace($sp, ',', $value), ',');
406 elseif (strpos($value, $sp) !== FALSE) {
407 $value = explode($sp, trim($value, $sp));
414 * This is a legacy wrapper for api_store_values.
416 * It checks suitable fields using getfields rather than DAO->fields.
418 * Getfields has handling for how to deal with unique names which dao->fields doesn't
420 * Note this is used by BAO type create functions - eg. contribution
422 * @param string $entity
423 * @param array $params
424 * @param array $values
426 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
427 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'create']);
428 $fields = $fields['values'];
429 _civicrm_api3_store_values($fields, $params, $values);
435 * @param array $fields
436 * @param array $params
437 * @param array $values
441 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
444 $keys = array_intersect_key($params, $fields);
445 foreach ($keys as $name => $value) {
446 if ($name !== 'id') {
447 $values[$name] = $value;
455 * Returns field names of the given entity fields.
457 * @param array $fields
458 * Fields array to retrieve the field names for.
461 function _civicrm_api3_field_names($fields) {
463 foreach ($fields as $key => $value) {
464 if (!empty($value['name'])) {
465 $result[] = $value['name'];
472 * Get function for query object api.
474 * The API supports 2 types of get request. The more complex uses the BAO query object.
475 * This is a generic function for those functions that call it
477 * At the moment only called by contact we should extend to contribution &
478 * others that use the query object. Note that this function passes permission information in.
481 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
485 * @param array $params
486 * As passed into api get or getcount function.
487 * @param array $additional_options
488 * Array of options (so we can modify the filter).
489 * @param bool $getCount
490 * Are we just after the count.
492 * This basically correlates to the component.
493 * @param null|array $defaultReturnProperties
494 * Default return properties for the entity
495 * (used if return not set - but don't do that - set return!).
498 * @throws API_Exception
500 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = [], $getCount = NULL, $mode = 1, $defaultReturnProperties = NULL) {
501 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
502 // Convert id to e.g. contact_id
503 if (empty($params[$lowercase_entity . '_id']) && isset($params['id'])) {
504 $params[$lowercase_entity . '_id'] = $params['id'];
506 unset($params['id']);
508 $options = _civicrm_api3_get_options_from_params($params, TRUE);
510 $inputParams = array_merge(
511 CRM_Utils_Array
::value('input_params', $options, []),
512 CRM_Utils_Array
::value('input_params', $additional_options, [])
514 $returnProperties = array_merge(
515 CRM_Utils_Array
::value('return', $options, []),
516 CRM_Utils_Array
::value('return', $additional_options, [])
518 if (empty($returnProperties)) {
519 $returnProperties = $defaultReturnProperties;
521 if (!empty($params['check_permissions'])) {
522 // we will filter query object against getfields
523 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'get']);
524 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
525 $fields['values'][$lowercase_entity . '_id'] = [];
526 $varsToFilter = ['returnProperties', 'inputParams'];
527 foreach ($varsToFilter as $varToFilter) {
528 if (!is_array($
$varToFilter)) {
531 //I was going to throw an exception rather than silently filter out - but
532 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
533 //so we are silently ignoring parts of their request
534 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
535 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
538 $options = array_merge($options, $additional_options);
539 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
540 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
541 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
542 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
546 $returnProperties = NULL;
549 if (substr($sort, 0, 2) == 'id') {
550 $sort = $lowercase_entity . "_" . $sort;
553 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
555 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
557 list($entities) = CRM_Contact_BAO_Query
::apiQuery(
576 * Get dao query object based on input params.
578 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
581 * @param array $params
582 * @param string $mode
583 * @param string $entity
586 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
588 function _civicrm_api3_get_query_object($params, $mode, $entity) {
589 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
590 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
591 $offset = CRM_Utils_Array
::value('offset', $options);
592 $rowCount = CRM_Utils_Array
::value('limit', $options);
593 $inputParams = CRM_Utils_Array
::value('input_params', $options, []);
594 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
595 if (empty($returnProperties)) {
596 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
599 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
600 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
602 empty($params['check_permissions']),
603 TRUE, TRUE, NULL, 'AND', 'NULL', TRUE
605 list($select, $from, $where, $having) = $query->query();
607 $sql = "$select $from $where $having";
610 $sort = CRM_Utils_Type
::escape($sort, 'MysqlOrderBy');
611 $sql .= " ORDER BY $sort ";
613 if (!empty($rowCount)) {
614 $sql .= " LIMIT $offset, $rowCount ";
616 $dao = CRM_Core_DAO
::executeQuery($sql);
617 return [$dao, $query];
621 * Function transfers the filters being passed into the DAO onto the params object.
623 * @deprecated DAO based retrieval is being phased out.
625 * @param CRM_Core_DAO $dao
626 * @param array $params
627 * @param bool $unique
628 * @param array $extraSql
629 * API specific queries eg for event isCurrent would be converted to
630 * $extraSql['where'] = array('civicrm_event' => array('(start_date >= CURDATE() || end_date >= CURDATE())'));
632 * @throws API_Exception
635 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $extraSql = []) {
636 $entity = _civicrm_api_get_entity_name_from_dao($dao);
637 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
638 if (!empty($params[$lowercase_entity . "_id"]) && empty($params['id'])) {
639 //if entity_id is set then treat it as ID (will be overridden by id if set)
640 $params['id'] = $params[$lowercase_entity . "_id"];
642 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
643 $fields = array_intersect(array_keys($allfields), array_keys($params));
645 $options = _civicrm_api3_get_options_from_params($params);
646 //apply options like sort
647 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
649 //accept filters like filter.activity_date_time_high
650 // std is now 'filters' => ..
651 if (strstr(implode(',', array_keys($params)), 'filter')) {
652 if (isset($params['filters']) && is_array($params['filters'])) {
653 foreach ($params['filters'] as $paramkey => $paramvalue) {
654 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
658 foreach ($params as $paramkey => $paramvalue) {
659 if (strstr($paramkey, 'filter')) {
660 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
669 foreach ($fields as $field) {
670 if (is_array($params[$field])) {
671 //get the actual fieldname from db
672 $fieldName = $allfields[$field]['name'];
673 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
674 if (!empty($where)) {
675 $dao->whereAdd($where);
680 $daoFieldName = $allfields[$field]['name'];
681 if (empty($daoFieldName)) {
682 throw new API_Exception("Failed to determine field name for \"$field\"");
684 $dao->{$daoFieldName} = $params[$field];
687 $dao->$field = $params[$field];
691 if (!empty($extraSql['where'])) {
692 foreach ($extraSql['where'] as $table => $sqlWhere) {
693 foreach ($sqlWhere as $where) {
694 $dao->whereAdd($where);
698 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
700 // Ensure 'id' is included.
701 $options['return']['id'] = TRUE;
702 $allfields = _civicrm_api3_get_unique_name_array($dao);
703 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
704 foreach ($returnMatched as $returnValue) {
705 $dao->selectAdd($returnValue);
708 // Not already matched on the field names.
709 $unmatchedFields = array_diff(
710 array_keys($options['return']),
714 $returnUniqueMatched = array_intersect(
716 // But a match for the field keys.
717 array_flip($allfields)
719 foreach ($returnUniqueMatched as $uniqueVal) {
720 $dao->selectAdd($allfields[$uniqueVal]);
723 $dao->setApiFilter($params);
727 * Apply filters (e.g. high, low) to DAO object (prior to find).
729 * @param string $filterField
730 * Field name of filter.
731 * @param string $filterValue
732 * Field value of filter.
736 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
737 if (strstr($filterField, 'high')) {
738 $fieldName = substr($filterField, 0, -5);
739 $dao->whereAdd("($fieldName <= $filterValue )");
741 if (strstr($filterField, 'low')) {
742 $fieldName = substr($filterField, 0, -4);
743 $dao->whereAdd("($fieldName >= $filterValue )");
745 if ($filterField == 'is_current' && $filterValue == 1) {
746 $todayStart = date('Ymd000000', strtotime('now'));
747 $todayEnd = date('Ymd235959', strtotime('now'));
748 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
749 if (property_exists($dao, 'is_active')) {
750 $dao->whereAdd('is_active = 1');
756 * Get sort, limit etc options from the params - supporting old & new formats.
758 * Get returnProperties for legacy
760 * @param array $params
761 * Params array as passed into civicrm_api.
762 * @param bool $queryObject
763 * Is this supporting a queryObject api (e.g contact) - if so we support more options.
764 * for legacy report & return a unique fields array
766 * @param string $entity
767 * @param string $action
769 * @throws API_Exception
771 * options extracted from params
773 function _civicrm_api3_get_options_from_params($params, $queryObject = FALSE, $entity = '', $action = '') {
774 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
776 $sort = CRM_Utils_Array
::value('sort', $params, 0);
777 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
778 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
780 $offset = CRM_Utils_Array
::value('offset', $params, 0);
781 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
782 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
783 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
785 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
786 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
787 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
789 if (is_array(CRM_Utils_Array
::value('options', $params))) {
790 // is count is set by generic getcount not user
791 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
792 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
793 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
794 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
797 $returnProperties = [];
798 // handle the format return =sort_name,display_name...
799 if (array_key_exists('return', $params)) {
800 if (is_array($params['return'])) {
801 $returnProperties = array_fill_keys($params['return'], 1);
804 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
805 $returnProperties = array_fill_keys($returnProperties, 1);
808 if ($entity && $action == 'get') {
809 if (!empty($returnProperties['id'])) {
810 $returnProperties[$lowercase_entity . '_id'] = 1;
811 unset($returnProperties['id']);
816 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
817 'limit' => (!$is_count && CRM_Utils_Rule
::integer($limit)) ?
$limit : NULL,
818 'is_count' => $is_count,
819 'return' => !empty($returnProperties) ?
$returnProperties : [],
823 $options['sort'] = NULL;
825 if (!is_array($sort)) {
826 $sort = array_map('trim', explode(',', $sort));
828 foreach ($sort as $s) {
829 if ($s == '(1)' || CRM_Utils_Rule
::mysqlOrderBy($s)) {
830 if ($entity && $action == 'get') {
831 switch (trim(strtolower($s))) {
835 $s = str_replace('id', $lowercase_entity . '_id', $s);
841 throw new API_Exception("Unknown field specified for sort. Cannot order by '$s'");
844 $options['sort'] = implode(', ', $finalSort);
847 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
848 throw new API_Exception('invalid string in sort options');
854 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
855 // if the query object is being used this should be used
857 $legacyreturnProperties = [];
859 'sort', 'offset', 'rowCount', 'options', 'return',
860 'version', 'prettyprint', 'check_permissions', 'sequential',
862 foreach ($params as $n => $v) {
863 if (substr($n, 0, 7) == 'return.') {
864 $legacyreturnProperties[substr($n, 7)] = $v;
866 elseif ($n == 'id') {
867 $inputParams[$lowercase_entity . '_id'] = $v;
869 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 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
894 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
895 if (!$options['is_count']) {
896 if (!empty($options['limit'])) {
897 $dao->limit((int) $options['offset'], (int) $options['limit']);
899 if (!empty($options['sort'])) {
900 $options['sort'] = CRM_Utils_Type
::escape($options['sort'], 'MysqlOrderBy');
901 $dao->orderBy($options['sort']);
907 * Build fields array.
909 * This is the array of fields as it relates to the given DAO
910 * returns unique fields as keys by default but if set but can return by DB fields
912 * @param CRM_Core_DAO $bao
913 * @param bool $unique
917 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
918 $fields = $bao->fields();
920 if (empty($fields['id'])) {
921 $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
922 if (isset($fields[$lowercase_entity . '_id'])) {
923 $fields['id'] = $fields[$lowercase_entity . '_id'];
924 unset($fields[$lowercase_entity . '_id']);
930 foreach ($fields as $field) {
931 $dbFields[$field['name']] = $field;
937 * Build fields array.
939 * This is the array of fields as it relates to the given DAO
940 * returns unique fields as keys by default but if set but can return by DB fields
942 * @param CRM_Core_DAO $bao
946 function _civicrm_api3_get_unique_name_array(&$bao) {
947 $fields = $bao->fields();
948 foreach ($fields as $field => $values) {
949 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
951 return $uniqueFields;
955 * Converts an DAO object to an array.
957 * @deprecated - DAO based retrieval is being phased out.
959 * @param CRM_Core_DAO $dao
961 * @param array $params
962 * @param bool $uniqueFields
963 * @param string $entity
964 * @param bool $autoFind
968 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
970 if (isset($params['options']) && !empty($params['options']['is_count'])) {
971 return $dao->count();
976 if ($autoFind && !$dao->find()) {
980 if (isset($dao->count
)) {
984 $fields = array_keys(_civicrm_api3_build_fields_array($dao, FALSE));
985 while ($dao->fetch()) {
987 foreach ($fields as $key) {
988 if (array_key_exists($key, $dao)) {
989 // not sure on that one
990 if ($dao->$key !== NULL) {
991 $tmp[$key] = $dao->$key;
995 $result[$dao->id
] = $tmp;
997 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
998 _civicrm_api3_custom_data_get($result[$dao->id
], $params['check_permissions'], $entity, $dao->id
);
1006 * Determine if custom fields need to be retrieved.
1008 * We currently retrieve all custom fields or none at this level so if we know the entity
1009 * && 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
1010 * @todo filter so only required fields are queried
1012 * @param string $entity
1013 * Entity name in CamelCase.
1014 * @param array $params
1018 function _civicrm_api3_custom_fields_are_required($entity, $params) {
1019 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
1022 $options = _civicrm_api3_get_options_from_params($params);
1023 // We check for possibility of 'custom' => 1 as well as specific custom fields.
1024 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
1025 if (stristr($returnString, 'custom')) {
1031 * Converts an object to an array.
1033 * @param object $dao
1034 * (reference) object to convert.
1035 * @param array $values
1036 * (reference) array.
1037 * @param array|bool $uniqueFields
1039 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
1041 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
1042 foreach ($fields as $key => $value) {
1043 if (array_key_exists($key, $dao)) {
1044 $values[$key] = $dao->$key;
1050 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1057 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1058 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1062 * Format custom parameters.
1064 * @param array $params
1065 * @param array $values
1066 * @param string $extends
1067 * Entity that this custom field extends (e.g. contribution, event, contact).
1068 * @param string $entityId
1069 * ID of entity per $extends.
1071 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1072 $values['custom'] = [];
1073 $checkCheckBoxField = FALSE;
1075 if (in_array($extends, ['Household', 'Individual', 'Organization'])) {
1076 $entity = 'Contact';
1079 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'create']);
1080 if (!$fields['is_error']) {
1081 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1082 $fields = $fields['values'];
1083 $checkCheckBoxField = TRUE;
1086 foreach ($params as $key => $value) {
1087 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
1088 if ($customFieldID && (!is_null($value))) {
1089 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1090 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1093 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1094 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1101 * Format parameters for create action.
1103 * @param array $params
1106 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1107 $nonGenericEntities = ['Contact', 'Individual', 'Household', 'Organization'];
1109 $customFieldEntities = array_diff_key(CRM_Core_SelectValues
::customGroupExtends(), array_fill_keys($nonGenericEntities, 1));
1110 if (!array_key_exists($entity, $customFieldEntities)) {
1114 _civicrm_api3_custom_format_params($params, $values, $entity);
1115 $params = array_merge($params, $values);
1119 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1121 * We should look at pushing to BAO function
1122 * 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
1123 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1125 * 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
1126 * don't touch - lots of very cautious code in here
1128 * The resulting array should look like
1134 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1136 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1137 * be fixed in future
1139 * @param mixed $checkboxFieldValue
1140 * @param string $customFieldLabel
1141 * @param string $entity
1143 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1145 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1146 // We can assume it's pre-formatted.
1149 $options = civicrm_api($entity, 'getoptions', ['field' => $customFieldLabel, 'version' => 3]);
1150 if (!empty($options['is_error'])) {
1151 // The check is precautionary - can probably be removed later.
1155 $options = $options['values'];
1157 if (is_array($checkboxFieldValue)) {
1158 foreach ($checkboxFieldValue as $key => $value) {
1159 if (!array_key_exists($key, $options)) {
1160 $validValue = FALSE;
1164 // we have been passed an array that is already in the 'odd' custom field format
1169 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1170 // if the array only has one item we'll treat it like any other string
1171 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1172 $possibleValue = reset($checkboxFieldValue);
1174 if (is_string($checkboxFieldValue)) {
1175 $possibleValue = $checkboxFieldValue;
1177 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1178 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1181 elseif (is_array($checkboxFieldValue)) {
1182 // so this time around we are considering the values in the array
1183 $possibleValues = $checkboxFieldValue;
1184 $formatValue = TRUE;
1186 elseif (stristr($checkboxFieldValue, ',')) {
1187 $formatValue = TRUE;
1188 //lets see if we should separate it - we do this near the end so we
1189 // ensure we have already checked that the comma is not part of a legitimate match
1190 // and of course, we don't make any changes if we don't now have matches
1191 $possibleValues = explode(',', $checkboxFieldValue);
1194 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1198 foreach ($possibleValues as $index => $possibleValue) {
1199 if (array_key_exists($possibleValue, $options)) {
1200 // 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)
1202 elseif (array_key_exists(trim($possibleValue), $options)) {
1203 $possibleValues[$index] = trim($possibleValue);
1206 $formatValue = FALSE;
1210 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1215 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1217 * @param string $bao_name
1219 * @param array $params
1221 * @param bool $returnAsSuccess
1222 * Return in api success format.
1223 * @param string $entity
1224 * @param CRM_Utils_SQL_Select|NULL $sql
1225 * Extra SQL bits to add to the query. For filtering current events, this might be:
1226 * CRM_Utils_SQL_Select::fragment()->where('(start_date >= CURDATE() || end_date >= CURDATE())');
1227 * @param bool $uniqueFields
1228 * Should unique field names be returned (for backward compatibility)
1232 function _civicrm_api3_basic_get($bao_name, $params, $returnAsSuccess = TRUE, $entity = "", $sql = NULL, $uniqueFields = FALSE) {
1233 $entity = $entity ?
: CRM_Core_DAO_AllCoreTables
::getBriefName(str_replace('_BAO_', '_DAO_', $bao_name));
1234 $options = _civicrm_api3_get_options_from_params($params);
1236 $query = new \Civi\API\
Api3SelectQuery($entity, CRM_Utils_Array
::value('check_permissions', $params, FALSE));
1237 $query->where
= $params;
1238 if ($options['is_count']) {
1239 $query->select
= ['count_rows'];
1242 $query->select
= array_keys(array_filter($options['return']));
1243 $query->orderBy
= $options['sort'];
1244 $query->isFillUniqueFields
= $uniqueFields;
1246 $query->limit
= $options['limit'];
1247 $query->offset
= $options['offset'];
1248 $query->merge($sql);
1249 $result = $query->run();
1251 if ($returnAsSuccess) {
1252 return civicrm_api3_create_success($result, $params, $entity, 'get');
1258 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1260 * @param string $bao_name
1261 * Name of BAO Class.
1262 * @param array $params
1263 * Parameters passed into the api call.
1264 * @param string $entity
1265 * Entity - pass in if entity is non-standard & required $ids array.
1267 * @throws API_Exception
1268 * @throws \Civi\API\Exception\UnauthorizedException
1271 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1272 _civicrm_api3_check_edit_permissions($bao_name, $params);
1273 _civicrm_api3_format_params_for_create($params, $entity);
1274 $args = array(&$params);
1276 $ids = [$entity => CRM_Utils_Array
::value('id', $params)];
1280 if (method_exists($bao_name, 'create')) {
1282 $fct_name = $bao_name . '::' . $fct;
1283 $bao = call_user_func_array([$bao_name, $fct], $args);
1285 elseif (method_exists($bao_name, 'add')) {
1287 $fct_name = $bao_name . '::' . $fct;
1288 $bao = call_user_func_array([$bao_name, $fct], $args);
1291 $fct_name = '_civicrm_api3_basic_create_fallback';
1292 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1295 if (is_null($bao)) {
1296 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1298 elseif (is_a($bao, 'CRM_Core_Error')) {
1299 //some weird circular thing means the error takes itself as an argument
1300 $msg = $bao->getMessages($bao);
1301 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1302 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1303 // so we need to reset the error object here to avoid getting concatenated errors
1304 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1305 CRM_Core_Error
::singleton()->reset();
1306 throw new API_Exception($msg);
1309 // If we have custom fields the BAO may have taken care of it or we may have to.
1310 // $extendsMap provides a pretty good hard-coded list of BAOs that take care of the custom data.
1311 if (isset($params['custom']) && empty(CRM_Core_BAO_CustomQuery
::$extendsMap[$entity])) {
1312 CRM_Core_BAO_CustomValueTable
::store($params['custom'], CRM_Core_DAO_AllCoreTables
::getTableForClass(CRM_Core_DAO_AllCoreTables
::getFullName($entity)), $bao->id
);
1315 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1316 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1321 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1323 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1324 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1326 * @param string $bao_name
1327 * @param array $params
1329 * @throws API_Exception
1331 * @return CRM_Core_DAO|NULL
1332 * An instance of the BAO
1334 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1335 $dao_name = get_parent_class($bao_name);
1336 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1337 $dao_name = $bao_name;
1339 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1340 if (empty($entityName)) {
1341 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", [
1342 'class_name' => $bao_name,
1345 $hook = empty($params['id']) ?
'create' : 'edit';
1347 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1348 $instance = new $dao_name();
1349 $instance->copyValues($params, TRUE);
1351 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1357 * Function to do a 'standard' api del.
1359 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1361 * @param string $bao_name
1362 * @param array $params
1366 * @throws API_Exception
1367 * @throws \Civi\API\Exception\UnauthorizedException
1369 function _civicrm_api3_basic_delete($bao_name, &$params) {
1370 civicrm_api3_verify_mandatory($params, NULL, ['id']);
1371 _civicrm_api3_check_edit_permissions($bao_name, ['id' => $params['id']]);
1372 $args = array(&$params['id']);
1373 if (method_exists($bao_name, 'del')) {
1374 $dao = new $bao_name();
1375 $dao->id
= $params['id'];
1377 $bao = call_user_func_array([$bao_name, 'del'], $args);
1378 if ($bao !== FALSE) {
1379 return civicrm_api3_create_success();
1381 throw new API_Exception('Could not delete entity id ' . $params['id']);
1383 throw new API_Exception('Could not delete entity id ' . $params['id']);
1385 elseif (method_exists($bao_name, 'delete')) {
1386 $dao = new $bao_name();
1387 $dao->id
= $params['id'];
1389 while ($dao->fetch()) {
1391 return civicrm_api3_create_success();
1395 throw new API_Exception('Could not delete entity id ' . $params['id']);
1399 throw new API_Exception('no delete method found');
1403 * Get custom data for the given entity & Add it to the returnArray.
1405 * This looks like 'custom_123' = 'custom string' AND
1406 * 'custom_123_1' = 'custom string'
1407 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1409 * @param array $returnArray
1410 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1411 * @param $checkPermission
1412 * @param string $entity
1413 * E.g membership, event.
1414 * @param int $entity_id
1415 * @param int $groupID
1416 * Per CRM_Core_BAO_CustomGroup::getTree.
1417 * @param int $subType
1418 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1419 * @param string $subName
1420 * Subtype of entity.
1422 function _civicrm_api3_custom_data_get(&$returnArray, $checkPermission, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1423 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1434 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1);
1436 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1438 foreach ($groupTree as $set) {
1439 $fieldInfo +
= $set['fields'];
1441 if (!empty($customValues)) {
1442 foreach ($customValues as $key => $val) {
1443 // per standard - return custom_fieldID
1444 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1445 $returnArray['custom_' . $id] = $val;
1447 //not standard - but some api did this so guess we should keep - cheap as chips
1448 $returnArray[$key] = $val;
1450 // Shim to restore legacy behavior of ContactReference custom fields
1451 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1452 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1453 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1460 * Used by the Validate API.
1461 * @param string $entity
1462 * @param string $action
1463 * @param array $params
1465 * @return array $errors
1467 function _civicrm_api3_validate($entity, $action, $params) {
1469 $fields = civicrm_api3($entity, 'getfields', ['sequential' => 1, 'api_action' => $action]);
1470 $fields = $fields['values'];
1472 // Check for required fields.
1473 foreach ($fields as $values) {
1474 if (!empty($values['api.required']) && empty($params[$values['name']])) {
1475 $errors[$values['name']] = [
1476 'message' => "Mandatory key(s) missing from params array: " . $values['name'],
1477 'code' => "mandatory_missing",
1482 // Select only the fields which have been input as a param.
1484 foreach ($fields as $values) {
1485 if (array_key_exists($values['name'], $params)) {
1486 $finalfields[] = $values;
1490 // This derives heavily from the function "_civicrm_api3_validate_fields".
1491 // However, the difference is that try-catch blocks are nested in the loop, making it
1492 // possible for us to get all errors in one go.
1493 foreach ($finalfields as $fieldInfo) {
1494 $fieldName = $fieldInfo['name'];
1496 _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params);
1498 catch (Exception
$e) {
1499 $errors[$fieldName] = [
1500 'message' => $e->getMessage(),
1501 'code' => 'incorrect_value',
1510 * Used by the Validate API.
1512 * @param array $fieldInfo
1513 * @param string $entity
1514 * @param array $params
1516 * @throws API_Exception
1519 function _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params) {
1520 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1521 case CRM_Utils_Type
::T_INT
:
1522 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1525 case CRM_Utils_Type
::T_DATE
:
1526 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1527 case CRM_Utils_Type
::T_TIMESTAMP
:
1528 //field is of type date or datetime
1529 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1532 case CRM_Utils_Type
::T_TEXT
:
1533 case CRM_Utils_Type
::T_STRING
:
1534 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1537 case CRM_Utils_Type
::T_MONEY
:
1538 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1540 foreach ((array) $fieldValue as $fieldvalue) {
1541 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1542 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1550 * Validate fields being passed into API.
1552 * This function relies on the getFields function working accurately
1553 * for the given API.
1555 * As of writing only date was implemented.
1557 * @param string $entity
1558 * @param string $action
1559 * @param array $params
1561 * @param array $fields
1562 * Response from getfields all variables are the same as per civicrm_api.
1566 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields) {
1567 //CRM-15792 handle datetime for custom fields below code handles chain api call
1568 $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params)));
1569 if (!empty($chainApikeys) && is_array($chainApikeys)) {
1570 foreach ($chainApikeys as $key => $value) {
1571 if (is_array($params[$key])) {
1572 $chainApiParams = array_intersect_key($fields, $params[$key]);
1573 $customFields = array_fill_keys(array_keys($params[$key]), $key);
1577 $fields = array_intersect_key($fields, $params);
1578 if (!empty($chainApiParams)) {
1579 $fields = array_merge($fields, $chainApiParams);
1581 foreach ($fields as $fieldName => $fieldInfo) {
1582 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1583 case CRM_Utils_Type
::T_INT
:
1584 //field is of type integer
1585 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1588 case CRM_Utils_Type
::T_DATE
:
1589 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1590 case CRM_Utils_Type
::T_TIMESTAMP
:
1591 //field is of type date or datetime
1592 if (!empty($customFields) && array_key_exists($fieldName, $customFields)) {
1593 $dateParams = &$params[$customFields[$fieldName]];
1596 $dateParams = &$params;
1598 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
1601 case CRM_Utils_Type
::T_TEXT
:
1602 case CRM_Utils_Type
::T_STRING
:
1603 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1606 case CRM_Utils_Type
::T_MONEY
:
1607 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1608 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1611 foreach ((array) $fieldValue as $fieldvalue) {
1612 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1613 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1622 * Validate foreign key values of fields being passed into API.
1624 * This function relies on the getFields function working accurately
1625 * for the given API.
1627 * @param string $entity
1628 * @param string $action
1629 * @param array $params
1631 * @param array $fields
1632 * Response from getfields all variables are the same as per civicrm_api.
1636 function _civicrm_api3_validate_foreign_keys($entity, $action, &$params, $fields) {
1637 // intensive checks - usually only called after DB level fail
1638 foreach ($fields as $fieldName => $fieldInfo) {
1639 if (!empty($fieldInfo['FKClassName'])) {
1640 if (!empty($params[$fieldName])) {
1641 foreach ((array) $params[$fieldName] as $fieldValue) {
1642 _civicrm_api3_validate_constraint($fieldValue, $fieldName, $fieldInfo);
1645 elseif (!empty($fieldInfo['required'])) {
1646 throw new Exception("DB Constraint Violation - $fieldName should possibly be marked as mandatory for $entity,$action API. If so, please raise a bug report.");
1649 if (!empty($fieldInfo['api.unique'])) {
1650 $params['entity'] = $entity;
1651 _civicrm_api3_validate_unique_key($params, $fieldName);
1657 * Validate date fields being passed into API.
1659 * It currently converts both unique fields and DB field names to a mysql date.
1660 * @todo - probably the unique field handling & the if exists handling is now done before this
1661 * function is reached in the wrapper - can reduce this code down to assume we
1662 * are only checking the passed in field
1664 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1665 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1667 * @param array $params
1668 * Params from civicrm_api.
1669 * @param string $fieldName
1670 * Uniquename of field being checked.
1671 * @param array $fieldInfo
1672 * Array of fields from getfields function.
1676 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1677 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1678 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1682 if ($fieldValue === 'null' && empty($fieldInfo['api.required'])) {
1683 // This is the wierd & wonderful way PEAR sets null.
1687 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1688 if (!empty($params[$fieldInfo['name']])) {
1689 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1691 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1692 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1696 $params[$fieldName][$op] = $fieldValue;
1699 $params[$fieldName] = $fieldValue;
1704 * Convert date into BAO friendly date.
1706 * We accept 'whatever strtotime accepts'
1708 * @param string $dateValue
1709 * @param string $fieldName
1715 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1716 if (is_array($dateValue)) {
1717 foreach ($dateValue as $key => $value) {
1718 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1722 if (strtotime($dateValue) === FALSE) {
1723 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1725 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1726 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1730 * Validate foreign constraint fields being passed into API.
1732 * @param mixed $fieldValue
1733 * @param string $fieldName
1734 * Uniquename of field being checked.
1735 * @param array $fieldInfo
1736 * Array of fields from getfields function.
1738 * @throws \API_Exception
1740 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1741 $daoName = $fieldInfo['FKClassName'];
1742 $dao = new $daoName();
1743 $dao->id
= $fieldValue;
1745 $dao->selectAdd('id');
1746 if (!$dao->find()) {
1747 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1752 * Validate foreign constraint fields being passed into API.
1754 * @param array $params
1755 * Params from civicrm_api.
1756 * @param string $fieldName
1757 * Uniquename of field being checked.
1761 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1762 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1763 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1766 $existing = civicrm_api($params['entity'], 'get', [
1767 'version' => $params['version'],
1768 $fieldName => $fieldValue,
1770 // an entry already exists for this unique field
1771 if ($existing['count'] == 1) {
1772 // question - could this ever be a security issue?
1773 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1778 * Generic implementation of the "replace" action.
1780 * Replace the old set of entities (matching some given keys) with a new set of
1781 * entities (matching the same keys).
1783 * @note This will verify that 'values' is present, but it does not directly verify
1784 * any other parameters.
1786 * @param string $entity
1788 * @param array $params
1789 * Params from civicrm_api, including:.
1790 * - 'values': an array of records to save
1791 * - all other items: keys which identify new/pre-existing records.
1795 function _civicrm_api3_generic_replace($entity, $params) {
1797 $transaction = new CRM_Core_Transaction();
1799 if (!is_array($params['values'])) {
1800 throw new Exception("Mandatory key(s) missing from params array: values");
1803 // Extract the keys -- somewhat scary, don't think too hard about it
1804 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1806 // Lookup pre-existing records
1807 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1808 if (civicrm_error($preexisting)) {
1809 $transaction->rollback();
1810 return $preexisting;
1813 // Save the new/updated records
1815 foreach ($params['values'] as $replacement) {
1816 // Sugar: Don't force clients to duplicate the 'key' data
1817 $replacement = array_merge($baseParams, $replacement);
1818 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1819 $create = civicrm_api($entity, $action, $replacement);
1820 if (civicrm_error($create)) {
1821 $transaction->rollback();
1824 foreach ($create['values'] as $entity_id => $entity_value) {
1825 $creates[$entity_id] = $entity_value;
1829 // Remove stale records
1830 $staleIDs = array_diff(
1831 array_keys($preexisting['values']),
1832 array_keys($creates)
1834 foreach ($staleIDs as $staleID) {
1835 $delete = civicrm_api($entity, 'delete', [
1836 'version' => $params['version'],
1839 if (civicrm_error($delete)) {
1840 $transaction->rollback();
1845 return civicrm_api3_create_success($creates, $params);
1847 catch (PEAR_Exception
$e) {
1848 $transaction->rollback();
1849 return civicrm_api3_create_error($e->getMessage());
1851 catch (Exception
$e) {
1852 $transaction->rollback();
1853 return civicrm_api3_create_error($e->getMessage());
1858 * Replace base parameters.
1860 * @param array $params
1864 function _civicrm_api3_generic_replace_base_params($params) {
1865 $baseParams = $params;
1866 unset($baseParams['values']);
1867 unset($baseParams['sequential']);
1868 unset($baseParams['options']);
1873 * Returns fields allowable by api.
1876 * String Entity to query.
1877 * @param bool $unique
1878 * Index by unique fields?.
1879 * @param array $params
1883 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = []) {
1891 $dao = _civicrm_api3_get_DAO($entity);
1896 $fields = $d->fields();
1898 foreach ($fields as $name => &$field) {
1899 // Denote as core field
1900 $field['is_core_field'] = TRUE;
1901 // Set html attributes for text fields
1902 if (isset($field['html'])) {
1903 $field['html'] +
= (array) $d::makeAttribute($field);
1907 // replace uniqueNames by the normal names as the key
1908 if (empty($unique)) {
1909 foreach ($fields as $name => &$field) {
1910 //getting rid of unused attributes
1911 foreach ($unsetIfEmpty as $attr) {
1912 if (empty($field[$attr])) {
1913 unset($field[$attr]);
1916 if ($name == $field['name']) {
1919 if (array_key_exists($field['name'], $fields)) {
1920 $field['error'] = 'name conflict';
1921 // it should never happen, but better safe than sorry
1924 $fields[$field['name']] = $field;
1925 $fields[$field['name']]['uniqueName'] = $name;
1926 unset($fields[$name]);
1929 // Translate FKClassName to the corresponding api
1930 foreach ($fields as $name => &$field) {
1931 if (!empty($field['FKClassName'])) {
1932 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1934 $field['FKApiName'] = $FKApi;
1938 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1943 * Return an array of fields for a given entity.
1945 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1948 * @param array $params
1952 function _civicrm_api_get_custom_fields($entity, &$params) {
1953 $entity = _civicrm_api_get_camel_name($entity);
1954 if ($entity == 'Contact') {
1955 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1956 $entity = CRM_Utils_Array
::value('contact_type', $params);
1958 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1961 // we could / should probably test for other subtypes here - e.g. activity_type_id
1962 CRM_Utils_Array
::value('contact_sub_type', $params),
1971 foreach ($customfields as $key => $value) {
1972 // Regular fields have a 'name' property
1973 $value['name'] = 'custom_' . $key;
1974 $value['title'] = $value['label'];
1975 if ($value['data_type'] == 'Date' && CRM_Utils_Array
::value('time_format', $value, 0) > 0) {
1976 $value['data_type'] = 'DateTime';
1978 $value['type'] = CRM_Utils_Array
::value($value['data_type'], CRM_Core_BAO_CustomField
::dataToType());
1979 $ret['custom_' . $key] = $value;
1985 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
1987 * If multiple aliases the last takes precedence
1989 * Function also swaps unique fields for non-unique fields & vice versa.
1991 * @param $apiRequest
1994 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1995 foreach ($fields as $field => $values) {
1996 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1997 if (!empty($values['api.aliases'])) {
1998 // if aliased field is not set we try to use field alias
1999 if (!isset($apiRequest['params'][$field])) {
2000 foreach ($values['api.aliases'] as $alias) {
2001 if (isset($apiRequest['params'][$alias])) {
2002 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
2004 //unset original field nb - need to be careful with this as it may bring inconsistencies
2005 // out of the woodwork but will be implementing only as _spec function extended
2006 unset($apiRequest['params'][$alias]);
2010 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
2011 && isset($apiRequest['params'][$values['name']])
2013 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
2014 // note that it would make sense to unset the original field here but tests need to be in place first
2015 if ($field != 'domain_version') {
2016 unset($apiRequest['params'][$values['name']]);
2019 if (!isset($apiRequest['params'][$field])
2021 && $field != $uniqueName
2022 && array_key_exists($uniqueName, $apiRequest['params'])
2024 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
2025 // note that it would make sense to unset the original field here but tests need to be in place first
2032 * Validate integer fields being passed into API.
2034 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
2036 * @param array $params
2037 * Params from civicrm_api.
2038 * @param string $fieldName
2039 * Uniquename of field being checked.
2040 * @param array $fieldInfo
2041 * Array of fields from getfields function.
2042 * @param string $entity
2044 * @throws API_Exception
2046 function _civicrm_api3_validate_integer(&$params, $fieldName, &$fieldInfo, $entity) {
2047 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2048 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2052 if (!empty($fieldValue) ||
$fieldValue === '0' ||
$fieldValue === 0) {
2053 // if value = 'user_contact_id' (or similar), replace value with contact id
2054 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
2055 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
2056 if ('unknown-user' === $realContactId) {
2057 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, ['error_field' => $fieldName, "type" => "integer"]);
2059 elseif (is_numeric($realContactId)) {
2060 $fieldValue = $realContactId;
2062 elseif (is_null($realContactId) && empty($fieldInfo['api.required']) && $fieldValue === 'user_contact_id') {
2063 // If not mandatory this will be OK. If mandatory it should fail.
2067 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2068 $additional_lookup_params = [];
2069 if (strtolower($entity) == 'address' && $fieldName == 'state_province_id') {
2070 $country_id = _civicrm_api3_resolve_country_id($params);
2071 if (!empty($country_id)) {
2072 $additional_lookup_params = ['country_id' => $country_id];
2075 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op, $additional_lookup_params);
2078 // After swapping options, ensure we have an integer(s)
2079 foreach ((array) ($fieldValue) as $value) {
2080 if ($value && !is_numeric($value) && $value !== 'null' && $value !== NULL && !is_array($value)) {
2081 throw new API_Exception("$fieldName is not a valid integer", 2001, ['error_field' => $fieldName, "type" => "integer"]);
2085 // Check our field length
2086 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
2088 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
2089 2100, ['field' => $fieldName, "max_length" => $fieldInfo['maxlength']]
2095 $params[$fieldName][$op] = $fieldValue;
2098 $params[$fieldName] = $fieldValue;
2103 * Helper function to determine country_id given the myriad of values for country_id or country that are supported
2108 function _civicrm_api3_resolve_country_id($params) {
2109 if (!empty($params['country_id'])) {
2110 if (is_numeric($params['country_id'])) {
2111 $country_id = $params['country_id'];
2114 $country = new CRM_Core_DAO_Country();
2115 $country->name
= $params['country_id'];
2116 if (!$country->find(TRUE)) {
2117 $country->name
= NULL;
2118 $country->iso_code
= $params['country_id'];
2119 $country->find(TRUE);
2121 if (!empty($country->id
)) {
2122 $country_id = $country->id
;
2126 elseif (!empty($params['country'])) {
2127 if (is_numeric($params['country'])) {
2128 $country_id = $params['country'];
2131 $country = new CRM_Core_DAO_Country();
2132 $country->name
= $params['country'];
2133 if (!$country->find(TRUE)) {
2134 $country->name
= NULL;
2135 $country->iso_code
= $params['country'];
2136 $country->find(TRUE);
2138 if (!empty($country->id
)) {
2139 $country_id = $country->id
;
2143 return !empty($country_id) ?
$country_id : NULL;
2147 * Determine a contact ID using a string expression.
2149 * @param string $contactIdExpr
2150 * E.g. "user_contact_id" or "@user:username".
2152 * @return int|null|'unknown-user'
2153 * @throws \CRM_Core_Exception
2155 function _civicrm_api3_resolve_contactID($contactIdExpr) {
2156 // If value = 'user_contact_id' replace value with logged in user id.
2157 if ($contactIdExpr == "user_contact_id") {
2158 return CRM_Core_Session
::getLoggedInContactID();
2160 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
2161 $config = CRM_Core_Config
::singleton();
2163 $ufID = $config->userSystem
->getUfId($matches[1]);
2165 return 'unknown-user';
2168 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
2170 return 'unknown-user';
2179 * Validate html (check for scripting attack).
2181 * @param array $params
2182 * @param string $fieldName
2183 * @param array $fieldInfo
2185 * @throws API_Exception
2187 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
2188 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2189 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
2193 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2194 throw new API_Exception('Input contains illegal SCRIPT tag.', ["field" => $fieldName, "error_code" => "xss"]);
2200 * Validate string fields being passed into API.
2202 * @param array $params
2203 * Params from civicrm_api.
2204 * @param string $fieldName
2205 * Uniquename of field being checked.
2206 * @param array $fieldInfo
2207 * Array of fields from getfields function.
2208 * @param string $entity
2210 * @throws API_Exception
2213 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2214 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName, 'String');
2215 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
2219 if (!is_array($fieldValue)) {
2220 $fieldValue = (string) $fieldValue;
2224 foreach ((array) $fieldValue as $key => $value) {
2225 foreach ([$fieldValue, $key, $value] as $input) {
2226 if (!CRM_Utils_Rule
::xssString($input)) {
2227 throw new Exception('Input contains illegal SCRIPT tag.');
2230 if ($fieldName == 'currency') {
2231 //When using IN operator $fieldValue is a array of currency codes
2232 if (!CRM_Utils_Rule
::currencyCode($value)) {
2233 throw new Exception("Currency not a valid code: $currency");
2238 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2239 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op);
2241 // Check our field length
2242 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2243 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2244 2100, ['field' => $fieldName]
2249 $params[$fieldName][$op] = $fieldValue;
2252 $params[$fieldName] = $fieldValue;
2257 * Validate & swap out any pseudoconstants / options.
2259 * @param mixed $fieldValue
2260 * @param string $entity : api entity name
2261 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2262 * @param array $fieldInfo : getfields meta-data
2264 * @param array $additional_lookup_params
2266 * @throws \API_Exception
2268 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo, $op = '=', $additional_lookup_params = []) {
2269 if (in_array($op, ['>', '<', '>=', '<=', 'LIKE', 'NOT LIKE'])) {
2273 $options = CRM_Utils_Array
::value('options', $fieldInfo);
2276 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2277 // We need to get the options from the entity the field relates to.
2278 $entity = $fieldInfo['entity'];
2280 $options_lookup_params = [
2282 'field' => $fieldInfo['name'],
2283 'context' => 'validate',
2285 if (!empty($additional_lookup_params)) {
2286 $options_lookup_params = array_merge($additional_lookup_params, $options_lookup_params);
2288 $options = civicrm_api($entity, 'getoptions', $options_lookup_params);
2290 $options = CRM_Utils_Array
::value('values', $options, []);
2293 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2295 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2296 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
2299 // If passed multiple options, validate each.
2300 if (is_array($fieldValue)) {
2301 foreach ($fieldValue as &$value) {
2302 if (!is_array($value)) {
2303 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName, CRM_Utils_Array
::value('api.required', $fieldInfo));
2306 // TODO: unwrap the call to implodePadded from the conditional and do it always
2307 // need to verify that this is safe and doesn't break anything though.
2308 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2310 CRM_Utils_Array
::implodePadded($fieldValue);
2314 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName, CRM_Utils_Array
::value('api.required', $fieldInfo));
2319 * Validate & swap a single option value for a field.
2321 * @param string $value field value
2322 * @param array $options array of options for this field
2323 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2324 * @param bool $isRequired
2325 * Is this a required field or is 'null' an acceptable option. We allow 'null' last
2326 * in case we have the weird situation of it being a valid option in which case our
2327 * brains will probably explode.
2329 * @throws API_Exception
2331 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName, $isRequired) {
2332 // If option is a key, no need to translate
2333 // or if no options are avaiable for pseudoconstant 'table' property
2334 if (array_key_exists($value, $options) ||
!$options) {
2338 // Hack for Profile formatting fields
2339 if ($fieldName === 'field_name' && (strpos($value, 'formatting') === 0)) {
2343 // Translate value into key
2344 // Cast $value to string to avoid a bug in array_search
2345 $newValue = array_search((string) $value, $options);
2346 if ($newValue !== FALSE) {
2350 // Case-insensitive matching
2351 $newValue = strtolower($value);
2352 $options = array_map("strtolower", $options);
2353 $newValue = array_search($newValue, $options);
2354 if ($newValue === FALSE) {
2355 if ($value === 'null' && !$isRequired) {
2356 // CiviMagic syntax for Nulling out the field - let it through.
2359 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, ['error_field' => $fieldName]);
2365 * Returns the canonical name of a field.
2368 * api entity name (string should already be standardized - no camelCase).
2370 * any variation of a field's name (name, unique_name, api.alias).
2372 * @param string $action
2374 * @return bool|string
2375 * FieldName or FALSE if the field does not exist
2377 function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') {
2381 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2384 if ($fieldName == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
2387 $result = civicrm_api($entity, 'getfields', [
2389 'action' => $action,
2391 $meta = $result['values'];
2392 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2393 $fieldName = $fieldName . '_id';
2395 if (isset($meta[$fieldName])) {
2396 return $meta[$fieldName]['name'];
2398 foreach ($meta as $info) {
2399 if ($fieldName == $info['name'] ||
$fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2400 return $info['name'];
2402 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, [])) !== FALSE) {
2403 return $info['name'];
2406 // Create didn't work, try with get
2407 if ($action == 'create') {
2408 return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get');
2414 * Check if the function is deprecated.
2416 * @param string $entity
2417 * @param array $result
2419 * @return string|array|null
2421 function _civicrm_api3_deprecation_check($entity, $result = []) {
2423 $apiFile = "api/v3/$entity.php";
2424 if (CRM_Utils_File
::isIncludable($apiFile)) {
2425 require_once $apiFile;
2427 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
2428 $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation";
2429 if (function_exists($fnName)) {
2430 return $fnName($result);
2436 * Get the actual field value.
2438 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2439 * So this function returns the actual field value.
2441 * @param array $params
2442 * @param string $fieldName
2443 * @param string $type
2447 function _civicrm_api3_field_value_check(&$params, $fieldName, $type = NULL) {
2448 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2451 if (!empty($fieldValue) && is_array($fieldValue) &&
2452 (array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators()) ||
2453 $type == 'String' && strstr(key($fieldValue), 'EMPTY'))
2455 $op = key($fieldValue);
2456 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2458 return [$fieldValue, $op];
2462 * A generic "get" API based on simple array data. This is comparable to
2463 * _civicrm_api3_basic_get but does not use DAO/BAO. This is useful for
2464 * small/mid-size data loaded from external JSON or XML documents.
2467 * @param array $params
2469 * @param array $records
2470 * List of all records.
2471 * @param string $idCol
2472 * The property which defines the ID of a record
2473 * @param array $filterableFields
2474 * List of filterable fields.
2477 * @throws \API_Exception
2479 function _civicrm_api3_basic_array_get($entity, $params, $records, $idCol, $filterableFields) {
2480 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
2481 // TODO // $sort = CRM_Utils_Array::value('sort', $options, NULL);
2482 $offset = CRM_Utils_Array
::value('offset', $options);
2483 $limit = CRM_Utils_Array
::value('limit', $options);
2488 foreach ($records as $record) {
2489 if ($idCol != 'id') {
2490 $record['id'] = $record[$idCol];
2493 foreach ($params as $k => $v) {
2497 if (in_array($k, $filterableFields) && $record[$k] != $v) {
2503 if ($currentOffset >= $offset) {
2504 $matches[$record[$idCol]] = $record;
2506 if ($limit && count($matches) >= $limit) {
2513 $return = CRM_Utils_Array
::value('return', $options, []);
2514 if (!empty($return)) {
2516 $matches = CRM_Utils_Array
::filterColumns($matches, array_keys($return));
2519 return civicrm_api3_create_success($matches, $params);
2523 * @param string $bao_name
2524 * @param array $params
2525 * @throws \Civi\API\Exception\UnauthorizedException
2527 function _civicrm_api3_check_edit_permissions($bao_name, $params) {
2528 // For lack of something more clever, here's a whitelist of entities whos permissions
2529 // are inherited from a contact record.
2530 // Note, when adding here, also remember to modify _civicrm_api3_permissions()
2531 $contactEntities = [
2532 'CRM_Core_BAO_Email',
2533 'CRM_Core_BAO_Phone',
2534 'CRM_Core_BAO_Address',
2536 'CRM_Core_BAO_Website',
2537 'CRM_Core_BAO_OpenID',
2539 if (!empty($params['check_permissions']) && in_array($bao_name, $contactEntities)) {
2540 $cid = !empty($params['contact_id']) ?
$params['contact_id'] : CRM_Core_DAO
::getFieldValue($bao_name, $params['id'], 'contact_id');
2541 if (!CRM_Contact_BAO_Contact_Permission
::allow($cid, CRM_Core_Permission
::EDIT
)) {
2542 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify contact record');
2548 * Check if an entity has been modified since the last known modified_date
2549 * @param string $modifiedDate Last knowm modified_date
2550 * @param int $id Id of record to check
2551 * @param string $entity API Entity
2554 function _civicrm_api3_compare_timestamps($modifiedDate, $id, $entity) {
2555 $currentDbInfo = civicrm_api3($entity, 'getsingle', ['id' => $id]);
2556 if (strtotime($currentDbInfo['modified_date']) <= strtotime($modifiedDate)) {