3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
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['contribution_cancel_date'])) {
177 // 5.16 legacy handling.
178 $values[$key]['cancel_date'] = $item['contribution_cancel_date'];
180 if (!empty($item['next_sched_contribution_date'])) {
181 // 4.4 legacy handling
182 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
187 if (is_array($params) && !empty($params['debug'])) {
188 if (is_string($action) && $action != 'getfields') {
189 $apiFields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => $action] +
$params);
191 elseif ($action != 'getfields') {
192 $apiFields = civicrm_api($entity, 'getfields', ['version' => 3] +
$params);
199 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
200 $allFields = array_keys($apiFields['values']);
202 $paramFields = array_keys($params);
203 $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), [
222 $result['undefined_fields'] = array_merge($undefined);
226 $result['version'] = 3;
227 if (is_array($values)) {
228 $result['count'] = (int) count($values);
230 // Convert value-separated strings to array
231 if ($action != 'getfields') {
232 _civicrm_api3_separate_values($values);
235 if ($result['count'] == 1) {
236 list($result['id']) = array_keys($values);
238 elseif (!empty($values['id']) && is_int($values['id'])) {
239 $result['id'] = $values['id'];
243 $result['count'] = !empty($values) ?
1 : 0;
246 if (is_array($values) && isset($params['sequential']) &&
247 $params['sequential'] == 1
249 $result['values'] = array_values($values);
252 $result['values'] = $values;
254 if (!empty($params['options']['metadata'])) {
255 // We've made metadata an array but only supporting 'fields' atm.
256 if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
257 $fields = civicrm_api3($entity, 'getfields', [
258 'action' => substr($action, 0, 3) == 'get' ?
'get' : 'create',
260 $result['metadata']['fields'] = $fields['values'];
263 // Report deprecations.
264 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
265 // Always report "setvalue" action as deprecated.
266 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'setvalue')) {
267 $deprecated = ((array) $deprecated) +
['setvalue' => 'The "setvalue" action is deprecated. Use "create" with an id instead.'];
269 // Always report "update" action as deprecated.
270 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'update')) {
271 $deprecated = ((array) $deprecated) +
['update' => 'The "update" action is deprecated. Use "create" with an id instead.'];
274 // Metadata-level deprecations or wholesale entity deprecations.
275 if ($entity == 'Entity' ||
$action == 'getactions' ||
is_string($deprecated)) {
276 $result['deprecated'] = $deprecated;
278 // Action-specific deprecations
279 elseif (!empty($deprecated[$action])) {
280 $result['deprecated'] = $deprecated[$action];
283 return array_merge($result, $extraReturnValues);
287 * Load the DAO of the entity.
293 function _civicrm_api3_load_DAO($entity) {
294 $dao = _civicrm_api3_get_DAO($entity);
303 * Return the DAO of the function or Entity.
305 * @param string $name
306 * Either a function of the api (civicrm_{entity}_create or the entity name.
307 * return the DAO name to manipulate this function
308 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
310 * @return mixed|string
312 function _civicrm_api3_get_DAO($name) {
313 if (strpos($name, 'civicrm_api3') !== FALSE) {
314 $last = strrpos($name, '_');
315 // len ('civicrm_api3_') == 13
316 $name = substr($name, 13, $last - 13);
319 $name = _civicrm_api_get_camel_name($name);
321 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
325 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
327 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
328 if ($name == 'MailingEventQueue') {
329 return 'CRM_Mailing_Event_DAO_Queue';
331 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
332 // but am not confident mailing_recipients is tested so have not tackled.
333 if ($name == 'MailingRecipients') {
334 return 'CRM_Mailing_DAO_Recipients';
336 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
337 if ($name == 'AclRole') {
338 return 'CRM_ACL_DAO_EntityRole';
340 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
341 // But this would impact SMS extensions so need to coordinate
342 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
343 if ($name == 'SmsProvider') {
344 return 'CRM_SMS_DAO_Provider';
346 // FIXME: DAO names should follow CamelCase convention
347 if ($name == 'Im' ||
$name == 'Acl' ||
$name == 'Pcp') {
348 $name = strtoupper($name);
350 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
351 if ($dao ||
!$name) {
355 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
356 if (file_exists("api/v3/$name.php")) {
357 include_once "api/v3/$name.php";
360 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
361 if (function_exists($daoFn)) {
369 * Return the BAO name of the function or Entity.
371 * @param string $name
372 * Is either a function of the api (civicrm_{entity}_create or the entity name.
373 * return the DAO name to manipulate this function
374 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
376 * @return string|null
378 function _civicrm_api3_get_BAO($name) {
379 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
380 if ($name == 'PrintLabel') {
381 return 'CRM_Badge_BAO_Layout';
383 if ($name === 'Order') {
384 // Order basically maps to contribution at the top level but
385 // has enhanced access to other entities.
386 $name = 'Contribution';
388 if ($name === 'Dedupe') {
389 // Dedupe is a pseudoentity for PrevNextCache - but accessing dedupe related info
390 // not the other cache info like search results (which could in fact be in Redis or another cache engine)
391 $name = 'PrevNextCache';
393 if ($name === 'Payment') {
394 $name = 'FinancialTrxn';
396 $dao = _civicrm_api3_get_DAO($name);
400 $bao = str_replace("DAO", "BAO", $dao);
401 $file = strtr($bao, '_', '/') . '.php';
402 // Check if this entity actually has a BAO. Fall back on the DAO if not.
403 return stream_resolve_include_path($file) ?
$bao : $dao;
407 * Recursive function to explode value-separated strings into arrays.
411 function _civicrm_api3_separate_values(&$values) {
412 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
413 foreach ($values as $key => & $value) {
414 if (is_array($value)) {
415 _civicrm_api3_separate_values($value);
417 elseif (is_string($value)) {
418 // This is to honor the way case API was originally written.
419 if ($key == 'case_type_id') {
420 $value = trim(str_replace($sp, ',', $value), ',');
422 elseif (strpos($value, $sp) !== FALSE) {
423 $value = explode($sp, trim($value, $sp));
430 * This is a legacy wrapper for api_store_values.
432 * It checks suitable fields using getfields rather than DAO->fields.
434 * Getfields has handling for how to deal with unique names which dao->fields doesn't
436 * Note this is used by BAO type create functions - eg. contribution
438 * @param string $entity
439 * @param array $params
440 * @param array $values
442 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
443 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'create']);
444 $fields = $fields['values'];
445 _civicrm_api3_store_values($fields, $params, $values);
451 * @param array $fields
452 * @param array $params
453 * @param array $values
457 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
460 $keys = array_intersect_key($params, $fields);
461 foreach ($keys as $name => $value) {
462 if ($name !== 'id') {
463 $values[$name] = $value;
471 * Returns field names of the given entity fields.
473 * @param array $fields
474 * Fields array to retrieve the field names for.
477 function _civicrm_api3_field_names($fields) {
479 foreach ($fields as $key => $value) {
480 if (!empty($value['name'])) {
481 $result[] = $value['name'];
488 * Get function for query object api.
490 * The API supports 2 types of get request. The more complex uses the BAO query object.
491 * This is a generic function for those functions that call it
493 * At the moment only called by contact we should extend to contribution &
494 * others that use the query object. Note that this function passes permission information in.
497 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
501 * @param array $params
502 * As passed into api get or getcount function.
503 * @param array $additional_options
504 * Array of options (so we can modify the filter).
505 * @param bool $getCount
506 * Are we just after the count.
508 * This basically correlates to the component.
509 * @param null|array $defaultReturnProperties
510 * Default return properties for the entity
511 * (used if return not set - but don't do that - set return!).
514 * @throws API_Exception
516 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = [], $getCount = NULL, $mode = 1, $defaultReturnProperties = NULL) {
517 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
518 // Convert id to e.g. contact_id
519 if (empty($params[$lowercase_entity . '_id']) && isset($params['id'])) {
520 $params[$lowercase_entity . '_id'] = $params['id'];
522 unset($params['id']);
524 $options = _civicrm_api3_get_options_from_params($params, TRUE);
526 $inputParams = array_merge(
527 CRM_Utils_Array
::value('input_params', $options, []),
528 CRM_Utils_Array
::value('input_params', $additional_options, [])
530 $returnProperties = array_merge(
531 CRM_Utils_Array
::value('return', $options, []),
532 CRM_Utils_Array
::value('return', $additional_options, [])
534 if (empty($returnProperties)) {
535 $returnProperties = $defaultReturnProperties;
537 if (!empty($params['check_permissions'])) {
538 // we will filter query object against getfields
539 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'get']);
540 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
541 $fields['values'][$lowercase_entity . '_id'] = [];
542 $varsToFilter = ['returnProperties', 'inputParams'];
543 foreach ($varsToFilter as $varToFilter) {
544 if (!is_array($
$varToFilter)) {
547 //I was going to throw an exception rather than silently filter out - but
548 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
549 //so we are silently ignoring parts of their request
550 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
551 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
554 $options = array_merge($options, $additional_options);
555 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
556 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
557 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
558 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
562 $returnProperties = NULL;
565 if (substr($sort, 0, 2) == 'id') {
566 $sort = $lowercase_entity . "_" . $sort;
569 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
571 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
573 list($entities) = CRM_Contact_BAO_Query
::apiQuery(
592 * Get dao query object based on input params.
594 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
597 * @param array $params
598 * @param string $mode
599 * @param string $entity
602 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
604 function _civicrm_api3_get_query_object($params, $mode, $entity) {
605 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
606 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
607 $offset = CRM_Utils_Array
::value('offset', $options);
608 $rowCount = CRM_Utils_Array
::value('limit', $options);
609 $inputParams = CRM_Utils_Array
::value('input_params', $options, []);
610 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
611 if (empty($returnProperties)) {
612 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
615 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
616 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
618 empty($params['check_permissions']),
619 TRUE, TRUE, NULL, 'AND', 'NULL', TRUE
621 list($select, $from, $where, $having) = $query->query();
623 $sql = "$select $from $where $having";
626 $sort = CRM_Utils_Type
::escape($sort, 'MysqlOrderBy');
627 $sql .= " ORDER BY $sort ";
629 if (!empty($rowCount)) {
630 $sql .= " LIMIT $offset, $rowCount ";
632 $dao = CRM_Core_DAO
::executeQuery($sql);
633 return [$dao, $query];
637 * Function transfers the filters being passed into the DAO onto the params object.
639 * @deprecated DAO based retrieval is being phased out.
641 * @param CRM_Core_DAO $dao
642 * @param array $params
643 * @param bool $unique
644 * @param array $extraSql
645 * API specific queries eg for event isCurrent would be converted to
646 * $extraSql['where'] = array('civicrm_event' => array('(start_date >= CURDATE() || end_date >= CURDATE())'));
648 * @throws API_Exception
651 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $extraSql = []) {
652 $entity = _civicrm_api_get_entity_name_from_dao($dao);
653 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
654 if (!empty($params[$lowercase_entity . "_id"]) && empty($params['id'])) {
655 //if entity_id is set then treat it as ID (will be overridden by id if set)
656 $params['id'] = $params[$lowercase_entity . "_id"];
658 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
659 $fields = array_intersect(array_keys($allfields), array_keys($params));
661 $options = _civicrm_api3_get_options_from_params($params);
662 //apply options like sort
663 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
665 //accept filters like filter.activity_date_time_high
666 // std is now 'filters' => ..
667 if (strstr(implode(',', array_keys($params)), 'filter')) {
668 if (isset($params['filters']) && is_array($params['filters'])) {
669 foreach ($params['filters'] as $paramkey => $paramvalue) {
670 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
674 foreach ($params as $paramkey => $paramvalue) {
675 if (strstr($paramkey, 'filter')) {
676 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
685 foreach ($fields as $field) {
686 if (is_array($params[$field])) {
687 //get the actual fieldname from db
688 $fieldName = $allfields[$field]['name'];
689 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
690 if (!empty($where)) {
691 $dao->whereAdd($where);
696 $daoFieldName = $allfields[$field]['name'];
697 if (empty($daoFieldName)) {
698 throw new API_Exception("Failed to determine field name for \"$field\"");
700 $dao->{$daoFieldName} = $params[$field];
703 $dao->$field = $params[$field];
707 if (!empty($extraSql['where'])) {
708 foreach ($extraSql['where'] as $table => $sqlWhere) {
709 foreach ($sqlWhere as $where) {
710 $dao->whereAdd($where);
714 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
716 // Ensure 'id' is included.
717 $options['return']['id'] = TRUE;
718 $allfields = _civicrm_api3_get_unique_name_array($dao);
719 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
720 foreach ($returnMatched as $returnValue) {
721 $dao->selectAdd($returnValue);
724 // Not already matched on the field names.
725 $unmatchedFields = array_diff(
726 array_keys($options['return']),
730 $returnUniqueMatched = array_intersect(
732 // But a match for the field keys.
733 array_flip($allfields)
735 foreach ($returnUniqueMatched as $uniqueVal) {
736 $dao->selectAdd($allfields[$uniqueVal]);
739 $dao->setApiFilter($params);
743 * Apply filters (e.g. high, low) to DAO object (prior to find).
745 * @param string $filterField
746 * Field name of filter.
747 * @param string $filterValue
748 * Field value of filter.
752 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
753 if (strstr($filterField, 'high')) {
754 $fieldName = substr($filterField, 0, -5);
755 $dao->whereAdd("($fieldName <= $filterValue )");
757 if (strstr($filterField, 'low')) {
758 $fieldName = substr($filterField, 0, -4);
759 $dao->whereAdd("($fieldName >= $filterValue )");
761 if ($filterField == 'is_current' && $filterValue == 1) {
762 $todayStart = date('Ymd000000', strtotime('now'));
763 $todayEnd = date('Ymd235959', strtotime('now'));
764 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
765 if (property_exists($dao, 'is_active')) {
766 $dao->whereAdd('is_active = 1');
772 * Get sort, limit etc options from the params - supporting old & new formats.
774 * Get returnProperties for legacy
776 * @param array $params
777 * Params array as passed into civicrm_api.
778 * @param bool $queryObject
779 * Is this supporting a queryObject api (e.g contact) - if so we support more options.
780 * for legacy report & return a unique fields array
782 * @param string $entity
783 * @param string $action
785 * @throws API_Exception
787 * options extracted from params
789 function _civicrm_api3_get_options_from_params($params, $queryObject = FALSE, $entity = '', $action = '') {
790 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
792 $sort = CRM_Utils_Array
::value('sort', $params, 0);
793 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
794 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
796 $offset = CRM_Utils_Array
::value('offset', $params, 0);
797 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
798 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
799 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
801 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
802 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
803 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
805 if (is_array(CRM_Utils_Array
::value('options', $params))) {
806 // is count is set by generic getcount not user
807 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
808 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
809 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
810 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
813 $returnProperties = [];
814 // handle the format return =sort_name,display_name...
815 if (array_key_exists('return', $params)) {
816 if (is_array($params['return'])) {
817 $returnProperties = array_fill_keys($params['return'], 1);
820 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
821 $returnProperties = array_fill_keys($returnProperties, 1);
824 if ($entity && $action == 'get') {
825 if (!empty($returnProperties['id'])) {
826 $returnProperties[$lowercase_entity . '_id'] = 1;
827 unset($returnProperties['id']);
832 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
833 'limit' => (!$is_count && CRM_Utils_Rule
::integer($limit)) ?
$limit : NULL,
834 'is_count' => $is_count,
835 'return' => !empty($returnProperties) ?
$returnProperties : [],
839 $options['sort'] = NULL;
841 if (!is_array($sort)) {
842 $sort = array_map('trim', explode(',', $sort));
844 foreach ($sort as $s) {
845 if ($s == '(1)' || CRM_Utils_Rule
::mysqlOrderBy($s)) {
846 if ($entity && $action == 'get') {
847 switch (trim(strtolower($s))) {
851 $s = str_replace('id', $lowercase_entity . '_id', $s);
857 throw new API_Exception("Unknown field specified for sort. Cannot order by '$s'");
860 $options['sort'] = implode(', ', $finalSort);
863 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
864 throw new API_Exception('invalid string in sort options');
870 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
871 // if the query object is being used this should be used
873 $legacyreturnProperties = [];
875 'sort', 'offset', 'rowCount', 'options', 'return',
876 'version', 'prettyprint', 'check_permissions', 'sequential',
878 foreach ($params as $n => $v) {
879 if (substr($n, 0, 7) == 'return.') {
880 $legacyreturnProperties[substr($n, 7)] = $v;
882 elseif ($n == 'id') {
883 $inputParams[$lowercase_entity . '_id'] = $v;
885 elseif (in_array($n, $otherVars)) {
888 $inputParams[$n] = $v;
889 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
890 throw new API_Exception('invalid string');
894 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
895 $options['input_params'] = $inputParams;
900 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
902 * @param array $params
903 * Params array as passed into civicrm_api.
908 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
910 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
911 if (!$options['is_count']) {
912 if (!empty($options['limit'])) {
913 $dao->limit((int) $options['offset'], (int) $options['limit']);
915 if (!empty($options['sort'])) {
916 $options['sort'] = CRM_Utils_Type
::escape($options['sort'], 'MysqlOrderBy');
917 $dao->orderBy($options['sort']);
923 * Build fields array.
925 * This is the array of fields as it relates to the given DAO
926 * returns unique fields as keys by default but if set but can return by DB fields
928 * @param CRM_Core_DAO $bao
929 * @param bool $unique
933 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
934 $fields = $bao->fields();
936 if (empty($fields['id'])) {
937 $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
938 if (isset($fields[$lowercase_entity . '_id'])) {
939 $fields['id'] = $fields[$lowercase_entity . '_id'];
940 unset($fields[$lowercase_entity . '_id']);
946 foreach ($fields as $field) {
947 $dbFields[$field['name']] = $field;
953 * Build fields array.
955 * This is the array of fields as it relates to the given DAO
956 * returns unique fields as keys by default but if set but can return by DB fields
958 * @param CRM_Core_DAO $bao
962 function _civicrm_api3_get_unique_name_array(&$bao) {
963 $fields = $bao->fields();
964 foreach ($fields as $field => $values) {
965 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
967 return $uniqueFields;
971 * Converts an DAO object to an array.
973 * @deprecated - DAO based retrieval is being phased out.
975 * @param CRM_Core_DAO $dao
977 * @param array $params
978 * @param bool $uniqueFields
979 * @param string $entity
980 * @param bool $autoFind
984 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
986 if (isset($params['options']) && !empty($params['options']['is_count'])) {
987 return $dao->count();
992 if ($autoFind && !$dao->find()) {
996 if (isset($dao->count
)) {
1000 $fields = array_keys(_civicrm_api3_build_fields_array($dao, FALSE));
1001 while ($dao->fetch()) {
1003 foreach ($fields as $key) {
1004 if (array_key_exists($key, $dao)) {
1005 // not sure on that one
1006 if ($dao->$key !== NULL) {
1007 $tmp[$key] = $dao->$key;
1011 $result[$dao->id
] = $tmp;
1013 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
1014 _civicrm_api3_custom_data_get($result[$dao->id
], $params['check_permissions'], $entity, $dao->id
);
1022 * Determine if custom fields need to be retrieved.
1024 * We currently retrieve all custom fields or none at this level so if we know the entity
1025 * && 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
1026 * @todo filter so only required fields are queried
1028 * @param string $entity
1029 * Entity name in CamelCase.
1030 * @param array $params
1034 function _civicrm_api3_custom_fields_are_required($entity, $params) {
1035 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
1038 $options = _civicrm_api3_get_options_from_params($params);
1039 // We check for possibility of 'custom' => 1 as well as specific custom fields.
1040 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
1041 if (stristr($returnString, 'custom')) {
1047 * Converts an object to an array.
1049 * @param object $dao
1050 * (reference) object to convert.
1051 * @param array $values
1052 * (reference) array.
1053 * @param array|bool $uniqueFields
1055 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
1057 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
1058 foreach ($fields as $key => $value) {
1059 if (array_key_exists($key, $dao)) {
1060 $values[$key] = $dao->$key;
1066 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1073 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1074 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1078 * Format custom parameters.
1080 * @param array $params
1081 * @param array $values
1082 * @param string $extends
1083 * Entity that this custom field extends (e.g. contribution, event, contact).
1084 * @param string $entityId
1085 * ID of entity per $extends.
1087 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1088 $values['custom'] = [];
1089 $checkCheckBoxField = FALSE;
1091 if (in_array($extends, ['Household', 'Individual', 'Organization'])) {
1092 $entity = 'Contact';
1095 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'create']);
1096 if (!$fields['is_error']) {
1097 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1098 $fields = $fields['values'];
1099 $checkCheckBoxField = TRUE;
1102 foreach ($params as $key => $value) {
1103 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
1104 if ($customFieldID && (!is_null($value))) {
1105 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1106 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1109 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1110 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1117 * Format parameters for create action.
1119 * @param array $params
1122 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1123 $nonGenericEntities = ['Contact', 'Individual', 'Household', 'Organization'];
1125 $customFieldEntities = array_diff_key(CRM_Core_SelectValues
::customGroupExtends(), array_fill_keys($nonGenericEntities, 1));
1126 if (!array_key_exists($entity, $customFieldEntities)) {
1130 _civicrm_api3_custom_format_params($params, $values, $entity);
1131 $params = array_merge($params, $values);
1135 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1137 * We should look at pushing to BAO function
1138 * 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
1139 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1141 * 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
1142 * don't touch - lots of very cautious code in here
1144 * The resulting array should look like
1150 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1152 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1153 * be fixed in future
1155 * @param mixed $checkboxFieldValue
1156 * @param string $customFieldLabel
1157 * @param string $entity
1159 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1161 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1162 // We can assume it's pre-formatted.
1165 $options = civicrm_api($entity, 'getoptions', ['field' => $customFieldLabel, 'version' => 3]);
1166 if (!empty($options['is_error'])) {
1167 // The check is precautionary - can probably be removed later.
1171 $options = $options['values'];
1173 if (is_array($checkboxFieldValue)) {
1174 foreach ($checkboxFieldValue as $key => $value) {
1175 if (!array_key_exists($key, $options)) {
1176 $validValue = FALSE;
1180 // we have been passed an array that is already in the 'odd' custom field format
1185 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1186 // if the array only has one item we'll treat it like any other string
1187 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1188 $possibleValue = reset($checkboxFieldValue);
1190 if (is_string($checkboxFieldValue)) {
1191 $possibleValue = $checkboxFieldValue;
1193 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1194 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1197 elseif (is_array($checkboxFieldValue)) {
1198 // so this time around we are considering the values in the array
1199 $possibleValues = $checkboxFieldValue;
1200 $formatValue = TRUE;
1202 elseif (stristr($checkboxFieldValue, ',')) {
1203 $formatValue = TRUE;
1204 //lets see if we should separate it - we do this near the end so we
1205 // ensure we have already checked that the comma is not part of a legitimate match
1206 // and of course, we don't make any changes if we don't now have matches
1207 $possibleValues = explode(',', $checkboxFieldValue);
1210 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1214 foreach ($possibleValues as $index => $possibleValue) {
1215 if (array_key_exists($possibleValue, $options)) {
1216 // 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)
1218 elseif (array_key_exists(trim($possibleValue), $options)) {
1219 $possibleValues[$index] = trim($possibleValue);
1222 $formatValue = FALSE;
1226 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1231 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1233 * @param string $bao_name
1235 * @param array $params
1237 * @param bool $returnAsSuccess
1238 * Return in api success format.
1239 * @param string $entity
1240 * @param CRM_Utils_SQL_Select|NULL $sql
1241 * Extra SQL bits to add to the query. For filtering current events, this might be:
1242 * CRM_Utils_SQL_Select::fragment()->where('(start_date >= CURDATE() || end_date >= CURDATE())');
1243 * @param bool $uniqueFields
1244 * Should unique field names be returned (for backward compatibility)
1248 function _civicrm_api3_basic_get($bao_name, $params, $returnAsSuccess = TRUE, $entity = "", $sql = NULL, $uniqueFields = FALSE) {
1249 $entity = $entity ?
: CRM_Core_DAO_AllCoreTables
::getBriefName(str_replace('_BAO_', '_DAO_', $bao_name));
1250 $options = _civicrm_api3_get_options_from_params($params);
1252 $query = new \Civi\API\
Api3SelectQuery($entity, CRM_Utils_Array
::value('check_permissions', $params, FALSE));
1253 $query->where
= $params;
1254 if ($options['is_count']) {
1255 $query->select
= ['count_rows'];
1258 $query->select
= array_keys(array_filter($options['return']));
1259 $query->orderBy
= $options['sort'];
1260 $query->isFillUniqueFields
= $uniqueFields;
1262 $query->limit
= $options['limit'];
1263 $query->offset
= $options['offset'];
1264 $query->merge($sql);
1265 $result = $query->run();
1267 if ($returnAsSuccess) {
1268 return civicrm_api3_create_success($result, $params, $entity, 'get');
1274 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1276 * @param string $bao_name
1277 * Name of BAO Class.
1278 * @param array $params
1279 * Parameters passed into the api call.
1280 * @param string $entity
1281 * Entity - pass in if entity is non-standard & required $ids array.
1283 * @throws API_Exception
1284 * @throws \Civi\API\Exception\UnauthorizedException
1287 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1288 _civicrm_api3_check_edit_permissions($bao_name, $params);
1289 _civicrm_api3_format_params_for_create($params, $entity);
1290 $args = array(&$params);
1292 $ids = [$entity => CRM_Utils_Array
::value('id', $params)];
1296 if (method_exists($bao_name, 'create')) {
1298 $fct_name = $bao_name . '::' . $fct;
1299 $bao = call_user_func_array([$bao_name, $fct], $args);
1301 elseif (method_exists($bao_name, 'add')) {
1303 $fct_name = $bao_name . '::' . $fct;
1304 $bao = call_user_func_array([$bao_name, $fct], $args);
1307 $fct_name = '_civicrm_api3_basic_create_fallback';
1308 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1311 if (is_null($bao)) {
1312 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1314 elseif (is_a($bao, 'CRM_Core_Error')) {
1315 //some weird circular thing means the error takes itself as an argument
1316 $msg = $bao->getMessages($bao);
1317 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1318 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1319 // so we need to reset the error object here to avoid getting concatenated errors
1320 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1321 CRM_Core_Error
::singleton()->reset();
1322 throw new API_Exception($msg);
1325 // If we have custom fields the BAO may have taken care of it or we may have to.
1326 // $extendsMap provides a pretty good hard-coded list of BAOs that take care of the custom data.
1327 if (isset($params['custom']) && empty(CRM_Core_BAO_CustomQuery
::$extendsMap[$entity])) {
1328 CRM_Core_BAO_CustomValueTable
::store($params['custom'], CRM_Core_DAO_AllCoreTables
::getTableForClass(CRM_Core_DAO_AllCoreTables
::getFullName($entity)), $bao->id
);
1331 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1332 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1337 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1339 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1340 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1342 * @param string $bao_name
1343 * @param array $params
1345 * @throws API_Exception
1347 * @return CRM_Core_DAO|NULL
1348 * An instance of the BAO
1350 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1351 $dao_name = get_parent_class($bao_name);
1352 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1353 $dao_name = $bao_name;
1355 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1356 if (empty($entityName)) {
1357 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", [
1358 'class_name' => $bao_name,
1361 $hook = empty($params['id']) ?
'create' : 'edit';
1363 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1364 $instance = new $dao_name();
1365 $instance->copyValues($params, TRUE);
1367 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1373 * Function to do a 'standard' api del.
1375 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1377 * @param string $bao_name
1378 * @param array $params
1382 * @throws API_Exception
1383 * @throws \Civi\API\Exception\UnauthorizedException
1385 function _civicrm_api3_basic_delete($bao_name, &$params) {
1386 civicrm_api3_verify_mandatory($params, NULL, ['id']);
1387 _civicrm_api3_check_edit_permissions($bao_name, ['id' => $params['id']]);
1388 $args = array(&$params['id']);
1389 if (method_exists($bao_name, 'del')) {
1390 $dao = new $bao_name();
1391 $dao->id
= $params['id'];
1393 $bao = call_user_func_array([$bao_name, 'del'], $args);
1394 if ($bao !== FALSE) {
1395 return civicrm_api3_create_success();
1397 throw new API_Exception('Could not delete entity id ' . $params['id']);
1399 throw new API_Exception('Could not delete entity id ' . $params['id']);
1401 elseif (method_exists($bao_name, 'delete')) {
1402 $dao = new $bao_name();
1403 $dao->id
= $params['id'];
1405 while ($dao->fetch()) {
1407 return civicrm_api3_create_success();
1411 throw new API_Exception('Could not delete entity id ' . $params['id']);
1415 throw new API_Exception('no delete method found');
1419 * Get custom data for the given entity & Add it to the returnArray.
1421 * This looks like 'custom_123' = 'custom string' AND
1422 * 'custom_123_1' = 'custom string'
1423 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1425 * @param array $returnArray
1426 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1427 * @param $checkPermission
1428 * @param string $entity
1429 * E.g membership, event.
1430 * @param int $entity_id
1431 * @param int $groupID
1432 * Per CRM_Core_BAO_CustomGroup::getTree.
1433 * @param int $subType
1434 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1435 * @param string $subName
1436 * Subtype of entity.
1438 function _civicrm_api3_custom_data_get(&$returnArray, $checkPermission, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1439 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1450 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1);
1452 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1454 foreach ($groupTree as $set) {
1455 $fieldInfo +
= $set['fields'];
1457 if (!empty($customValues)) {
1458 foreach ($customValues as $key => $val) {
1459 // per standard - return custom_fieldID
1460 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1461 $returnArray['custom_' . $id] = $val;
1463 //not standard - but some api did this so guess we should keep - cheap as chips
1464 $returnArray[$key] = $val;
1466 // Shim to restore legacy behavior of ContactReference custom fields
1467 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1468 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1469 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1476 * Used by the Validate API.
1477 * @param string $entity
1478 * @param string $action
1479 * @param array $params
1481 * @return array $errors
1483 function _civicrm_api3_validate($entity, $action, $params) {
1485 $fields = civicrm_api3($entity, 'getfields', ['sequential' => 1, 'api_action' => $action]);
1486 $fields = $fields['values'];
1488 // Check for required fields.
1489 foreach ($fields as $values) {
1490 if (!empty($values['api.required']) && empty($params[$values['name']])) {
1491 $errors[$values['name']] = [
1492 'message' => "Mandatory key(s) missing from params array: " . $values['name'],
1493 'code' => "mandatory_missing",
1498 // Select only the fields which have been input as a param.
1500 foreach ($fields as $values) {
1501 if (array_key_exists($values['name'], $params)) {
1502 $finalfields[] = $values;
1506 // This derives heavily from the function "_civicrm_api3_validate_fields".
1507 // However, the difference is that try-catch blocks are nested in the loop, making it
1508 // possible for us to get all errors in one go.
1509 foreach ($finalfields as $fieldInfo) {
1510 $fieldName = $fieldInfo['name'];
1512 _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params);
1514 catch (Exception
$e) {
1515 $errors[$fieldName] = [
1516 'message' => $e->getMessage(),
1517 'code' => 'incorrect_value',
1526 * Used by the Validate API.
1528 * @param array $fieldInfo
1529 * @param string $entity
1530 * @param array $params
1532 * @throws API_Exception
1535 function _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params) {
1536 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1537 case CRM_Utils_Type
::T_INT
:
1538 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1541 case CRM_Utils_Type
::T_DATE
:
1542 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1543 case CRM_Utils_Type
::T_TIMESTAMP
:
1544 //field is of type date or datetime
1545 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1548 case CRM_Utils_Type
::T_TEXT
:
1549 case CRM_Utils_Type
::T_STRING
:
1550 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1553 case CRM_Utils_Type
::T_MONEY
:
1554 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1556 foreach ((array) $fieldValue as $fieldvalue) {
1557 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1558 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1566 * Validate fields being passed into API.
1568 * This function relies on the getFields function working accurately
1569 * for the given API.
1571 * As of writing only date was implemented.
1573 * @param string $entity
1574 * @param string $action
1575 * @param array $params
1577 * @param array $fields
1578 * Response from getfields all variables are the same as per civicrm_api.
1582 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields) {
1583 //CRM-15792 handle datetime for custom fields below code handles chain api call
1584 $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params)));
1585 if (!empty($chainApikeys) && is_array($chainApikeys)) {
1586 foreach ($chainApikeys as $key => $value) {
1587 if (is_array($params[$key])) {
1588 $chainApiParams = array_intersect_key($fields, $params[$key]);
1589 $customFields = array_fill_keys(array_keys($params[$key]), $key);
1593 $fields = array_intersect_key($fields, $params);
1594 if (!empty($chainApiParams)) {
1595 $fields = array_merge($fields, $chainApiParams);
1597 foreach ($fields as $fieldName => $fieldInfo) {
1598 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1599 case CRM_Utils_Type
::T_INT
:
1600 //field is of type integer
1601 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1604 case CRM_Utils_Type
::T_DATE
:
1605 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1606 case CRM_Utils_Type
::T_TIMESTAMP
:
1607 //field is of type date or datetime
1608 if (!empty($customFields) && array_key_exists($fieldName, $customFields)) {
1609 $dateParams = &$params[$customFields[$fieldName]];
1612 $dateParams = &$params;
1614 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
1617 case CRM_Utils_Type
::T_TEXT
:
1618 case CRM_Utils_Type
::T_STRING
:
1619 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1622 case CRM_Utils_Type
::T_MONEY
:
1623 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1624 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1627 foreach ((array) $fieldValue as $fieldvalue) {
1628 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1629 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1638 * Validate foreign key values of fields being passed into API.
1640 * This function relies on the getFields function working accurately
1641 * for the given API.
1643 * @param string $entity
1644 * @param string $action
1645 * @param array $params
1647 * @param array $fields
1648 * Response from getfields all variables are the same as per civicrm_api.
1652 function _civicrm_api3_validate_foreign_keys($entity, $action, &$params, $fields) {
1653 // intensive checks - usually only called after DB level fail
1654 foreach ($fields as $fieldName => $fieldInfo) {
1655 if (!empty($fieldInfo['FKClassName'])) {
1656 if (!empty($params[$fieldName])) {
1657 foreach ((array) $params[$fieldName] as $fieldValue) {
1658 _civicrm_api3_validate_constraint($fieldValue, $fieldName, $fieldInfo);
1661 elseif (!empty($fieldInfo['required'])) {
1662 throw new Exception("DB Constraint Violation - $fieldName should possibly be marked as mandatory for $entity,$action API. If so, please raise a bug report.");
1665 if (!empty($fieldInfo['api.unique'])) {
1666 $params['entity'] = $entity;
1667 _civicrm_api3_validate_unique_key($params, $fieldName);
1673 * Validate date fields being passed into API.
1675 * It currently converts both unique fields and DB field names to a mysql date.
1676 * @todo - probably the unique field handling & the if exists handling is now done before this
1677 * function is reached in the wrapper - can reduce this code down to assume we
1678 * are only checking the passed in field
1680 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1681 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1683 * @param array $params
1684 * Params from civicrm_api.
1685 * @param string $fieldName
1686 * Uniquename of field being checked.
1687 * @param array $fieldInfo
1688 * Array of fields from getfields function.
1692 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1693 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1694 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1698 if ($fieldValue === 'null' && empty($fieldInfo['api.required'])) {
1699 // This is the wierd & wonderful way PEAR sets null.
1703 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1704 if (!empty($params[$fieldInfo['name']])) {
1705 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1707 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1708 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1712 $params[$fieldName][$op] = $fieldValue;
1715 $params[$fieldName] = $fieldValue;
1720 * Convert date into BAO friendly date.
1722 * We accept 'whatever strtotime accepts'
1724 * @param string $dateValue
1725 * @param string $fieldName
1731 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1732 if (is_array($dateValue)) {
1733 foreach ($dateValue as $key => $value) {
1734 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1738 if (strtotime($dateValue) === FALSE) {
1739 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1741 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1742 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1746 * Validate foreign constraint fields being passed into API.
1748 * @param mixed $fieldValue
1749 * @param string $fieldName
1750 * Uniquename of field being checked.
1751 * @param array $fieldInfo
1752 * Array of fields from getfields function.
1754 * @throws \API_Exception
1756 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1757 $daoName = $fieldInfo['FKClassName'];
1758 $dao = new $daoName();
1759 $dao->id
= $fieldValue;
1761 $dao->selectAdd('id');
1762 if (!$dao->find()) {
1763 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1768 * Validate foreign constraint fields being passed into API.
1770 * @param array $params
1771 * Params from civicrm_api.
1772 * @param string $fieldName
1773 * Uniquename of field being checked.
1777 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1778 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1779 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1782 $existing = civicrm_api($params['entity'], 'get', [
1783 'version' => $params['version'],
1784 $fieldName => $fieldValue,
1786 // an entry already exists for this unique field
1787 if ($existing['count'] == 1) {
1788 // question - could this ever be a security issue?
1789 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1794 * Generic implementation of the "replace" action.
1796 * Replace the old set of entities (matching some given keys) with a new set of
1797 * entities (matching the same keys).
1799 * @note This will verify that 'values' is present, but it does not directly verify
1800 * any other parameters.
1802 * @param string $entity
1804 * @param array $params
1805 * Params from civicrm_api, including:.
1806 * - 'values': an array of records to save
1807 * - all other items: keys which identify new/pre-existing records.
1811 function _civicrm_api3_generic_replace($entity, $params) {
1813 $transaction = new CRM_Core_Transaction();
1815 if (!is_array($params['values'])) {
1816 throw new Exception("Mandatory key(s) missing from params array: values");
1819 // Extract the keys -- somewhat scary, don't think too hard about it
1820 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1822 // Lookup pre-existing records
1823 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1824 if (civicrm_error($preexisting)) {
1825 $transaction->rollback();
1826 return $preexisting;
1829 // Save the new/updated records
1831 foreach ($params['values'] as $replacement) {
1832 // Sugar: Don't force clients to duplicate the 'key' data
1833 $replacement = array_merge($baseParams, $replacement);
1834 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1835 $create = civicrm_api($entity, $action, $replacement);
1836 if (civicrm_error($create)) {
1837 $transaction->rollback();
1840 foreach ($create['values'] as $entity_id => $entity_value) {
1841 $creates[$entity_id] = $entity_value;
1845 // Remove stale records
1846 $staleIDs = array_diff(
1847 array_keys($preexisting['values']),
1848 array_keys($creates)
1850 foreach ($staleIDs as $staleID) {
1851 $delete = civicrm_api($entity, 'delete', [
1852 'version' => $params['version'],
1855 if (civicrm_error($delete)) {
1856 $transaction->rollback();
1861 return civicrm_api3_create_success($creates, $params);
1863 catch (PEAR_Exception
$e) {
1864 $transaction->rollback();
1865 return civicrm_api3_create_error($e->getMessage());
1867 catch (Exception
$e) {
1868 $transaction->rollback();
1869 return civicrm_api3_create_error($e->getMessage());
1874 * Replace base parameters.
1876 * @param array $params
1880 function _civicrm_api3_generic_replace_base_params($params) {
1881 $baseParams = $params;
1882 unset($baseParams['values']);
1883 unset($baseParams['sequential']);
1884 unset($baseParams['options']);
1889 * Returns fields allowable by api.
1892 * String Entity to query.
1893 * @param bool $unique
1894 * Index by unique fields?.
1895 * @param array $params
1899 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = []) {
1907 $dao = _civicrm_api3_get_DAO($entity);
1912 $fields = $d->fields();
1914 foreach ($fields as $name => &$field) {
1915 // Denote as core field
1916 $field['is_core_field'] = TRUE;
1917 // Set html attributes for text fields
1918 if (isset($field['html'])) {
1919 $field['html'] +
= (array) $d::makeAttribute($field);
1923 // replace uniqueNames by the normal names as the key
1924 if (empty($unique)) {
1925 foreach ($fields as $name => &$field) {
1926 //getting rid of unused attributes
1927 foreach ($unsetIfEmpty as $attr) {
1928 if (empty($field[$attr])) {
1929 unset($field[$attr]);
1932 if ($name == $field['name']) {
1935 if (array_key_exists($field['name'], $fields)) {
1936 $field['error'] = 'name conflict';
1937 // it should never happen, but better safe than sorry
1940 $fields[$field['name']] = $field;
1941 $fields[$field['name']]['uniqueName'] = $name;
1942 unset($fields[$name]);
1945 // Translate FKClassName to the corresponding api
1946 foreach ($fields as $name => &$field) {
1947 if (!empty($field['FKClassName'])) {
1948 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1950 $field['FKApiName'] = $FKApi;
1954 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1959 * Return an array of fields for a given entity.
1961 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1964 * @param array $params
1968 function _civicrm_api_get_custom_fields($entity, &$params) {
1969 $entity = _civicrm_api_get_camel_name($entity);
1970 if ($entity == 'Contact') {
1971 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1972 $entity = CRM_Utils_Array
::value('contact_type', $params);
1974 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1977 // we could / should probably test for other subtypes here - e.g. activity_type_id
1978 CRM_Utils_Array
::value('contact_sub_type', $params),
1987 foreach ($customfields as $key => $value) {
1988 // Regular fields have a 'name' property
1989 $value['name'] = 'custom_' . $key;
1990 $value['title'] = $value['label'];
1991 if ($value['data_type'] == 'Date' && CRM_Utils_Array
::value('time_format', $value, 0) > 0) {
1992 $value['data_type'] = 'DateTime';
1994 $value['type'] = CRM_Utils_Array
::value($value['data_type'], CRM_Core_BAO_CustomField
::dataToType());
1995 $ret['custom_' . $key] = $value;
2001 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
2003 * If multiple aliases the last takes precedence
2005 * Function also swaps unique fields for non-unique fields & vice versa.
2007 * @param $apiRequest
2010 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
2011 foreach ($fields as $field => $values) {
2012 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
2013 if (!empty($values['api.aliases'])) {
2014 // if aliased field is not set we try to use field alias
2015 if (!isset($apiRequest['params'][$field])) {
2016 foreach ($values['api.aliases'] as $alias) {
2017 if (isset($apiRequest['params'][$alias])) {
2018 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
2020 //unset original field nb - need to be careful with this as it may bring inconsistencies
2021 // out of the woodwork but will be implementing only as _spec function extended
2022 unset($apiRequest['params'][$alias]);
2026 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
2027 && isset($apiRequest['params'][$values['name']])
2029 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
2030 // note that it would make sense to unset the original field here but tests need to be in place first
2031 if ($field != 'domain_version') {
2032 unset($apiRequest['params'][$values['name']]);
2035 if (!isset($apiRequest['params'][$field])
2037 && $field != $uniqueName
2038 && array_key_exists($uniqueName, $apiRequest['params'])
2040 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
2041 // note that it would make sense to unset the original field here but tests need to be in place first
2048 * Validate integer fields being passed into API.
2050 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
2052 * @param array $params
2053 * Params from civicrm_api.
2054 * @param string $fieldName
2055 * Uniquename of field being checked.
2056 * @param array $fieldInfo
2057 * Array of fields from getfields function.
2058 * @param string $entity
2060 * @throws API_Exception
2062 function _civicrm_api3_validate_integer(&$params, $fieldName, &$fieldInfo, $entity) {
2063 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2064 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2068 if (!empty($fieldValue) ||
$fieldValue === '0' ||
$fieldValue === 0) {
2069 // if value = 'user_contact_id' (or similar), replace value with contact id
2070 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
2071 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
2072 if ('unknown-user' === $realContactId) {
2073 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, ['error_field' => $fieldName, "type" => "integer"]);
2075 elseif (is_numeric($realContactId)) {
2076 $fieldValue = $realContactId;
2078 elseif (is_null($realContactId) && empty($fieldInfo['api.required']) && $fieldValue === 'user_contact_id') {
2079 // If not mandatory this will be OK. If mandatory it should fail.
2083 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2084 $additional_lookup_params = [];
2085 if (strtolower($entity) == 'address' && $fieldName == 'state_province_id') {
2086 $country_id = _civicrm_api3_resolve_country_id($params);
2087 if (!empty($country_id)) {
2088 $additional_lookup_params = ['country_id' => $country_id];
2091 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op, $additional_lookup_params);
2094 // After swapping options, ensure we have an integer(s)
2095 foreach ((array) ($fieldValue) as $value) {
2096 if ($value && !is_numeric($value) && $value !== 'null' && $value !== NULL && !is_array($value)) {
2097 throw new API_Exception("$fieldName is not a valid integer", 2001, ['error_field' => $fieldName, "type" => "integer"]);
2101 // Check our field length
2102 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
2104 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
2105 2100, ['field' => $fieldName, "max_length" => $fieldInfo['maxlength']]
2111 $params[$fieldName][$op] = $fieldValue;
2114 $params[$fieldName] = $fieldValue;
2119 * Helper function to determine country_id given the myriad of values for country_id or country that are supported
2124 function _civicrm_api3_resolve_country_id($params) {
2125 if (!empty($params['country_id'])) {
2126 if (is_numeric($params['country_id'])) {
2127 $country_id = $params['country_id'];
2130 $country = new CRM_Core_DAO_Country();
2131 $country->name
= $params['country_id'];
2132 if (!$country->find(TRUE)) {
2133 $country->name
= NULL;
2134 $country->iso_code
= $params['country_id'];
2135 $country->find(TRUE);
2137 if (!empty($country->id
)) {
2138 $country_id = $country->id
;
2142 elseif (!empty($params['country'])) {
2143 if (is_numeric($params['country'])) {
2144 $country_id = $params['country'];
2147 $country = new CRM_Core_DAO_Country();
2148 $country->name
= $params['country'];
2149 if (!$country->find(TRUE)) {
2150 $country->name
= NULL;
2151 $country->iso_code
= $params['country'];
2152 $country->find(TRUE);
2154 if (!empty($country->id
)) {
2155 $country_id = $country->id
;
2159 return !empty($country_id) ?
$country_id : NULL;
2163 * Determine a contact ID using a string expression.
2165 * @param string $contactIdExpr
2166 * E.g. "user_contact_id" or "@user:username".
2168 * @return int|null|'unknown-user'
2169 * @throws \CRM_Core_Exception
2171 function _civicrm_api3_resolve_contactID($contactIdExpr) {
2172 // If value = 'user_contact_id' replace value with logged in user id.
2173 if ($contactIdExpr == "user_contact_id") {
2174 return CRM_Core_Session
::getLoggedInContactID();
2176 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
2177 $config = CRM_Core_Config
::singleton();
2179 $ufID = $config->userSystem
->getUfId($matches[1]);
2181 return 'unknown-user';
2184 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
2186 return 'unknown-user';
2195 * Validate html (check for scripting attack).
2197 * @param array $params
2198 * @param string $fieldName
2199 * @param array $fieldInfo
2201 * @throws API_Exception
2203 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
2204 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2205 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
2209 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2210 throw new API_Exception('Input contains illegal SCRIPT tag.', ["field" => $fieldName, "error_code" => "xss"]);
2216 * Validate string fields being passed into API.
2218 * @param array $params
2219 * Params from civicrm_api.
2220 * @param string $fieldName
2221 * Uniquename of field being checked.
2222 * @param array $fieldInfo
2223 * Array of fields from getfields function.
2224 * @param string $entity
2226 * @throws API_Exception
2229 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2230 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName, 'String');
2231 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
2235 if (!is_array($fieldValue)) {
2236 $fieldValue = (string) $fieldValue;
2240 foreach ((array) $fieldValue as $key => $value) {
2241 foreach ([$fieldValue, $key, $value] as $input) {
2242 if (!CRM_Utils_Rule
::xssString($input)) {
2243 throw new Exception('Input contains illegal SCRIPT tag.');
2246 if ($fieldName == 'currency') {
2247 //When using IN operator $fieldValue is a array of currency codes
2248 if (!CRM_Utils_Rule
::currencyCode($value)) {
2249 throw new Exception("Currency not a valid code: $currency");
2254 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2255 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op);
2257 // Check our field length
2258 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2259 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2260 2100, ['field' => $fieldName]
2265 $params[$fieldName][$op] = $fieldValue;
2268 $params[$fieldName] = $fieldValue;
2273 * Validate & swap out any pseudoconstants / options.
2275 * @param mixed $fieldValue
2276 * @param string $entity : api entity name
2277 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2278 * @param array $fieldInfo : getfields meta-data
2280 * @param array $additional_lookup_params
2282 * @throws \API_Exception
2284 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo, $op = '=', $additional_lookup_params = []) {
2285 if (in_array($op, ['>', '<', '>=', '<=', 'LIKE', 'NOT LIKE'])) {
2289 $options = CRM_Utils_Array
::value('options', $fieldInfo);
2292 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2293 // We need to get the options from the entity the field relates to.
2294 $entity = $fieldInfo['entity'];
2296 $options_lookup_params = [
2298 'field' => $fieldInfo['name'],
2299 'context' => 'validate',
2301 if (!empty($additional_lookup_params)) {
2302 $options_lookup_params = array_merge($additional_lookup_params, $options_lookup_params);
2304 $options = civicrm_api($entity, 'getoptions', $options_lookup_params);
2306 $options = CRM_Utils_Array
::value('values', $options, []);
2309 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2311 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2312 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
2315 // If passed multiple options, validate each.
2316 if (is_array($fieldValue)) {
2317 foreach ($fieldValue as &$value) {
2318 if (!is_array($value)) {
2319 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName, CRM_Utils_Array
::value('api.required', $fieldInfo));
2322 // TODO: unwrap the call to implodePadded from the conditional and do it always
2323 // need to verify that this is safe and doesn't break anything though.
2324 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2326 CRM_Utils_Array
::implodePadded($fieldValue);
2330 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName, CRM_Utils_Array
::value('api.required', $fieldInfo));
2335 * Validate & swap a single option value for a field.
2337 * @param string $value field value
2338 * @param array $options array of options for this field
2339 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2340 * @param bool $isRequired
2341 * Is this a required field or is 'null' an acceptable option. We allow 'null' last
2342 * in case we have the weird situation of it being a valid option in which case our
2343 * brains will probably explode.
2345 * @throws API_Exception
2347 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName, $isRequired) {
2348 // If option is a key, no need to translate
2349 // or if no options are avaiable for pseudoconstant 'table' property
2350 if (array_key_exists($value, $options) ||
!$options) {
2354 // Hack for Profile formatting fields
2355 if ($fieldName === 'field_name' && (strpos($value, 'formatting') === 0)) {
2359 // Translate value into key
2360 // Cast $value to string to avoid a bug in array_search
2361 $newValue = array_search((string) $value, $options);
2362 if ($newValue !== FALSE) {
2366 // Case-insensitive matching
2367 $newValue = strtolower($value);
2368 $options = array_map("strtolower", $options);
2369 $newValue = array_search($newValue, $options);
2370 if ($newValue === FALSE) {
2371 if ($value === 'null' && !$isRequired) {
2372 // CiviMagic syntax for Nulling out the field - let it through.
2375 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, ['error_field' => $fieldName]);
2381 * Returns the canonical name of a field.
2384 * api entity name (string should already be standardized - no camelCase).
2386 * any variation of a field's name (name, unique_name, api.alias).
2388 * @param string $action
2390 * @return bool|string
2391 * FieldName or FALSE if the field does not exist
2393 function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') {
2397 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2400 if ($fieldName == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
2403 $result = civicrm_api($entity, 'getfields', [
2405 'action' => $action,
2407 $meta = $result['values'];
2408 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2409 $fieldName = $fieldName . '_id';
2411 if (isset($meta[$fieldName])) {
2412 return $meta[$fieldName]['name'];
2414 foreach ($meta as $info) {
2415 if ($fieldName == $info['name'] ||
$fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2416 return $info['name'];
2418 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, [])) !== FALSE) {
2419 return $info['name'];
2422 // Create didn't work, try with get
2423 if ($action == 'create') {
2424 return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get');
2430 * Check if the function is deprecated.
2432 * @param string $entity
2433 * @param array $result
2435 * @return string|array|null
2437 function _civicrm_api3_deprecation_check($entity, $result = []) {
2439 $apiFile = "api/v3/$entity.php";
2440 if (CRM_Utils_File
::isIncludable($apiFile)) {
2441 require_once $apiFile;
2443 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
2444 $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation";
2445 if (function_exists($fnName)) {
2446 return $fnName($result);
2452 * Get the actual field value.
2454 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2455 * So this function returns the actual field value.
2457 * @param array $params
2458 * @param string $fieldName
2459 * @param string $type
2463 function _civicrm_api3_field_value_check(&$params, $fieldName, $type = NULL) {
2464 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2467 if (!empty($fieldValue) && is_array($fieldValue) &&
2468 (array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators()) ||
2469 $type == 'String' && strstr(key($fieldValue), 'EMPTY'))
2471 $op = key($fieldValue);
2472 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2474 return [$fieldValue, $op];
2478 * A generic "get" API based on simple array data. This is comparable to
2479 * _civicrm_api3_basic_get but does not use DAO/BAO. This is useful for
2480 * small/mid-size data loaded from external JSON or XML documents.
2483 * @param array $params
2485 * @param array $records
2486 * List of all records.
2487 * @param string $idCol
2488 * The property which defines the ID of a record
2489 * @param array $filterableFields
2490 * List of filterable fields.
2493 * @throws \API_Exception
2495 function _civicrm_api3_basic_array_get($entity, $params, $records, $idCol, $filterableFields) {
2496 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
2497 // TODO // $sort = CRM_Utils_Array::value('sort', $options, NULL);
2498 $offset = CRM_Utils_Array
::value('offset', $options);
2499 $limit = CRM_Utils_Array
::value('limit', $options);
2504 foreach ($records as $record) {
2505 if ($idCol != 'id') {
2506 $record['id'] = $record[$idCol];
2509 foreach ($params as $k => $v) {
2513 if (in_array($k, $filterableFields) && $record[$k] != $v) {
2519 if ($currentOffset >= $offset) {
2520 $matches[$record[$idCol]] = $record;
2522 if ($limit && count($matches) >= $limit) {
2529 $return = CRM_Utils_Array
::value('return', $options, []);
2530 if (!empty($return)) {
2532 $matches = CRM_Utils_Array
::filterColumns($matches, array_keys($return));
2535 return civicrm_api3_create_success($matches, $params);
2539 * @param string $bao_name
2540 * @param array $params
2541 * @throws \Civi\API\Exception\UnauthorizedException
2543 function _civicrm_api3_check_edit_permissions($bao_name, $params) {
2544 // For lack of something more clever, here's a whitelist of entities whos permissions
2545 // are inherited from a contact record.
2546 // Note, when adding here, also remember to modify _civicrm_api3_permissions()
2547 $contactEntities = [
2548 'CRM_Core_BAO_Email',
2549 'CRM_Core_BAO_Phone',
2550 'CRM_Core_BAO_Address',
2552 'CRM_Core_BAO_Website',
2553 'CRM_Core_BAO_OpenID',
2555 if (!empty($params['check_permissions']) && in_array($bao_name, $contactEntities)) {
2556 $cid = !empty($params['contact_id']) ?
$params['contact_id'] : CRM_Core_DAO
::getFieldValue($bao_name, $params['id'], 'contact_id');
2557 if (!CRM_Contact_BAO_Contact_Permission
::allow($cid, CRM_Core_Permission
::EDIT
)) {
2558 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify contact record');
2564 * Check if an entity has been modified since the last known modified_date
2565 * @param string $modifiedDate Last knowm modified_date
2566 * @param int $id Id of record to check
2567 * @param string $entity API Entity
2570 function _civicrm_api3_compare_timestamps($modifiedDate, $id, $entity) {
2571 $currentDbInfo = civicrm_api3($entity, 'getsingle', ['id' => $id]);
2572 if (strtotime($currentDbInfo['modified_date']) <= strtotime($modifiedDate)) {