3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * CiviCRM APIv3 utility functions.
31 * @package CiviCRM_APIv3
35 * Initialize CiviCRM - should be run at the start of each API function.
37 function _civicrm_api3_initialize() {
38 require_once 'CRM/Core/ClassLoader.php';
39 CRM_Core_ClassLoader
::singleton()->register();
40 CRM_Core_Config
::singleton();
44 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking.
46 * @param array $params
47 * Array of fields to check.
48 * @param array $daoName
49 * String DAO to check for required fields (create functions only).
50 * @param array $keyoptions
51 * List of required fields options. One of the options is required.
53 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = []) {
55 foreach ($keyoptions as $key) {
58 civicrm_api3_verify_mandatory($params, $daoName, $keys);
62 * Check mandatory fields are included.
64 * @param array $params
65 * Array of fields to check.
66 * @param array $daoName
67 * String DAO to check for required fields (create functions only).
69 * List of required fields. A value can be an array denoting that either this or that is required.
70 * @param bool $verifyDAO
72 * @throws \API_Exception
74 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = [], $verifyDAO = TRUE) {
77 if (!empty($params['id'])) {
81 if (!in_array('version', $keys)) {
82 // required from v3 onwards
86 foreach ($keys as $key) {
90 foreach ($key as $subkey) {
91 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
92 $optionset[] = $subkey;
95 // As long as there is one match we don't need to return anything.
99 if (empty($match) && !empty($optionset)) {
100 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
104 // Disallow empty values except for the number zero.
105 // TODO: create a utility for this since it's needed in many places.
106 if (!array_key_exists($key, $params) ||
(empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
111 if (!empty($unmatched)) {
112 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched), "mandatory_missing", ["fields" => $unmatched]);
117 * Create error array.
124 function civicrm_api3_create_error($msg, $data = []) {
125 $data['is_error'] = 1;
126 $data['error_message'] = $msg;
128 // we will show sql to privileged user only (not sure of a specific
129 // security hole here but seems sensible - perhaps should apply to the trace as well?)
130 if (isset($data['sql'])) {
131 if (CRM_Core_Permission
::check('Administer CiviCRM') || CIVICRM_UF
== 'UnitTests') {
132 // Isn't this redundant?
133 $data['debug_information'] = $data['sql'];
143 * Format array in result output style.
145 * @param array|int $values values generated by API operation (the result)
146 * @param array $params
147 * Parameters passed into API call.
148 * @param string $entity
149 * The entity being acted on.
150 * @param string $action
151 * The action passed to the API.
153 * DAO object to be freed here.
154 * @param array $extraReturnValues
155 * Additional values to be added to top level of result array(.
156 * - this param is currently used for legacy behaviour support
160 function civicrm_api3_create_success($values = 1, $params = [], $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = []) {
162 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
163 // TODO: This shouldn't be necessary but this fn sometimes gets called with lowercase entity
164 $entity = _civicrm_api_get_camel_name($entity);
165 $result['is_error'] = 0;
166 //lets set the ['id'] field if it's not set & we know what the entity is
167 if (is_array($values) && $entity && $action != 'getfields') {
168 foreach ($values as $key => $item) {
169 if (empty($item['id']) && !empty($item[$lowercase_entity . "_id"])) {
170 $values[$key]['id'] = $item[$lowercase_entity . "_id"];
172 if (!empty($item['financial_type_id'])) {
173 // 4.3 legacy handling.
174 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
176 if (!empty($item['next_sched_contribution_date'])) {
177 // 4.4 legacy handling
178 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
183 if (is_array($params) && !empty($params['debug'])) {
184 if (is_string($action) && $action != 'getfields') {
185 $apiFields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => $action] +
$params);
187 elseif ($action != 'getfields') {
188 $apiFields = civicrm_api($entity, 'getfields', ['version' => 3] +
$params);
195 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
196 $allFields = array_keys($apiFields['values']);
198 $paramFields = array_keys($params);
199 $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), [
218 $result['undefined_fields'] = array_merge($undefined);
222 $result['version'] = 3;
223 if (is_array($values)) {
224 $result['count'] = (int) count($values);
226 // Convert value-separated strings to array
227 if ($action != 'getfields') {
228 _civicrm_api3_separate_values($values);
231 if ($result['count'] == 1) {
232 list($result['id']) = array_keys($values);
234 elseif (!empty($values['id']) && is_int($values['id'])) {
235 $result['id'] = $values['id'];
239 $result['count'] = !empty($values) ?
1 : 0;
242 if (is_array($values) && isset($params['sequential']) &&
243 $params['sequential'] == 1
245 $result['values'] = array_values($values);
248 $result['values'] = $values;
250 if (!empty($params['options']['metadata'])) {
251 // We've made metadata an array but only supporting 'fields' atm.
252 if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
253 $fields = civicrm_api3($entity, 'getfields', [
254 'action' => substr($action, 0, 3) == 'get' ?
'get' : 'create',
256 $result['metadata']['fields'] = $fields['values'];
259 // Report deprecations.
260 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
261 // Always report "setvalue" action as deprecated.
262 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'setvalue')) {
263 $deprecated = ((array) $deprecated) +
['setvalue' => 'The "setvalue" action is deprecated. Use "create" with an id instead.'];
265 // Always report "update" action as deprecated.
266 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'update')) {
267 $deprecated = ((array) $deprecated) +
['update' => 'The "update" action is deprecated. Use "create" with an id instead.'];
270 // Metadata-level deprecations or wholesale entity deprecations.
271 if ($entity == 'Entity' ||
$action == 'getactions' ||
is_string($deprecated)) {
272 $result['deprecated'] = $deprecated;
274 // Action-specific deprecations
275 elseif (!empty($deprecated[$action])) {
276 $result['deprecated'] = $deprecated[$action];
279 return array_merge($result, $extraReturnValues);
283 * Load the DAO of the entity.
289 function _civicrm_api3_load_DAO($entity) {
290 $dao = _civicrm_api3_get_DAO($entity);
299 * Return the DAO of the function or Entity.
301 * @param string $name
302 * Either a function of the api (civicrm_{entity}_create or the entity name.
303 * return the DAO name to manipulate this function
304 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
306 * @return mixed|string
308 function _civicrm_api3_get_DAO($name) {
309 if (strpos($name, 'civicrm_api3') !== FALSE) {
310 $last = strrpos($name, '_');
311 // len ('civicrm_api3_') == 13
312 $name = substr($name, 13, $last - 13);
315 $name = _civicrm_api_get_camel_name($name);
317 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
321 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
323 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
324 if ($name == 'MailingEventQueue') {
325 return 'CRM_Mailing_Event_DAO_Queue';
327 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
328 // but am not confident mailing_recipients is tested so have not tackled.
329 if ($name == 'MailingRecipients') {
330 return 'CRM_Mailing_DAO_Recipients';
332 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
333 if ($name == 'AclRole') {
334 return 'CRM_ACL_DAO_EntityRole';
336 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
337 // But this would impact SMS extensions so need to coordinate
338 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
339 if ($name == 'SmsProvider') {
340 return 'CRM_SMS_DAO_Provider';
342 // FIXME: DAO names should follow CamelCase convention
343 if ($name == 'Im' ||
$name == 'Acl' ||
$name == 'Pcp') {
344 $name = strtoupper($name);
346 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
347 if ($dao ||
!$name) {
351 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
352 if (file_exists("api/v3/$name.php")) {
353 include_once "api/v3/$name.php";
356 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
357 if (function_exists($daoFn)) {
365 * Return the BAO name of the function or Entity.
367 * @param string $name
368 * Is either a function of the api (civicrm_{entity}_create or the entity name.
369 * return the DAO name to manipulate this function
370 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
372 * @return string|null
374 function _civicrm_api3_get_BAO($name) {
375 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
376 if ($name == 'PrintLabel') {
377 return 'CRM_Badge_BAO_Layout';
379 if ($name === 'Order') {
380 // Order basically maps to contribution at the top level but
381 // has enhanced access to other entities.
382 $name = 'Contribution';
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.
461 * @param array $fields
462 * Fields array to retrieve the field names for.
465 function _civicrm_api3_field_names($fields) {
467 foreach ($fields as $key => $value) {
468 if (!empty($value['name'])) {
469 $result[] = $value['name'];
476 * Get function for query object api.
478 * The API supports 2 types of get request. The more complex uses the BAO query object.
479 * This is a generic function for those functions that call it
481 * At the moment only called by contact we should extend to contribution &
482 * others that use the query object. Note that this function passes permission information in.
485 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
489 * @param array $params
490 * As passed into api get or getcount function.
491 * @param array $additional_options
492 * Array of options (so we can modify the filter).
493 * @param bool $getCount
494 * Are we just after the count.
496 * This basically correlates to the component.
497 * @param null|array $defaultReturnProperties
498 * Default return properties for the entity
499 * (used if return not set - but don't do that - set return!).
502 * @throws API_Exception
504 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = [], $getCount = NULL, $mode = 1, $defaultReturnProperties = NULL) {
505 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
506 // Convert id to e.g. contact_id
507 if (empty($params[$lowercase_entity . '_id']) && isset($params['id'])) {
508 $params[$lowercase_entity . '_id'] = $params['id'];
510 unset($params['id']);
512 $options = _civicrm_api3_get_options_from_params($params, TRUE);
514 $inputParams = array_merge(
515 CRM_Utils_Array
::value('input_params', $options, []),
516 CRM_Utils_Array
::value('input_params', $additional_options, [])
518 $returnProperties = array_merge(
519 CRM_Utils_Array
::value('return', $options, []),
520 CRM_Utils_Array
::value('return', $additional_options, [])
522 if (empty($returnProperties)) {
523 $returnProperties = $defaultReturnProperties;
525 if (!empty($params['check_permissions'])) {
526 // we will filter query object against getfields
527 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'get']);
528 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
529 $fields['values'][$lowercase_entity . '_id'] = [];
530 $varsToFilter = ['returnProperties', 'inputParams'];
531 foreach ($varsToFilter as $varToFilter) {
532 if (!is_array($
$varToFilter)) {
535 //I was going to throw an exception rather than silently filter out - but
536 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
537 //so we are silently ignoring parts of their request
538 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
539 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
542 $options = array_merge($options, $additional_options);
543 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
544 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
545 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
546 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
550 $returnProperties = NULL;
553 if (substr($sort, 0, 2) == 'id') {
554 $sort = $lowercase_entity . "_" . $sort;
557 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
559 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
561 list($entities) = CRM_Contact_BAO_Query
::apiQuery(
580 * Get dao query object based on input params.
582 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
585 * @param array $params
586 * @param string $mode
587 * @param string $entity
590 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
592 function _civicrm_api3_get_query_object($params, $mode, $entity) {
593 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
594 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
595 $offset = CRM_Utils_Array
::value('offset', $options);
596 $rowCount = CRM_Utils_Array
::value('limit', $options);
597 $inputParams = CRM_Utils_Array
::value('input_params', $options, []);
598 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
599 if (empty($returnProperties)) {
600 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
603 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
604 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
606 empty($params['check_permissions']),
607 TRUE, TRUE, NULL, 'AND', 'NULL', TRUE
609 list($select, $from, $where, $having) = $query->query();
611 $sql = "$select $from $where $having";
614 $sort = CRM_Utils_Type
::escape($sort, 'MysqlOrderBy');
615 $sql .= " ORDER BY $sort ";
617 if (!empty($rowCount)) {
618 $sql .= " LIMIT $offset, $rowCount ";
620 $dao = CRM_Core_DAO
::executeQuery($sql);
621 return [$dao, $query];
625 * Function transfers the filters being passed into the DAO onto the params object.
627 * @deprecated DAO based retrieval is being phased out.
629 * @param CRM_Core_DAO $dao
630 * @param array $params
631 * @param bool $unique
632 * @param array $extraSql
633 * API specific queries eg for event isCurrent would be converted to
634 * $extraSql['where'] = array('civicrm_event' => array('(start_date >= CURDATE() || end_date >= CURDATE())'));
636 * @throws API_Exception
639 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $extraSql = []) {
640 $entity = _civicrm_api_get_entity_name_from_dao($dao);
641 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
642 if (!empty($params[$lowercase_entity . "_id"]) && empty($params['id'])) {
643 //if entity_id is set then treat it as ID (will be overridden by id if set)
644 $params['id'] = $params[$lowercase_entity . "_id"];
646 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
647 $fields = array_intersect(array_keys($allfields), array_keys($params));
649 $options = _civicrm_api3_get_options_from_params($params);
650 //apply options like sort
651 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
653 //accept filters like filter.activity_date_time_high
654 // std is now 'filters' => ..
655 if (strstr(implode(',', array_keys($params)), 'filter')) {
656 if (isset($params['filters']) && is_array($params['filters'])) {
657 foreach ($params['filters'] as $paramkey => $paramvalue) {
658 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
662 foreach ($params as $paramkey => $paramvalue) {
663 if (strstr($paramkey, 'filter')) {
664 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
673 foreach ($fields as $field) {
674 if (is_array($params[$field])) {
675 //get the actual fieldname from db
676 $fieldName = $allfields[$field]['name'];
677 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
678 if (!empty($where)) {
679 $dao->whereAdd($where);
684 $daoFieldName = $allfields[$field]['name'];
685 if (empty($daoFieldName)) {
686 throw new API_Exception("Failed to determine field name for \"$field\"");
688 $dao->{$daoFieldName} = $params[$field];
691 $dao->$field = $params[$field];
695 if (!empty($extraSql['where'])) {
696 foreach ($extraSql['where'] as $table => $sqlWhere) {
697 foreach ($sqlWhere as $where) {
698 $dao->whereAdd($where);
702 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
704 // Ensure 'id' is included.
705 $options['return']['id'] = TRUE;
706 $allfields = _civicrm_api3_get_unique_name_array($dao);
707 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
708 foreach ($returnMatched as $returnValue) {
709 $dao->selectAdd($returnValue);
712 // Not already matched on the field names.
713 $unmatchedFields = array_diff(
714 array_keys($options['return']),
718 $returnUniqueMatched = array_intersect(
720 // But a match for the field keys.
721 array_flip($allfields)
723 foreach ($returnUniqueMatched as $uniqueVal) {
724 $dao->selectAdd($allfields[$uniqueVal]);
727 $dao->setApiFilter($params);
731 * Apply filters (e.g. high, low) to DAO object (prior to find).
733 * @param string $filterField
734 * Field name of filter.
735 * @param string $filterValue
736 * Field value of filter.
740 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
741 if (strstr($filterField, 'high')) {
742 $fieldName = substr($filterField, 0, -5);
743 $dao->whereAdd("($fieldName <= $filterValue )");
745 if (strstr($filterField, 'low')) {
746 $fieldName = substr($filterField, 0, -4);
747 $dao->whereAdd("($fieldName >= $filterValue )");
749 if ($filterField == 'is_current' && $filterValue == 1) {
750 $todayStart = date('Ymd000000', strtotime('now'));
751 $todayEnd = date('Ymd235959', strtotime('now'));
752 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
753 if (property_exists($dao, 'is_active')) {
754 $dao->whereAdd('is_active = 1');
760 * Get sort, limit etc options from the params - supporting old & new formats.
762 * Get returnProperties for legacy
764 * @param array $params
765 * Params array as passed into civicrm_api.
766 * @param bool $queryObject
767 * Is this supporting a queryObject api (e.g contact) - if so we support more options.
768 * for legacy report & return a unique fields array
770 * @param string $entity
771 * @param string $action
773 * @throws API_Exception
775 * options extracted from params
777 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
778 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
780 $sort = CRM_Utils_Array
::value('sort', $params, 0);
781 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
782 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
784 $offset = CRM_Utils_Array
::value('offset', $params, 0);
785 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
786 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
787 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
789 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
790 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
791 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
793 if (is_array(CRM_Utils_Array
::value('options', $params))) {
794 // is count is set by generic getcount not user
795 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
796 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
797 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
798 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
801 $returnProperties = [];
802 // handle the format return =sort_name,display_name...
803 if (array_key_exists('return', $params)) {
804 if (is_array($params['return'])) {
805 $returnProperties = array_fill_keys($params['return'], 1);
808 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
809 $returnProperties = array_fill_keys($returnProperties, 1);
812 if ($entity && $action == 'get') {
813 if (!empty($returnProperties['id'])) {
814 $returnProperties[$lowercase_entity . '_id'] = 1;
815 unset($returnProperties['id']);
820 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
821 'limit' => (!$is_count && CRM_Utils_Rule
::integer($limit)) ?
$limit : NULL,
822 'is_count' => $is_count,
823 'return' => !empty($returnProperties) ?
$returnProperties : [],
827 $options['sort'] = NULL;
829 if (!is_array($sort)) {
830 $sort = array_map('trim', explode(',', $sort));
832 foreach ($sort as $s) {
833 if ($s == '(1)' || CRM_Utils_Rule
::mysqlOrderBy($s)) {
834 if ($entity && $action == 'get') {
835 switch (trim(strtolower($s))) {
839 $s = str_replace('id', $lowercase_entity . '_id', $s);
845 throw new API_Exception("Unknown field specified for sort. Cannot order by '$s'");
848 $options['sort'] = implode(', ', $finalSort);
851 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
852 throw new API_Exception('invalid string in sort options');
858 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
859 // if the query object is being used this should be used
861 $legacyreturnProperties = [];
863 'sort', 'offset', 'rowCount', 'options', 'return',
864 'version', 'prettyprint', 'check_permissions', 'sequential',
866 foreach ($params as $n => $v) {
867 if (substr($n, 0, 7) == 'return.') {
868 $legacyreturnProperties[substr($n, 7)] = $v;
870 elseif ($n == 'id') {
871 $inputParams[$lowercase_entity . '_id'] = $v;
873 elseif (in_array($n, $otherVars)) {
876 $inputParams[$n] = $v;
877 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
878 throw new API_Exception('invalid string');
882 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
883 $options['input_params'] = $inputParams;
888 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
890 * @param array $params
891 * Params array as passed into civicrm_api.
896 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
898 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
899 if (!$options['is_count']) {
900 if (!empty($options['limit'])) {
901 $dao->limit((int) $options['offset'], (int) $options['limit']);
903 if (!empty($options['sort'])) {
904 $options['sort'] = CRM_Utils_Type
::escape($options['sort'], 'MysqlOrderBy');
905 $dao->orderBy($options['sort']);
911 * Build fields array.
913 * This is the array of fields as it relates to the given DAO
914 * returns unique fields as keys by default but if set but can return by DB fields
916 * @param CRM_Core_DAO $bao
917 * @param bool $unique
921 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
922 $fields = $bao->fields();
924 if (empty($fields['id'])) {
925 $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
926 if (isset($fields[$lowercase_entity . '_id'])) {
927 $fields['id'] = $fields[$lowercase_entity . '_id'];
928 unset($fields[$lowercase_entity . '_id']);
934 foreach ($fields as $field) {
935 $dbFields[$field['name']] = $field;
941 * Build fields array.
943 * This is the array of fields as it relates to the given DAO
944 * returns unique fields as keys by default but if set but can return by DB fields
946 * @param CRM_Core_DAO $bao
950 function _civicrm_api3_get_unique_name_array(&$bao) {
951 $fields = $bao->fields();
952 foreach ($fields as $field => $values) {
953 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
955 return $uniqueFields;
959 * Converts an DAO object to an array.
961 * @deprecated - DAO based retrieval is being phased out.
963 * @param CRM_Core_DAO $dao
965 * @param array $params
966 * @param bool $uniqueFields
967 * @param string $entity
968 * @param bool $autoFind
972 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
974 if (isset($params['options']) && !empty($params['options']['is_count'])) {
975 return $dao->count();
980 if ($autoFind && !$dao->find()) {
984 if (isset($dao->count
)) {
988 $fields = array_keys(_civicrm_api3_build_fields_array($dao, FALSE));
989 while ($dao->fetch()) {
991 foreach ($fields as $key) {
992 if (array_key_exists($key, $dao)) {
993 // not sure on that one
994 if ($dao->$key !== NULL) {
995 $tmp[$key] = $dao->$key;
999 $result[$dao->id
] = $tmp;
1001 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
1002 _civicrm_api3_custom_data_get($result[$dao->id
], $params['check_permissions'], $entity, $dao->id
);
1010 * Determine if custom fields need to be retrieved.
1012 * We currently retrieve all custom fields or none at this level so if we know the entity
1013 * && 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
1014 * @todo filter so only required fields are queried
1016 * @param string $entity
1017 * Entity name in CamelCase.
1018 * @param array $params
1022 function _civicrm_api3_custom_fields_are_required($entity, $params) {
1023 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
1026 $options = _civicrm_api3_get_options_from_params($params);
1027 // We check for possibility of 'custom' => 1 as well as specific custom fields.
1028 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
1029 if (stristr($returnString, 'custom')) {
1035 * Converts an object to an array.
1037 * @param object $dao
1038 * (reference) object to convert.
1039 * @param array $values
1040 * (reference) array.
1041 * @param array|bool $uniqueFields
1043 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
1045 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
1046 foreach ($fields as $key => $value) {
1047 if (array_key_exists($key, $dao)) {
1048 $values[$key] = $dao->$key;
1054 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1061 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1062 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1066 * Format custom parameters.
1068 * @param array $params
1069 * @param array $values
1070 * @param string $extends
1071 * Entity that this custom field extends (e.g. contribution, event, contact).
1072 * @param string $entityId
1073 * ID of entity per $extends.
1075 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1076 $values['custom'] = [];
1077 $checkCheckBoxField = FALSE;
1079 if (in_array($extends, ['Household', 'Individual', 'Organization'])) {
1080 $entity = 'Contact';
1083 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'create']);
1084 if (!$fields['is_error']) {
1085 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1086 $fields = $fields['values'];
1087 $checkCheckBoxField = TRUE;
1090 foreach ($params as $key => $value) {
1091 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
1092 if ($customFieldID && (!is_null($value))) {
1093 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1094 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1097 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1098 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1105 * Format parameters for create action.
1107 * @param array $params
1110 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1111 $nonGenericEntities = ['Contact', 'Individual', 'Household', 'Organization'];
1113 $customFieldEntities = array_diff_key(CRM_Core_SelectValues
::customGroupExtends(), array_fill_keys($nonGenericEntities, 1));
1114 if (!array_key_exists($entity, $customFieldEntities)) {
1118 _civicrm_api3_custom_format_params($params, $values, $entity);
1119 $params = array_merge($params, $values);
1123 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1125 * We should look at pushing to BAO function
1126 * 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
1127 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1129 * 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
1130 * don't touch - lots of very cautious code in here
1132 * The resulting array should look like
1138 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1140 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1141 * be fixed in future
1143 * @param mixed $checkboxFieldValue
1144 * @param string $customFieldLabel
1145 * @param string $entity
1147 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1149 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1150 // We can assume it's pre-formatted.
1153 $options = civicrm_api($entity, 'getoptions', ['field' => $customFieldLabel, 'version' => 3]);
1154 if (!empty($options['is_error'])) {
1155 // The check is precautionary - can probably be removed later.
1159 $options = $options['values'];
1161 if (is_array($checkboxFieldValue)) {
1162 foreach ($checkboxFieldValue as $key => $value) {
1163 if (!array_key_exists($key, $options)) {
1164 $validValue = FALSE;
1168 // we have been passed an array that is already in the 'odd' custom field format
1173 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1174 // if the array only has one item we'll treat it like any other string
1175 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1176 $possibleValue = reset($checkboxFieldValue);
1178 if (is_string($checkboxFieldValue)) {
1179 $possibleValue = $checkboxFieldValue;
1181 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1182 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1185 elseif (is_array($checkboxFieldValue)) {
1186 // so this time around we are considering the values in the array
1187 $possibleValues = $checkboxFieldValue;
1188 $formatValue = TRUE;
1190 elseif (stristr($checkboxFieldValue, ',')) {
1191 $formatValue = TRUE;
1192 //lets see if we should separate it - we do this near the end so we
1193 // ensure we have already checked that the comma is not part of a legitimate match
1194 // and of course, we don't make any changes if we don't now have matches
1195 $possibleValues = explode(',', $checkboxFieldValue);
1198 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1202 foreach ($possibleValues as $index => $possibleValue) {
1203 if (array_key_exists($possibleValue, $options)) {
1204 // 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)
1206 elseif (array_key_exists(trim($possibleValue), $options)) {
1207 $possibleValues[$index] = trim($possibleValue);
1210 $formatValue = FALSE;
1214 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1219 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1221 * @param string $bao_name
1223 * @param array $params
1225 * @param bool $returnAsSuccess
1226 * Return in api success format.
1227 * @param string $entity
1228 * @param CRM_Utils_SQL_Select|NULL $sql
1229 * Extra SQL bits to add to the query. For filtering current events, this might be:
1230 * CRM_Utils_SQL_Select::fragment()->where('(start_date >= CURDATE() || end_date >= CURDATE())');
1231 * @param bool $uniqueFields
1232 * Should unique field names be returned (for backward compatibility)
1236 function _civicrm_api3_basic_get($bao_name, $params, $returnAsSuccess = TRUE, $entity = "", $sql = NULL, $uniqueFields = FALSE) {
1237 $entity = $entity ?
: CRM_Core_DAO_AllCoreTables
::getBriefName(str_replace('_BAO_', '_DAO_', $bao_name));
1238 $options = _civicrm_api3_get_options_from_params($params);
1240 $query = new \Civi\API\
Api3SelectQuery($entity, CRM_Utils_Array
::value('check_permissions', $params, FALSE));
1241 $query->where
= $params;
1242 if ($options['is_count']) {
1243 $query->select
= ['count_rows'];
1246 $query->select
= array_keys(array_filter($options['return']));
1247 $query->orderBy
= $options['sort'];
1248 $query->isFillUniqueFields
= $uniqueFields;
1250 $query->limit
= $options['limit'];
1251 $query->offset
= $options['offset'];
1252 $query->merge($sql);
1253 $result = $query->run();
1255 if ($returnAsSuccess) {
1256 return civicrm_api3_create_success($result, $params, $entity, 'get');
1262 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1264 * @param string $bao_name
1265 * Name of BAO Class.
1266 * @param array $params
1267 * Parameters passed into the api call.
1268 * @param string $entity
1269 * Entity - pass in if entity is non-standard & required $ids array.
1271 * @throws API_Exception
1272 * @throws \Civi\API\Exception\UnauthorizedException
1275 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1276 _civicrm_api3_check_edit_permissions($bao_name, $params);
1277 _civicrm_api3_format_params_for_create($params, $entity);
1278 $args = array(&$params);
1280 $ids = [$entity => CRM_Utils_Array
::value('id', $params)];
1284 if (method_exists($bao_name, 'create')) {
1286 $fct_name = $bao_name . '::' . $fct;
1287 $bao = call_user_func_array([$bao_name, $fct], $args);
1289 elseif (method_exists($bao_name, 'add')) {
1291 $fct_name = $bao_name . '::' . $fct;
1292 $bao = call_user_func_array([$bao_name, $fct], $args);
1295 $fct_name = '_civicrm_api3_basic_create_fallback';
1296 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1299 if (is_null($bao)) {
1300 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1302 elseif (is_a($bao, 'CRM_Core_Error')) {
1303 //some weird circular thing means the error takes itself as an argument
1304 $msg = $bao->getMessages($bao);
1305 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1306 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1307 // so we need to reset the error object here to avoid getting concatenated errors
1308 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1309 CRM_Core_Error
::singleton()->reset();
1310 throw new API_Exception($msg);
1313 // If we have custom fields the BAO may have taken care of it or we may have to.
1314 // $extendsMap provides a pretty good hard-coded list of BAOs that take care of the custom data.
1315 if (isset($params['custom']) && empty(CRM_Core_BAO_CustomQuery
::$extendsMap[$entity])) {
1316 CRM_Core_BAO_CustomValueTable
::store($params['custom'], CRM_Core_DAO_AllCoreTables
::getTableForClass(CRM_Core_DAO_AllCoreTables
::getFullName($entity)), $bao->id
);
1319 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1320 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1325 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1327 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1328 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1330 * @param string $bao_name
1331 * @param array $params
1333 * @throws API_Exception
1335 * @return CRM_Core_DAO|NULL
1336 * An instance of the BAO
1338 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1339 $dao_name = get_parent_class($bao_name);
1340 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1341 $dao_name = $bao_name;
1343 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1344 if (empty($entityName)) {
1345 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", [
1346 'class_name' => $bao_name,
1349 $hook = empty($params['id']) ?
'create' : 'edit';
1351 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1352 $instance = new $dao_name();
1353 $instance->copyValues($params, TRUE);
1355 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1361 * Function to do a 'standard' api del.
1363 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1365 * @param string $bao_name
1366 * @param array $params
1370 * @throws API_Exception
1371 * @throws \Civi\API\Exception\UnauthorizedException
1373 function _civicrm_api3_basic_delete($bao_name, &$params) {
1374 civicrm_api3_verify_mandatory($params, NULL, ['id']);
1375 _civicrm_api3_check_edit_permissions($bao_name, ['id' => $params['id']]);
1376 $args = array(&$params['id']);
1377 if (method_exists($bao_name, 'del')) {
1378 $dao = new $bao_name();
1379 $dao->id
= $params['id'];
1381 $bao = call_user_func_array([$bao_name, 'del'], $args);
1382 if ($bao !== FALSE) {
1383 return civicrm_api3_create_success();
1385 throw new API_Exception('Could not delete entity id ' . $params['id']);
1387 throw new API_Exception('Could not delete entity id ' . $params['id']);
1389 elseif (method_exists($bao_name, 'delete')) {
1390 $dao = new $bao_name();
1391 $dao->id
= $params['id'];
1393 while ($dao->fetch()) {
1395 return civicrm_api3_create_success();
1399 throw new API_Exception('Could not delete entity id ' . $params['id']);
1403 throw new API_Exception('no delete method found');
1407 * Get custom data for the given entity & Add it to the returnArray.
1409 * This looks like 'custom_123' = 'custom string' AND
1410 * 'custom_123_1' = 'custom string'
1411 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1413 * @param array $returnArray
1414 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1415 * @param $checkPermission
1416 * @param string $entity
1417 * E.g membership, event.
1418 * @param int $entity_id
1419 * @param int $groupID
1420 * Per CRM_Core_BAO_CustomGroup::getTree.
1421 * @param int $subType
1422 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1423 * @param string $subName
1424 * Subtype of entity.
1426 function _civicrm_api3_custom_data_get(&$returnArray, $checkPermission, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1427 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1438 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1);
1440 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1442 foreach ($groupTree as $set) {
1443 $fieldInfo +
= $set['fields'];
1445 if (!empty($customValues)) {
1446 foreach ($customValues as $key => $val) {
1447 // per standard - return custom_fieldID
1448 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1449 $returnArray['custom_' . $id] = $val;
1451 //not standard - but some api did this so guess we should keep - cheap as chips
1452 $returnArray[$key] = $val;
1454 // Shim to restore legacy behavior of ContactReference custom fields
1455 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1456 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1457 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1464 * Used by the Validate API.
1465 * @param string $entity
1466 * @param string $action
1467 * @param array $params
1469 * @return array $errors
1471 function _civicrm_api3_validate($entity, $action, $params) {
1473 $fields = civicrm_api3($entity, 'getfields', ['sequential' => 1, 'api_action' => $action]);
1474 $fields = $fields['values'];
1476 // Check for required fields.
1477 foreach ($fields as $values) {
1478 if (!empty($values['api.required']) && empty($params[$values['name']])) {
1479 $errors[$values['name']] = [
1480 'message' => "Mandatory key(s) missing from params array: " . $values['name'],
1481 'code' => "mandatory_missing",
1486 // Select only the fields which have been input as a param.
1488 foreach ($fields as $values) {
1489 if (array_key_exists($values['name'], $params)) {
1490 $finalfields[] = $values;
1494 // This derives heavily from the function "_civicrm_api3_validate_fields".
1495 // However, the difference is that try-catch blocks are nested in the loop, making it
1496 // possible for us to get all errors in one go.
1497 foreach ($finalfields as $fieldInfo) {
1498 $fieldName = $fieldInfo['name'];
1500 _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params);
1502 catch (Exception
$e) {
1503 $errors[$fieldName] = [
1504 'message' => $e->getMessage(),
1505 'code' => 'incorrect_value',
1514 * Used by the Validate API.
1516 * @param array $fieldInfo
1517 * @param string $entity
1518 * @param array $params
1520 * @throws API_Exception
1523 function _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params) {
1524 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1525 case CRM_Utils_Type
::T_INT
:
1526 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1529 case CRM_Utils_Type
::T_DATE
:
1530 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1531 case CRM_Utils_Type
::T_TIMESTAMP
:
1532 //field is of type date or datetime
1533 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1536 case CRM_Utils_Type
::T_TEXT
:
1537 case CRM_Utils_Type
::T_STRING
:
1538 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1541 case CRM_Utils_Type
::T_MONEY
:
1542 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1544 foreach ((array) $fieldValue as $fieldvalue) {
1545 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1546 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1554 * Validate fields being passed into API.
1556 * This function relies on the getFields function working accurately
1557 * for the given API.
1559 * As of writing only date was implemented.
1561 * @param string $entity
1562 * @param string $action
1563 * @param array $params
1565 * @param array $fields
1566 * Response from getfields all variables are the same as per civicrm_api.
1570 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields) {
1571 //CRM-15792 handle datetime for custom fields below code handles chain api call
1572 $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params)));
1573 if (!empty($chainApikeys) && is_array($chainApikeys)) {
1574 foreach ($chainApikeys as $key => $value) {
1575 if (is_array($params[$key])) {
1576 $chainApiParams = array_intersect_key($fields, $params[$key]);
1577 $customFields = array_fill_keys(array_keys($params[$key]), $key);
1581 $fields = array_intersect_key($fields, $params);
1582 if (!empty($chainApiParams)) {
1583 $fields = array_merge($fields, $chainApiParams);
1585 foreach ($fields as $fieldName => $fieldInfo) {
1586 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1587 case CRM_Utils_Type
::T_INT
:
1588 //field is of type integer
1589 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1592 case CRM_Utils_Type
::T_DATE
:
1593 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1594 case CRM_Utils_Type
::T_TIMESTAMP
:
1595 //field is of type date or datetime
1596 if (!empty($customFields) && array_key_exists($fieldName, $customFields)) {
1597 $dateParams = &$params[$customFields[$fieldName]];
1600 $dateParams = &$params;
1602 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
1605 case CRM_Utils_Type
::T_TEXT
:
1606 case CRM_Utils_Type
::T_STRING
:
1607 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1610 case CRM_Utils_Type
::T_MONEY
:
1611 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1612 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1615 foreach ((array) $fieldValue as $fieldvalue) {
1616 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1617 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1626 * Validate foreign key values of fields being passed into API.
1628 * This function relies on the getFields function working accurately
1629 * for the given API.
1631 * @param string $entity
1632 * @param string $action
1633 * @param array $params
1635 * @param array $fields
1636 * Response from getfields all variables are the same as per civicrm_api.
1640 function _civicrm_api3_validate_foreign_keys($entity, $action, &$params, $fields) {
1641 // intensive checks - usually only called after DB level fail
1642 foreach ($fields as $fieldName => $fieldInfo) {
1643 if (!empty($fieldInfo['FKClassName'])) {
1644 if (!empty($params[$fieldName])) {
1645 foreach ((array) $params[$fieldName] as $fieldValue) {
1646 _civicrm_api3_validate_constraint($fieldValue, $fieldName, $fieldInfo);
1649 elseif (!empty($fieldInfo['required'])) {
1650 throw new Exception("DB Constraint Violation - $fieldName should possibly be marked as mandatory for $entity,$action API. If so, please raise a bug report.");
1653 if (!empty($fieldInfo['api.unique'])) {
1654 $params['entity'] = $entity;
1655 _civicrm_api3_validate_unique_key($params, $fieldName);
1661 * Validate date fields being passed into API.
1663 * It currently converts both unique fields and DB field names to a mysql date.
1664 * @todo - probably the unique field handling & the if exists handling is now done before this
1665 * function is reached in the wrapper - can reduce this code down to assume we
1666 * are only checking the passed in field
1668 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1669 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1671 * @param array $params
1672 * Params from civicrm_api.
1673 * @param string $fieldName
1674 * Uniquename of field being checked.
1675 * @param array $fieldInfo
1676 * Array of fields from getfields function.
1680 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1681 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1682 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1686 if ($fieldValue === 'null' && empty($fieldInfo['api.required'])) {
1687 // This is the wierd & wonderful way PEAR sets null.
1691 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1692 if (!empty($params[$fieldInfo['name']])) {
1693 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1695 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1696 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1700 $params[$fieldName][$op] = $fieldValue;
1703 $params[$fieldName] = $fieldValue;
1708 * Convert date into BAO friendly date.
1710 * We accept 'whatever strtotime accepts'
1712 * @param string $dateValue
1713 * @param string $fieldName
1719 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1720 if (is_array($dateValue)) {
1721 foreach ($dateValue as $key => $value) {
1722 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1726 if (strtotime($dateValue) === FALSE) {
1727 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1729 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1730 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1734 * Validate foreign constraint fields being passed into API.
1736 * @param mixed $fieldValue
1737 * @param string $fieldName
1738 * Uniquename of field being checked.
1739 * @param array $fieldInfo
1740 * Array of fields from getfields function.
1742 * @throws \API_Exception
1744 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1745 $daoName = $fieldInfo['FKClassName'];
1746 $dao = new $daoName();
1747 $dao->id
= $fieldValue;
1749 $dao->selectAdd('id');
1750 if (!$dao->find()) {
1751 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1756 * Validate foreign constraint fields being passed into API.
1758 * @param array $params
1759 * Params from civicrm_api.
1760 * @param string $fieldName
1761 * Uniquename of field being checked.
1765 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1766 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1767 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1770 $existing = civicrm_api($params['entity'], 'get', [
1771 'version' => $params['version'],
1772 $fieldName => $fieldValue,
1774 // an entry already exists for this unique field
1775 if ($existing['count'] == 1) {
1776 // question - could this ever be a security issue?
1777 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1782 * Generic implementation of the "replace" action.
1784 * Replace the old set of entities (matching some given keys) with a new set of
1785 * entities (matching the same keys).
1787 * @note This will verify that 'values' is present, but it does not directly verify
1788 * any other parameters.
1790 * @param string $entity
1792 * @param array $params
1793 * Params from civicrm_api, including:.
1794 * - 'values': an array of records to save
1795 * - all other items: keys which identify new/pre-existing records.
1799 function _civicrm_api3_generic_replace($entity, $params) {
1801 $transaction = new CRM_Core_Transaction();
1803 if (!is_array($params['values'])) {
1804 throw new Exception("Mandatory key(s) missing from params array: values");
1807 // Extract the keys -- somewhat scary, don't think too hard about it
1808 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1810 // Lookup pre-existing records
1811 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1812 if (civicrm_error($preexisting)) {
1813 $transaction->rollback();
1814 return $preexisting;
1817 // Save the new/updated records
1819 foreach ($params['values'] as $replacement) {
1820 // Sugar: Don't force clients to duplicate the 'key' data
1821 $replacement = array_merge($baseParams, $replacement);
1822 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1823 $create = civicrm_api($entity, $action, $replacement);
1824 if (civicrm_error($create)) {
1825 $transaction->rollback();
1828 foreach ($create['values'] as $entity_id => $entity_value) {
1829 $creates[$entity_id] = $entity_value;
1833 // Remove stale records
1834 $staleIDs = array_diff(
1835 array_keys($preexisting['values']),
1836 array_keys($creates)
1838 foreach ($staleIDs as $staleID) {
1839 $delete = civicrm_api($entity, 'delete', [
1840 'version' => $params['version'],
1843 if (civicrm_error($delete)) {
1844 $transaction->rollback();
1849 return civicrm_api3_create_success($creates, $params);
1851 catch (PEAR_Exception
$e) {
1852 $transaction->rollback();
1853 return civicrm_api3_create_error($e->getMessage());
1855 catch (Exception
$e) {
1856 $transaction->rollback();
1857 return civicrm_api3_create_error($e->getMessage());
1862 * Replace base parameters.
1864 * @param array $params
1868 function _civicrm_api3_generic_replace_base_params($params) {
1869 $baseParams = $params;
1870 unset($baseParams['values']);
1871 unset($baseParams['sequential']);
1872 unset($baseParams['options']);
1877 * Returns fields allowable by api.
1880 * String Entity to query.
1881 * @param bool $unique
1882 * Index by unique fields?.
1883 * @param array $params
1887 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = []) {
1895 $dao = _civicrm_api3_get_DAO($entity);
1900 $fields = $d->fields();
1902 foreach ($fields as $name => &$field) {
1903 // Denote as core field
1904 $field['is_core_field'] = TRUE;
1905 // Set html attributes for text fields
1906 if (isset($field['html'])) {
1907 $field['html'] +
= (array) $d::makeAttribute($field);
1911 // replace uniqueNames by the normal names as the key
1912 if (empty($unique)) {
1913 foreach ($fields as $name => &$field) {
1914 //getting rid of unused attributes
1915 foreach ($unsetIfEmpty as $attr) {
1916 if (empty($field[$attr])) {
1917 unset($field[$attr]);
1920 if ($name == $field['name']) {
1923 if (array_key_exists($field['name'], $fields)) {
1924 $field['error'] = 'name conflict';
1925 // it should never happen, but better safe than sorry
1928 $fields[$field['name']] = $field;
1929 $fields[$field['name']]['uniqueName'] = $name;
1930 unset($fields[$name]);
1933 // Translate FKClassName to the corresponding api
1934 foreach ($fields as $name => &$field) {
1935 if (!empty($field['FKClassName'])) {
1936 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1938 $field['FKApiName'] = $FKApi;
1942 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1947 * Return an array of fields for a given entity.
1949 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1952 * @param array $params
1956 function _civicrm_api_get_custom_fields($entity, &$params) {
1957 $entity = _civicrm_api_get_camel_name($entity);
1958 if ($entity == 'Contact') {
1959 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1960 $entity = CRM_Utils_Array
::value('contact_type', $params);
1962 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1965 // we could / should probably test for other subtypes here - e.g. activity_type_id
1966 CRM_Utils_Array
::value('contact_sub_type', $params),
1975 foreach ($customfields as $key => $value) {
1976 // Regular fields have a 'name' property
1977 $value['name'] = 'custom_' . $key;
1978 $value['title'] = $value['label'];
1979 if ($value['data_type'] == 'Date' && CRM_Utils_Array
::value('time_format', $value, 0) > 0) {
1980 $value['data_type'] = 'DateTime';
1982 $value['type'] = CRM_Utils_Array
::value($value['data_type'], CRM_Core_BAO_CustomField
::dataToType());
1983 $ret['custom_' . $key] = $value;
1989 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
1991 * If multiple aliases the last takes precedence
1993 * Function also swaps unique fields for non-unique fields & vice versa.
1995 * @param $apiRequest
1998 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1999 foreach ($fields as $field => $values) {
2000 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
2001 if (!empty($values['api.aliases'])) {
2002 // if aliased field is not set we try to use field alias
2003 if (!isset($apiRequest['params'][$field])) {
2004 foreach ($values['api.aliases'] as $alias) {
2005 if (isset($apiRequest['params'][$alias])) {
2006 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
2008 //unset original field nb - need to be careful with this as it may bring inconsistencies
2009 // out of the woodwork but will be implementing only as _spec function extended
2010 unset($apiRequest['params'][$alias]);
2014 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
2015 && isset($apiRequest['params'][$values['name']])
2017 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
2018 // note that it would make sense to unset the original field here but tests need to be in place first
2019 if ($field != 'domain_version') {
2020 unset($apiRequest['params'][$values['name']]);
2023 if (!isset($apiRequest['params'][$field])
2025 && $field != $uniqueName
2026 && array_key_exists($uniqueName, $apiRequest['params'])
2028 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
2029 // note that it would make sense to unset the original field here but tests need to be in place first
2036 * Validate integer fields being passed into API.
2038 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
2040 * @param array $params
2041 * Params from civicrm_api.
2042 * @param string $fieldName
2043 * Uniquename of field being checked.
2044 * @param array $fieldInfo
2045 * Array of fields from getfields function.
2046 * @param string $entity
2048 * @throws API_Exception
2050 function _civicrm_api3_validate_integer(&$params, $fieldName, &$fieldInfo, $entity) {
2051 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2052 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2056 if (!empty($fieldValue) ||
$fieldValue === '0' ||
$fieldValue === 0) {
2057 // if value = 'user_contact_id' (or similar), replace value with contact id
2058 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
2059 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
2060 if ('unknown-user' === $realContactId) {
2061 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, ['error_field' => $fieldName, "type" => "integer"]);
2063 elseif (is_numeric($realContactId)) {
2064 $fieldValue = $realContactId;
2066 elseif (is_null($realContactId) && empty($fieldInfo['api.required']) && $fieldValue === 'user_contact_id') {
2067 // If not mandatory this will be OK. If mandatory it should fail.
2071 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2072 $additional_lookup_params = [];
2073 if (strtolower($entity) == 'address' && $fieldName == 'state_province_id') {
2074 $country_id = _civicrm_api3_resolve_country_id($params);
2075 if (!empty($country_id)) {
2076 $additional_lookup_params = ['country_id' => $country_id];
2079 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op, $additional_lookup_params);
2082 // After swapping options, ensure we have an integer(s)
2083 foreach ((array) ($fieldValue) as $value) {
2084 if ($value && !is_numeric($value) && $value !== 'null' && $value !== NULL && !is_array($value)) {
2085 throw new API_Exception("$fieldName is not a valid integer", 2001, ['error_field' => $fieldName, "type" => "integer"]);
2089 // Check our field length
2090 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
2092 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
2093 2100, ['field' => $fieldName, "max_length" => $fieldInfo['maxlength']]
2099 $params[$fieldName][$op] = $fieldValue;
2102 $params[$fieldName] = $fieldValue;
2107 * Helper function to determine country_id given the myriad of values for country_id or country that are supported
2112 function _civicrm_api3_resolve_country_id($params) {
2113 if (!empty($params['country_id'])) {
2114 if (is_numeric($params['country_id'])) {
2115 $country_id = $params['country_id'];
2118 $country = new CRM_Core_DAO_Country();
2119 $country->name
= $params['country_id'];
2120 if (!$country->find(TRUE)) {
2121 $country->name
= NULL;
2122 $country->iso_code
= $params['country_id'];
2123 $country->find(TRUE);
2125 if (!empty($country->id
)) {
2126 $country_id = $country->id
;
2130 elseif (!empty($params['country'])) {
2131 if (is_numeric($params['country'])) {
2132 $country_id = $params['country'];
2135 $country = new CRM_Core_DAO_Country();
2136 $country->name
= $params['country'];
2137 if (!$country->find(TRUE)) {
2138 $country->name
= NULL;
2139 $country->iso_code
= $params['country'];
2140 $country->find(TRUE);
2142 if (!empty($country->id
)) {
2143 $country_id = $country->id
;
2147 return !empty($country_id) ?
$country_id : NULL;
2151 * Determine a contact ID using a string expression.
2153 * @param string $contactIdExpr
2154 * E.g. "user_contact_id" or "@user:username".
2156 * @return int|null|'unknown-user'
2157 * @throws \CRM_Core_Exception
2159 function _civicrm_api3_resolve_contactID($contactIdExpr) {
2160 // If value = 'user_contact_id' replace value with logged in user id.
2161 if ($contactIdExpr == "user_contact_id") {
2162 return CRM_Core_Session
::getLoggedInContactID();
2164 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
2165 $config = CRM_Core_Config
::singleton();
2167 $ufID = $config->userSystem
->getUfId($matches[1]);
2169 return 'unknown-user';
2172 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
2174 return 'unknown-user';
2183 * Validate html (check for scripting attack).
2185 * @param array $params
2186 * @param string $fieldName
2187 * @param array $fieldInfo
2189 * @throws API_Exception
2191 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
2192 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2193 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
2197 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2198 throw new API_Exception('Input contains illegal SCRIPT tag.', ["field" => $fieldName, "error_code" => "xss"]);
2204 * Validate string fields being passed into API.
2206 * @param array $params
2207 * Params from civicrm_api.
2208 * @param string $fieldName
2209 * Uniquename of field being checked.
2210 * @param array $fieldInfo
2211 * Array of fields from getfields function.
2212 * @param string $entity
2214 * @throws API_Exception
2217 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2218 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName, 'String');
2219 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
2223 if (!is_array($fieldValue)) {
2224 $fieldValue = (string) $fieldValue;
2228 foreach ((array) $fieldValue as $key => $value) {
2229 foreach ([$fieldValue, $key, $value] as $input) {
2230 if (!CRM_Utils_Rule
::xssString($input)) {
2231 throw new Exception('Input contains illegal SCRIPT tag.');
2234 if ($fieldName == 'currency') {
2235 //When using IN operator $fieldValue is a array of currency codes
2236 if (!CRM_Utils_Rule
::currencyCode($value)) {
2237 throw new Exception("Currency not a valid code: $currency");
2242 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2243 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op);
2245 // Check our field length
2246 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2247 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2248 2100, ['field' => $fieldName]
2253 $params[$fieldName][$op] = $fieldValue;
2256 $params[$fieldName] = $fieldValue;
2261 * Validate & swap out any pseudoconstants / options.
2263 * @param mixed $fieldValue
2264 * @param string $entity : api entity name
2265 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2266 * @param array $fieldInfo : getfields meta-data
2268 * @param array $additional_lookup_params
2270 * @throws \API_Exception
2272 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo, $op = '=', $additional_lookup_params = []) {
2273 if (in_array($op, ['>', '<', '>=', '<=', 'LIKE', 'NOT LIKE'])) {
2277 $options = CRM_Utils_Array
::value('options', $fieldInfo);
2280 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2281 // We need to get the options from the entity the field relates to.
2282 $entity = $fieldInfo['entity'];
2284 $options_lookup_params = [
2286 'field' => $fieldInfo['name'],
2287 'context' => 'validate',
2289 if (!empty($additional_lookup_params)) {
2290 $options_lookup_params = array_merge($additional_lookup_params, $options_lookup_params);
2292 $options = civicrm_api($entity, 'getoptions', $options_lookup_params);
2294 $options = CRM_Utils_Array
::value('values', $options, []);
2297 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2299 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2300 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
2303 // If passed multiple options, validate each.
2304 if (is_array($fieldValue)) {
2305 foreach ($fieldValue as &$value) {
2306 if (!is_array($value)) {
2307 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName, CRM_Utils_Array
::value('api.required', $fieldInfo));
2310 // TODO: unwrap the call to implodePadded from the conditional and do it always
2311 // need to verify that this is safe and doesn't break anything though.
2312 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2314 CRM_Utils_Array
::implodePadded($fieldValue);
2318 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName, CRM_Utils_Array
::value('api.required', $fieldInfo));
2323 * Validate & swap a single option value for a field.
2325 * @param string $value field value
2326 * @param array $options array of options for this field
2327 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2328 * @param bool $isRequired
2329 * Is this a required field or is 'null' an acceptable option. We allow 'null' last
2330 * in case we have the weird situation of it being a valid option in which case our
2331 * brains will probably explode.
2333 * @throws API_Exception
2335 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName, $isRequired) {
2336 // If option is a key, no need to translate
2337 // or if no options are avaiable for pseudoconstant 'table' property
2338 if (array_key_exists($value, $options) ||
!$options) {
2342 // Hack for Profile formatting fields
2343 if ($fieldName === 'field_name' && (strpos($value, 'formatting') === 0)) {
2347 // Translate value into key
2348 // Cast $value to string to avoid a bug in array_search
2349 $newValue = array_search((string) $value, $options);
2350 if ($newValue !== FALSE) {
2354 // Case-insensitive matching
2355 $newValue = strtolower($value);
2356 $options = array_map("strtolower", $options);
2357 $newValue = array_search($newValue, $options);
2358 if ($newValue === FALSE) {
2359 if ($value === 'null' && !$isRequired) {
2360 // CiviMagic syntax for Nulling out the field - let it through.
2363 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, ['error_field' => $fieldName]);
2369 * Returns the canonical name of a field.
2372 * api entity name (string should already be standardized - no camelCase).
2374 * any variation of a field's name (name, unique_name, api.alias).
2376 * @param string $action
2378 * @return bool|string
2379 * FieldName or FALSE if the field does not exist
2381 function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') {
2385 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2388 if ($fieldName == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
2391 $result = civicrm_api($entity, 'getfields', [
2393 'action' => $action,
2395 $meta = $result['values'];
2396 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2397 $fieldName = $fieldName . '_id';
2399 if (isset($meta[$fieldName])) {
2400 return $meta[$fieldName]['name'];
2402 foreach ($meta as $info) {
2403 if ($fieldName == $info['name'] ||
$fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2404 return $info['name'];
2406 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, [])) !== FALSE) {
2407 return $info['name'];
2410 // Create didn't work, try with get
2411 if ($action == 'create') {
2412 return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get');
2418 * Check if the function is deprecated.
2420 * @param string $entity
2421 * @param array $result
2423 * @return string|array|null
2425 function _civicrm_api3_deprecation_check($entity, $result = []) {
2427 $apiFile = "api/v3/$entity.php";
2428 if (CRM_Utils_File
::isIncludable($apiFile)) {
2429 require_once $apiFile;
2431 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
2432 $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation";
2433 if (function_exists($fnName)) {
2434 return $fnName($result);
2440 * Get the actual field value.
2442 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2443 * So this function returns the actual field value.
2445 * @param array $params
2446 * @param string $fieldName
2447 * @param string $type
2451 function _civicrm_api3_field_value_check(&$params, $fieldName, $type = NULL) {
2452 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2455 if (!empty($fieldValue) && is_array($fieldValue) &&
2456 (array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators()) ||
2457 $type == 'String' && strstr(key($fieldValue), 'EMPTY'))
2459 $op = key($fieldValue);
2460 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2462 return [$fieldValue, $op];
2466 * A generic "get" API based on simple array data. This is comparable to
2467 * _civicrm_api3_basic_get but does not use DAO/BAO. This is useful for
2468 * small/mid-size data loaded from external JSON or XML documents.
2471 * @param array $params
2473 * @param array $records
2474 * List of all records.
2475 * @param string $idCol
2476 * The property which defines the ID of a record
2477 * @param array $filterableFields
2478 * List of filterable fields.
2481 * @throws \API_Exception
2483 function _civicrm_api3_basic_array_get($entity, $params, $records, $idCol, $filterableFields) {
2484 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
2485 // TODO // $sort = CRM_Utils_Array::value('sort', $options, NULL);
2486 $offset = CRM_Utils_Array
::value('offset', $options);
2487 $limit = CRM_Utils_Array
::value('limit', $options);
2492 foreach ($records as $record) {
2493 if ($idCol != 'id') {
2494 $record['id'] = $record[$idCol];
2497 foreach ($params as $k => $v) {
2501 if (in_array($k, $filterableFields) && $record[$k] != $v) {
2507 if ($currentOffset >= $offset) {
2508 $matches[$record[$idCol]] = $record;
2510 if ($limit && count($matches) >= $limit) {
2517 $return = CRM_Utils_Array
::value('return', $options, []);
2518 if (!empty($return)) {
2520 $matches = CRM_Utils_Array
::filterColumns($matches, array_keys($return));
2523 return civicrm_api3_create_success($matches, $params);
2527 * @param string $bao_name
2528 * @param array $params
2529 * @throws \Civi\API\Exception\UnauthorizedException
2531 function _civicrm_api3_check_edit_permissions($bao_name, $params) {
2532 // For lack of something more clever, here's a whitelist of entities whos permissions
2533 // are inherited from a contact record.
2534 // Note, when adding here, also remember to modify _civicrm_api3_permissions()
2535 $contactEntities = [
2536 'CRM_Core_BAO_Email',
2537 'CRM_Core_BAO_Phone',
2538 'CRM_Core_BAO_Address',
2540 'CRM_Core_BAO_Website',
2541 'CRM_Core_BAO_OpenID',
2543 if (!empty($params['check_permissions']) && in_array($bao_name, $contactEntities)) {
2544 $cid = !empty($params['contact_id']) ?
$params['contact_id'] : CRM_Core_DAO
::getFieldValue($bao_name, $params['id'], 'contact_id');
2545 if (!CRM_Contact_BAO_Contact_Permission
::allow($cid, CRM_Core_Permission
::EDIT
)) {
2546 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify contact record');
2552 * Check if an entity has been modified since the last known modified_date
2553 * @param string $modifiedDate Last knowm modified_date
2554 * @param int $id Id of record to check
2555 * @param string $entity API Entity
2558 function _civicrm_api3_compare_timestamps($modifiedDate, $id, $entity) {
2559 $currentDbInfo = civicrm_api3($entity, 'getsingle', ['id' => $id]);
2560 if (strtotime($currentDbInfo['modified_date']) <= strtotime($modifiedDate)) {