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 if ($name === 'Dedupe') {
385 // Dedupe is a pseudoentity for PrevNextCache - but accessing dedupe related info
386 // not the other cache info like search results (which could in fact be in Redis or another cache engine)
387 $name = 'PrevNextCache';
389 $dao = _civicrm_api3_get_DAO($name);
393 $bao = str_replace("DAO", "BAO", $dao);
394 $file = strtr($bao, '_', '/') . '.php';
395 // Check if this entity actually has a BAO. Fall back on the DAO if not.
396 return stream_resolve_include_path($file) ?
$bao : $dao;
400 * Recursive function to explode value-separated strings into arrays.
404 function _civicrm_api3_separate_values(&$values) {
405 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
406 foreach ($values as $key => & $value) {
407 if (is_array($value)) {
408 _civicrm_api3_separate_values($value);
410 elseif (is_string($value)) {
411 // This is to honor the way case API was originally written.
412 if ($key == 'case_type_id') {
413 $value = trim(str_replace($sp, ',', $value), ',');
415 elseif (strpos($value, $sp) !== FALSE) {
416 $value = explode($sp, trim($value, $sp));
423 * This is a legacy wrapper for api_store_values.
425 * It checks suitable fields using getfields rather than DAO->fields.
427 * Getfields has handling for how to deal with unique names which dao->fields doesn't
429 * Note this is used by BAO type create functions - eg. contribution
431 * @param string $entity
432 * @param array $params
433 * @param array $values
435 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
436 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'create']);
437 $fields = $fields['values'];
438 _civicrm_api3_store_values($fields, $params, $values);
444 * @param array $fields
445 * @param array $params
446 * @param array $values
450 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
453 $keys = array_intersect_key($params, $fields);
454 foreach ($keys as $name => $value) {
455 if ($name !== 'id') {
456 $values[$name] = $value;
464 * Returns field names of the given entity fields.
466 * @param array $fields
467 * Fields array to retrieve the field names for.
470 function _civicrm_api3_field_names($fields) {
472 foreach ($fields as $key => $value) {
473 if (!empty($value['name'])) {
474 $result[] = $value['name'];
481 * Get function for query object api.
483 * The API supports 2 types of get request. The more complex uses the BAO query object.
484 * This is a generic function for those functions that call it
486 * At the moment only called by contact we should extend to contribution &
487 * others that use the query object. Note that this function passes permission information in.
490 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
494 * @param array $params
495 * As passed into api get or getcount function.
496 * @param array $additional_options
497 * Array of options (so we can modify the filter).
498 * @param bool $getCount
499 * Are we just after the count.
501 * This basically correlates to the component.
502 * @param null|array $defaultReturnProperties
503 * Default return properties for the entity
504 * (used if return not set - but don't do that - set return!).
507 * @throws API_Exception
509 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = [], $getCount = NULL, $mode = 1, $defaultReturnProperties = NULL) {
510 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
511 // Convert id to e.g. contact_id
512 if (empty($params[$lowercase_entity . '_id']) && isset($params['id'])) {
513 $params[$lowercase_entity . '_id'] = $params['id'];
515 unset($params['id']);
517 $options = _civicrm_api3_get_options_from_params($params, TRUE);
519 $inputParams = array_merge(
520 CRM_Utils_Array
::value('input_params', $options, []),
521 CRM_Utils_Array
::value('input_params', $additional_options, [])
523 $returnProperties = array_merge(
524 CRM_Utils_Array
::value('return', $options, []),
525 CRM_Utils_Array
::value('return', $additional_options, [])
527 if (empty($returnProperties)) {
528 $returnProperties = $defaultReturnProperties;
530 if (!empty($params['check_permissions'])) {
531 // we will filter query object against getfields
532 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'get']);
533 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
534 $fields['values'][$lowercase_entity . '_id'] = [];
535 $varsToFilter = ['returnProperties', 'inputParams'];
536 foreach ($varsToFilter as $varToFilter) {
537 if (!is_array($
$varToFilter)) {
540 //I was going to throw an exception rather than silently filter out - but
541 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
542 //so we are silently ignoring parts of their request
543 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
544 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
547 $options = array_merge($options, $additional_options);
548 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
549 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
550 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
551 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
555 $returnProperties = NULL;
558 if (substr($sort, 0, 2) == 'id') {
559 $sort = $lowercase_entity . "_" . $sort;
562 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
564 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
566 list($entities) = CRM_Contact_BAO_Query
::apiQuery(
585 * Get dao query object based on input params.
587 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
590 * @param array $params
591 * @param string $mode
592 * @param string $entity
595 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
597 function _civicrm_api3_get_query_object($params, $mode, $entity) {
598 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
599 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
600 $offset = CRM_Utils_Array
::value('offset', $options);
601 $rowCount = CRM_Utils_Array
::value('limit', $options);
602 $inputParams = CRM_Utils_Array
::value('input_params', $options, []);
603 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
604 if (empty($returnProperties)) {
605 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
608 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
609 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
611 empty($params['check_permissions']),
612 TRUE, TRUE, NULL, 'AND', 'NULL', TRUE
614 list($select, $from, $where, $having) = $query->query();
616 $sql = "$select $from $where $having";
619 $sort = CRM_Utils_Type
::escape($sort, 'MysqlOrderBy');
620 $sql .= " ORDER BY $sort ";
622 if (!empty($rowCount)) {
623 $sql .= " LIMIT $offset, $rowCount ";
625 $dao = CRM_Core_DAO
::executeQuery($sql);
626 return [$dao, $query];
630 * Function transfers the filters being passed into the DAO onto the params object.
632 * @deprecated DAO based retrieval is being phased out.
634 * @param CRM_Core_DAO $dao
635 * @param array $params
636 * @param bool $unique
637 * @param array $extraSql
638 * API specific queries eg for event isCurrent would be converted to
639 * $extraSql['where'] = array('civicrm_event' => array('(start_date >= CURDATE() || end_date >= CURDATE())'));
641 * @throws API_Exception
644 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $extraSql = []) {
645 $entity = _civicrm_api_get_entity_name_from_dao($dao);
646 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
647 if (!empty($params[$lowercase_entity . "_id"]) && empty($params['id'])) {
648 //if entity_id is set then treat it as ID (will be overridden by id if set)
649 $params['id'] = $params[$lowercase_entity . "_id"];
651 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
652 $fields = array_intersect(array_keys($allfields), array_keys($params));
654 $options = _civicrm_api3_get_options_from_params($params);
655 //apply options like sort
656 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
658 //accept filters like filter.activity_date_time_high
659 // std is now 'filters' => ..
660 if (strstr(implode(',', array_keys($params)), 'filter')) {
661 if (isset($params['filters']) && is_array($params['filters'])) {
662 foreach ($params['filters'] as $paramkey => $paramvalue) {
663 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
667 foreach ($params as $paramkey => $paramvalue) {
668 if (strstr($paramkey, 'filter')) {
669 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
678 foreach ($fields as $field) {
679 if (is_array($params[$field])) {
680 //get the actual fieldname from db
681 $fieldName = $allfields[$field]['name'];
682 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
683 if (!empty($where)) {
684 $dao->whereAdd($where);
689 $daoFieldName = $allfields[$field]['name'];
690 if (empty($daoFieldName)) {
691 throw new API_Exception("Failed to determine field name for \"$field\"");
693 $dao->{$daoFieldName} = $params[$field];
696 $dao->$field = $params[$field];
700 if (!empty($extraSql['where'])) {
701 foreach ($extraSql['where'] as $table => $sqlWhere) {
702 foreach ($sqlWhere as $where) {
703 $dao->whereAdd($where);
707 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
709 // Ensure 'id' is included.
710 $options['return']['id'] = TRUE;
711 $allfields = _civicrm_api3_get_unique_name_array($dao);
712 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
713 foreach ($returnMatched as $returnValue) {
714 $dao->selectAdd($returnValue);
717 // Not already matched on the field names.
718 $unmatchedFields = array_diff(
719 array_keys($options['return']),
723 $returnUniqueMatched = array_intersect(
725 // But a match for the field keys.
726 array_flip($allfields)
728 foreach ($returnUniqueMatched as $uniqueVal) {
729 $dao->selectAdd($allfields[$uniqueVal]);
732 $dao->setApiFilter($params);
736 * Apply filters (e.g. high, low) to DAO object (prior to find).
738 * @param string $filterField
739 * Field name of filter.
740 * @param string $filterValue
741 * Field value of filter.
745 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
746 if (strstr($filterField, 'high')) {
747 $fieldName = substr($filterField, 0, -5);
748 $dao->whereAdd("($fieldName <= $filterValue )");
750 if (strstr($filterField, 'low')) {
751 $fieldName = substr($filterField, 0, -4);
752 $dao->whereAdd("($fieldName >= $filterValue )");
754 if ($filterField == 'is_current' && $filterValue == 1) {
755 $todayStart = date('Ymd000000', strtotime('now'));
756 $todayEnd = date('Ymd235959', strtotime('now'));
757 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
758 if (property_exists($dao, 'is_active')) {
759 $dao->whereAdd('is_active = 1');
765 * Get sort, limit etc options from the params - supporting old & new formats.
767 * Get returnProperties for legacy
769 * @param array $params
770 * Params array as passed into civicrm_api.
771 * @param bool $queryObject
772 * Is this supporting a queryObject api (e.g contact) - if so we support more options.
773 * for legacy report & return a unique fields array
775 * @param string $entity
776 * @param string $action
778 * @throws API_Exception
780 * options extracted from params
782 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
783 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
785 $sort = CRM_Utils_Array
::value('sort', $params, 0);
786 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
787 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
789 $offset = CRM_Utils_Array
::value('offset', $params, 0);
790 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
791 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
792 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
794 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
795 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
796 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
798 if (is_array(CRM_Utils_Array
::value('options', $params))) {
799 // is count is set by generic getcount not user
800 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
801 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
802 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
803 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
806 $returnProperties = [];
807 // handle the format return =sort_name,display_name...
808 if (array_key_exists('return', $params)) {
809 if (is_array($params['return'])) {
810 $returnProperties = array_fill_keys($params['return'], 1);
813 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
814 $returnProperties = array_fill_keys($returnProperties, 1);
817 if ($entity && $action == 'get') {
818 if (!empty($returnProperties['id'])) {
819 $returnProperties[$lowercase_entity . '_id'] = 1;
820 unset($returnProperties['id']);
825 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
826 'limit' => (!$is_count && CRM_Utils_Rule
::integer($limit)) ?
$limit : NULL,
827 'is_count' => $is_count,
828 'return' => !empty($returnProperties) ?
$returnProperties : [],
832 $options['sort'] = NULL;
834 if (!is_array($sort)) {
835 $sort = array_map('trim', explode(',', $sort));
837 foreach ($sort as $s) {
838 if ($s == '(1)' || CRM_Utils_Rule
::mysqlOrderBy($s)) {
839 if ($entity && $action == 'get') {
840 switch (trim(strtolower($s))) {
844 $s = str_replace('id', $lowercase_entity . '_id', $s);
850 throw new API_Exception("Unknown field specified for sort. Cannot order by '$s'");
853 $options['sort'] = implode(', ', $finalSort);
856 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
857 throw new API_Exception('invalid string in sort options');
863 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
864 // if the query object is being used this should be used
866 $legacyreturnProperties = [];
868 'sort', 'offset', 'rowCount', 'options', 'return',
869 'version', 'prettyprint', 'check_permissions', 'sequential',
871 foreach ($params as $n => $v) {
872 if (substr($n, 0, 7) == 'return.') {
873 $legacyreturnProperties[substr($n, 7)] = $v;
875 elseif ($n == 'id') {
876 $inputParams[$lowercase_entity . '_id'] = $v;
878 elseif (in_array($n, $otherVars)) {
881 $inputParams[$n] = $v;
882 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
883 throw new API_Exception('invalid string');
887 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
888 $options['input_params'] = $inputParams;
893 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
895 * @param array $params
896 * Params array as passed into civicrm_api.
901 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
903 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
904 if (!$options['is_count']) {
905 if (!empty($options['limit'])) {
906 $dao->limit((int) $options['offset'], (int) $options['limit']);
908 if (!empty($options['sort'])) {
909 $options['sort'] = CRM_Utils_Type
::escape($options['sort'], 'MysqlOrderBy');
910 $dao->orderBy($options['sort']);
916 * Build fields array.
918 * This is the array of fields as it relates to the given DAO
919 * returns unique fields as keys by default but if set but can return by DB fields
921 * @param CRM_Core_DAO $bao
922 * @param bool $unique
926 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
927 $fields = $bao->fields();
929 if (empty($fields['id'])) {
930 $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
931 if (isset($fields[$lowercase_entity . '_id'])) {
932 $fields['id'] = $fields[$lowercase_entity . '_id'];
933 unset($fields[$lowercase_entity . '_id']);
939 foreach ($fields as $field) {
940 $dbFields[$field['name']] = $field;
946 * Build fields array.
948 * This is the array of fields as it relates to the given DAO
949 * returns unique fields as keys by default but if set but can return by DB fields
951 * @param CRM_Core_DAO $bao
955 function _civicrm_api3_get_unique_name_array(&$bao) {
956 $fields = $bao->fields();
957 foreach ($fields as $field => $values) {
958 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
960 return $uniqueFields;
964 * Converts an DAO object to an array.
966 * @deprecated - DAO based retrieval is being phased out.
968 * @param CRM_Core_DAO $dao
970 * @param array $params
971 * @param bool $uniqueFields
972 * @param string $entity
973 * @param bool $autoFind
977 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
979 if (isset($params['options']) && !empty($params['options']['is_count'])) {
980 return $dao->count();
985 if ($autoFind && !$dao->find()) {
989 if (isset($dao->count
)) {
993 $fields = array_keys(_civicrm_api3_build_fields_array($dao, FALSE));
994 while ($dao->fetch()) {
996 foreach ($fields as $key) {
997 if (array_key_exists($key, $dao)) {
998 // not sure on that one
999 if ($dao->$key !== NULL) {
1000 $tmp[$key] = $dao->$key;
1004 $result[$dao->id
] = $tmp;
1006 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
1007 _civicrm_api3_custom_data_get($result[$dao->id
], $params['check_permissions'], $entity, $dao->id
);
1015 * Determine if custom fields need to be retrieved.
1017 * We currently retrieve all custom fields or none at this level so if we know the entity
1018 * && 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
1019 * @todo filter so only required fields are queried
1021 * @param string $entity
1022 * Entity name in CamelCase.
1023 * @param array $params
1027 function _civicrm_api3_custom_fields_are_required($entity, $params) {
1028 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
1031 $options = _civicrm_api3_get_options_from_params($params);
1032 // We check for possibility of 'custom' => 1 as well as specific custom fields.
1033 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
1034 if (stristr($returnString, 'custom')) {
1040 * Converts an object to an array.
1042 * @param object $dao
1043 * (reference) object to convert.
1044 * @param array $values
1045 * (reference) array.
1046 * @param array|bool $uniqueFields
1048 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
1050 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
1051 foreach ($fields as $key => $value) {
1052 if (array_key_exists($key, $dao)) {
1053 $values[$key] = $dao->$key;
1059 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1066 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1067 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1071 * Format custom parameters.
1073 * @param array $params
1074 * @param array $values
1075 * @param string $extends
1076 * Entity that this custom field extends (e.g. contribution, event, contact).
1077 * @param string $entityId
1078 * ID of entity per $extends.
1080 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1081 $values['custom'] = [];
1082 $checkCheckBoxField = FALSE;
1084 if (in_array($extends, ['Household', 'Individual', 'Organization'])) {
1085 $entity = 'Contact';
1088 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'create']);
1089 if (!$fields['is_error']) {
1090 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1091 $fields = $fields['values'];
1092 $checkCheckBoxField = TRUE;
1095 foreach ($params as $key => $value) {
1096 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
1097 if ($customFieldID && (!is_null($value))) {
1098 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1099 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1102 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1103 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1110 * Format parameters for create action.
1112 * @param array $params
1115 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1116 $nonGenericEntities = ['Contact', 'Individual', 'Household', 'Organization'];
1118 $customFieldEntities = array_diff_key(CRM_Core_SelectValues
::customGroupExtends(), array_fill_keys($nonGenericEntities, 1));
1119 if (!array_key_exists($entity, $customFieldEntities)) {
1123 _civicrm_api3_custom_format_params($params, $values, $entity);
1124 $params = array_merge($params, $values);
1128 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1130 * We should look at pushing to BAO function
1131 * 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
1132 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1134 * 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
1135 * don't touch - lots of very cautious code in here
1137 * The resulting array should look like
1143 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1145 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1146 * be fixed in future
1148 * @param mixed $checkboxFieldValue
1149 * @param string $customFieldLabel
1150 * @param string $entity
1152 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1154 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1155 // We can assume it's pre-formatted.
1158 $options = civicrm_api($entity, 'getoptions', ['field' => $customFieldLabel, 'version' => 3]);
1159 if (!empty($options['is_error'])) {
1160 // The check is precautionary - can probably be removed later.
1164 $options = $options['values'];
1166 if (is_array($checkboxFieldValue)) {
1167 foreach ($checkboxFieldValue as $key => $value) {
1168 if (!array_key_exists($key, $options)) {
1169 $validValue = FALSE;
1173 // we have been passed an array that is already in the 'odd' custom field format
1178 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1179 // if the array only has one item we'll treat it like any other string
1180 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1181 $possibleValue = reset($checkboxFieldValue);
1183 if (is_string($checkboxFieldValue)) {
1184 $possibleValue = $checkboxFieldValue;
1186 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1187 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1190 elseif (is_array($checkboxFieldValue)) {
1191 // so this time around we are considering the values in the array
1192 $possibleValues = $checkboxFieldValue;
1193 $formatValue = TRUE;
1195 elseif (stristr($checkboxFieldValue, ',')) {
1196 $formatValue = TRUE;
1197 //lets see if we should separate it - we do this near the end so we
1198 // ensure we have already checked that the comma is not part of a legitimate match
1199 // and of course, we don't make any changes if we don't now have matches
1200 $possibleValues = explode(',', $checkboxFieldValue);
1203 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1207 foreach ($possibleValues as $index => $possibleValue) {
1208 if (array_key_exists($possibleValue, $options)) {
1209 // 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)
1211 elseif (array_key_exists(trim($possibleValue), $options)) {
1212 $possibleValues[$index] = trim($possibleValue);
1215 $formatValue = FALSE;
1219 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1224 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1226 * @param string $bao_name
1228 * @param array $params
1230 * @param bool $returnAsSuccess
1231 * Return in api success format.
1232 * @param string $entity
1233 * @param CRM_Utils_SQL_Select|NULL $sql
1234 * Extra SQL bits to add to the query. For filtering current events, this might be:
1235 * CRM_Utils_SQL_Select::fragment()->where('(start_date >= CURDATE() || end_date >= CURDATE())');
1236 * @param bool $uniqueFields
1237 * Should unique field names be returned (for backward compatibility)
1241 function _civicrm_api3_basic_get($bao_name, $params, $returnAsSuccess = TRUE, $entity = "", $sql = NULL, $uniqueFields = FALSE) {
1242 $entity = $entity ?
: CRM_Core_DAO_AllCoreTables
::getBriefName(str_replace('_BAO_', '_DAO_', $bao_name));
1243 $options = _civicrm_api3_get_options_from_params($params);
1245 $query = new \Civi\API\
Api3SelectQuery($entity, CRM_Utils_Array
::value('check_permissions', $params, FALSE));
1246 $query->where
= $params;
1247 if ($options['is_count']) {
1248 $query->select
= ['count_rows'];
1251 $query->select
= array_keys(array_filter($options['return']));
1252 $query->orderBy
= $options['sort'];
1253 $query->isFillUniqueFields
= $uniqueFields;
1255 $query->limit
= $options['limit'];
1256 $query->offset
= $options['offset'];
1257 $query->merge($sql);
1258 $result = $query->run();
1260 if ($returnAsSuccess) {
1261 return civicrm_api3_create_success($result, $params, $entity, 'get');
1267 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1269 * @param string $bao_name
1270 * Name of BAO Class.
1271 * @param array $params
1272 * Parameters passed into the api call.
1273 * @param string $entity
1274 * Entity - pass in if entity is non-standard & required $ids array.
1276 * @throws API_Exception
1277 * @throws \Civi\API\Exception\UnauthorizedException
1280 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1281 _civicrm_api3_check_edit_permissions($bao_name, $params);
1282 _civicrm_api3_format_params_for_create($params, $entity);
1283 $args = array(&$params);
1285 $ids = [$entity => CRM_Utils_Array
::value('id', $params)];
1289 if (method_exists($bao_name, 'create')) {
1291 $fct_name = $bao_name . '::' . $fct;
1292 $bao = call_user_func_array([$bao_name, $fct], $args);
1294 elseif (method_exists($bao_name, 'add')) {
1296 $fct_name = $bao_name . '::' . $fct;
1297 $bao = call_user_func_array([$bao_name, $fct], $args);
1300 $fct_name = '_civicrm_api3_basic_create_fallback';
1301 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1304 if (is_null($bao)) {
1305 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1307 elseif (is_a($bao, 'CRM_Core_Error')) {
1308 //some weird circular thing means the error takes itself as an argument
1309 $msg = $bao->getMessages($bao);
1310 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1311 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1312 // so we need to reset the error object here to avoid getting concatenated errors
1313 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1314 CRM_Core_Error
::singleton()->reset();
1315 throw new API_Exception($msg);
1318 // If we have custom fields the BAO may have taken care of it or we may have to.
1319 // $extendsMap provides a pretty good hard-coded list of BAOs that take care of the custom data.
1320 if (isset($params['custom']) && empty(CRM_Core_BAO_CustomQuery
::$extendsMap[$entity])) {
1321 CRM_Core_BAO_CustomValueTable
::store($params['custom'], CRM_Core_DAO_AllCoreTables
::getTableForClass(CRM_Core_DAO_AllCoreTables
::getFullName($entity)), $bao->id
);
1324 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1325 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1330 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1332 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1333 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1335 * @param string $bao_name
1336 * @param array $params
1338 * @throws API_Exception
1340 * @return CRM_Core_DAO|NULL
1341 * An instance of the BAO
1343 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1344 $dao_name = get_parent_class($bao_name);
1345 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1346 $dao_name = $bao_name;
1348 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1349 if (empty($entityName)) {
1350 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", [
1351 'class_name' => $bao_name,
1354 $hook = empty($params['id']) ?
'create' : 'edit';
1356 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1357 $instance = new $dao_name();
1358 $instance->copyValues($params, TRUE);
1360 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1366 * Function to do a 'standard' api del.
1368 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1370 * @param string $bao_name
1371 * @param array $params
1375 * @throws API_Exception
1376 * @throws \Civi\API\Exception\UnauthorizedException
1378 function _civicrm_api3_basic_delete($bao_name, &$params) {
1379 civicrm_api3_verify_mandatory($params, NULL, ['id']);
1380 _civicrm_api3_check_edit_permissions($bao_name, ['id' => $params['id']]);
1381 $args = array(&$params['id']);
1382 if (method_exists($bao_name, 'del')) {
1383 $dao = new $bao_name();
1384 $dao->id
= $params['id'];
1386 $bao = call_user_func_array([$bao_name, 'del'], $args);
1387 if ($bao !== FALSE) {
1388 return civicrm_api3_create_success();
1390 throw new API_Exception('Could not delete entity id ' . $params['id']);
1392 throw new API_Exception('Could not delete entity id ' . $params['id']);
1394 elseif (method_exists($bao_name, 'delete')) {
1395 $dao = new $bao_name();
1396 $dao->id
= $params['id'];
1398 while ($dao->fetch()) {
1400 return civicrm_api3_create_success();
1404 throw new API_Exception('Could not delete entity id ' . $params['id']);
1408 throw new API_Exception('no delete method found');
1412 * Get custom data for the given entity & Add it to the returnArray.
1414 * This looks like 'custom_123' = 'custom string' AND
1415 * 'custom_123_1' = 'custom string'
1416 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1418 * @param array $returnArray
1419 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1420 * @param $checkPermission
1421 * @param string $entity
1422 * E.g membership, event.
1423 * @param int $entity_id
1424 * @param int $groupID
1425 * Per CRM_Core_BAO_CustomGroup::getTree.
1426 * @param int $subType
1427 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1428 * @param string $subName
1429 * Subtype of entity.
1431 function _civicrm_api3_custom_data_get(&$returnArray, $checkPermission, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1432 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1443 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1);
1445 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1447 foreach ($groupTree as $set) {
1448 $fieldInfo +
= $set['fields'];
1450 if (!empty($customValues)) {
1451 foreach ($customValues as $key => $val) {
1452 // per standard - return custom_fieldID
1453 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1454 $returnArray['custom_' . $id] = $val;
1456 //not standard - but some api did this so guess we should keep - cheap as chips
1457 $returnArray[$key] = $val;
1459 // Shim to restore legacy behavior of ContactReference custom fields
1460 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1461 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1462 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1469 * Used by the Validate API.
1470 * @param string $entity
1471 * @param string $action
1472 * @param array $params
1474 * @return array $errors
1476 function _civicrm_api3_validate($entity, $action, $params) {
1478 $fields = civicrm_api3($entity, 'getfields', ['sequential' => 1, 'api_action' => $action]);
1479 $fields = $fields['values'];
1481 // Check for required fields.
1482 foreach ($fields as $values) {
1483 if (!empty($values['api.required']) && empty($params[$values['name']])) {
1484 $errors[$values['name']] = [
1485 'message' => "Mandatory key(s) missing from params array: " . $values['name'],
1486 'code' => "mandatory_missing",
1491 // Select only the fields which have been input as a param.
1493 foreach ($fields as $values) {
1494 if (array_key_exists($values['name'], $params)) {
1495 $finalfields[] = $values;
1499 // This derives heavily from the function "_civicrm_api3_validate_fields".
1500 // However, the difference is that try-catch blocks are nested in the loop, making it
1501 // possible for us to get all errors in one go.
1502 foreach ($finalfields as $fieldInfo) {
1503 $fieldName = $fieldInfo['name'];
1505 _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params);
1507 catch (Exception
$e) {
1508 $errors[$fieldName] = [
1509 'message' => $e->getMessage(),
1510 'code' => 'incorrect_value',
1519 * Used by the Validate API.
1521 * @param array $fieldInfo
1522 * @param string $entity
1523 * @param array $params
1525 * @throws API_Exception
1528 function _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params) {
1529 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1530 case CRM_Utils_Type
::T_INT
:
1531 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1534 case CRM_Utils_Type
::T_DATE
:
1535 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1536 case CRM_Utils_Type
::T_TIMESTAMP
:
1537 //field is of type date or datetime
1538 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1541 case CRM_Utils_Type
::T_TEXT
:
1542 case CRM_Utils_Type
::T_STRING
:
1543 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1546 case CRM_Utils_Type
::T_MONEY
:
1547 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1549 foreach ((array) $fieldValue as $fieldvalue) {
1550 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1551 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1559 * Validate fields being passed into API.
1561 * This function relies on the getFields function working accurately
1562 * for the given API.
1564 * As of writing only date was implemented.
1566 * @param string $entity
1567 * @param string $action
1568 * @param array $params
1570 * @param array $fields
1571 * Response from getfields all variables are the same as per civicrm_api.
1575 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields) {
1576 //CRM-15792 handle datetime for custom fields below code handles chain api call
1577 $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params)));
1578 if (!empty($chainApikeys) && is_array($chainApikeys)) {
1579 foreach ($chainApikeys as $key => $value) {
1580 if (is_array($params[$key])) {
1581 $chainApiParams = array_intersect_key($fields, $params[$key]);
1582 $customFields = array_fill_keys(array_keys($params[$key]), $key);
1586 $fields = array_intersect_key($fields, $params);
1587 if (!empty($chainApiParams)) {
1588 $fields = array_merge($fields, $chainApiParams);
1590 foreach ($fields as $fieldName => $fieldInfo) {
1591 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1592 case CRM_Utils_Type
::T_INT
:
1593 //field is of type integer
1594 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1597 case CRM_Utils_Type
::T_DATE
:
1598 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1599 case CRM_Utils_Type
::T_TIMESTAMP
:
1600 //field is of type date or datetime
1601 if (!empty($customFields) && array_key_exists($fieldName, $customFields)) {
1602 $dateParams = &$params[$customFields[$fieldName]];
1605 $dateParams = &$params;
1607 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
1610 case CRM_Utils_Type
::T_TEXT
:
1611 case CRM_Utils_Type
::T_STRING
:
1612 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1615 case CRM_Utils_Type
::T_MONEY
:
1616 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1617 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1620 foreach ((array) $fieldValue as $fieldvalue) {
1621 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1622 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1631 * Validate foreign key values of fields being passed into API.
1633 * This function relies on the getFields function working accurately
1634 * for the given API.
1636 * @param string $entity
1637 * @param string $action
1638 * @param array $params
1640 * @param array $fields
1641 * Response from getfields all variables are the same as per civicrm_api.
1645 function _civicrm_api3_validate_foreign_keys($entity, $action, &$params, $fields) {
1646 // intensive checks - usually only called after DB level fail
1647 foreach ($fields as $fieldName => $fieldInfo) {
1648 if (!empty($fieldInfo['FKClassName'])) {
1649 if (!empty($params[$fieldName])) {
1650 foreach ((array) $params[$fieldName] as $fieldValue) {
1651 _civicrm_api3_validate_constraint($fieldValue, $fieldName, $fieldInfo);
1654 elseif (!empty($fieldInfo['required'])) {
1655 throw new Exception("DB Constraint Violation - $fieldName should possibly be marked as mandatory for $entity,$action API. If so, please raise a bug report.");
1658 if (!empty($fieldInfo['api.unique'])) {
1659 $params['entity'] = $entity;
1660 _civicrm_api3_validate_unique_key($params, $fieldName);
1666 * Validate date fields being passed into API.
1668 * It currently converts both unique fields and DB field names to a mysql date.
1669 * @todo - probably the unique field handling & the if exists handling is now done before this
1670 * function is reached in the wrapper - can reduce this code down to assume we
1671 * are only checking the passed in field
1673 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1674 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1676 * @param array $params
1677 * Params from civicrm_api.
1678 * @param string $fieldName
1679 * Uniquename of field being checked.
1680 * @param array $fieldInfo
1681 * Array of fields from getfields function.
1685 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1686 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1687 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1691 if ($fieldValue === 'null' && empty($fieldInfo['api.required'])) {
1692 // This is the wierd & wonderful way PEAR sets null.
1696 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1697 if (!empty($params[$fieldInfo['name']])) {
1698 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1700 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1701 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1705 $params[$fieldName][$op] = $fieldValue;
1708 $params[$fieldName] = $fieldValue;
1713 * Convert date into BAO friendly date.
1715 * We accept 'whatever strtotime accepts'
1717 * @param string $dateValue
1718 * @param string $fieldName
1724 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1725 if (is_array($dateValue)) {
1726 foreach ($dateValue as $key => $value) {
1727 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1731 if (strtotime($dateValue) === FALSE) {
1732 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1734 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1735 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1739 * Validate foreign constraint fields being passed into API.
1741 * @param mixed $fieldValue
1742 * @param string $fieldName
1743 * Uniquename of field being checked.
1744 * @param array $fieldInfo
1745 * Array of fields from getfields function.
1747 * @throws \API_Exception
1749 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1750 $daoName = $fieldInfo['FKClassName'];
1751 $dao = new $daoName();
1752 $dao->id
= $fieldValue;
1754 $dao->selectAdd('id');
1755 if (!$dao->find()) {
1756 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1761 * Validate foreign constraint fields being passed into API.
1763 * @param array $params
1764 * Params from civicrm_api.
1765 * @param string $fieldName
1766 * Uniquename of field being checked.
1770 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1771 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1772 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1775 $existing = civicrm_api($params['entity'], 'get', [
1776 'version' => $params['version'],
1777 $fieldName => $fieldValue,
1779 // an entry already exists for this unique field
1780 if ($existing['count'] == 1) {
1781 // question - could this ever be a security issue?
1782 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1787 * Generic implementation of the "replace" action.
1789 * Replace the old set of entities (matching some given keys) with a new set of
1790 * entities (matching the same keys).
1792 * @note This will verify that 'values' is present, but it does not directly verify
1793 * any other parameters.
1795 * @param string $entity
1797 * @param array $params
1798 * Params from civicrm_api, including:.
1799 * - 'values': an array of records to save
1800 * - all other items: keys which identify new/pre-existing records.
1804 function _civicrm_api3_generic_replace($entity, $params) {
1806 $transaction = new CRM_Core_Transaction();
1808 if (!is_array($params['values'])) {
1809 throw new Exception("Mandatory key(s) missing from params array: values");
1812 // Extract the keys -- somewhat scary, don't think too hard about it
1813 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1815 // Lookup pre-existing records
1816 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1817 if (civicrm_error($preexisting)) {
1818 $transaction->rollback();
1819 return $preexisting;
1822 // Save the new/updated records
1824 foreach ($params['values'] as $replacement) {
1825 // Sugar: Don't force clients to duplicate the 'key' data
1826 $replacement = array_merge($baseParams, $replacement);
1827 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1828 $create = civicrm_api($entity, $action, $replacement);
1829 if (civicrm_error($create)) {
1830 $transaction->rollback();
1833 foreach ($create['values'] as $entity_id => $entity_value) {
1834 $creates[$entity_id] = $entity_value;
1838 // Remove stale records
1839 $staleIDs = array_diff(
1840 array_keys($preexisting['values']),
1841 array_keys($creates)
1843 foreach ($staleIDs as $staleID) {
1844 $delete = civicrm_api($entity, 'delete', [
1845 'version' => $params['version'],
1848 if (civicrm_error($delete)) {
1849 $transaction->rollback();
1854 return civicrm_api3_create_success($creates, $params);
1856 catch (PEAR_Exception
$e) {
1857 $transaction->rollback();
1858 return civicrm_api3_create_error($e->getMessage());
1860 catch (Exception
$e) {
1861 $transaction->rollback();
1862 return civicrm_api3_create_error($e->getMessage());
1867 * Replace base parameters.
1869 * @param array $params
1873 function _civicrm_api3_generic_replace_base_params($params) {
1874 $baseParams = $params;
1875 unset($baseParams['values']);
1876 unset($baseParams['sequential']);
1877 unset($baseParams['options']);
1882 * Returns fields allowable by api.
1885 * String Entity to query.
1886 * @param bool $unique
1887 * Index by unique fields?.
1888 * @param array $params
1892 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = []) {
1900 $dao = _civicrm_api3_get_DAO($entity);
1905 $fields = $d->fields();
1907 foreach ($fields as $name => &$field) {
1908 // Denote as core field
1909 $field['is_core_field'] = TRUE;
1910 // Set html attributes for text fields
1911 if (isset($field['html'])) {
1912 $field['html'] +
= (array) $d::makeAttribute($field);
1916 // replace uniqueNames by the normal names as the key
1917 if (empty($unique)) {
1918 foreach ($fields as $name => &$field) {
1919 //getting rid of unused attributes
1920 foreach ($unsetIfEmpty as $attr) {
1921 if (empty($field[$attr])) {
1922 unset($field[$attr]);
1925 if ($name == $field['name']) {
1928 if (array_key_exists($field['name'], $fields)) {
1929 $field['error'] = 'name conflict';
1930 // it should never happen, but better safe than sorry
1933 $fields[$field['name']] = $field;
1934 $fields[$field['name']]['uniqueName'] = $name;
1935 unset($fields[$name]);
1938 // Translate FKClassName to the corresponding api
1939 foreach ($fields as $name => &$field) {
1940 if (!empty($field['FKClassName'])) {
1941 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1943 $field['FKApiName'] = $FKApi;
1947 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1952 * Return an array of fields for a given entity.
1954 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1957 * @param array $params
1961 function _civicrm_api_get_custom_fields($entity, &$params) {
1962 $entity = _civicrm_api_get_camel_name($entity);
1963 if ($entity == 'Contact') {
1964 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1965 $entity = CRM_Utils_Array
::value('contact_type', $params);
1967 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1970 // we could / should probably test for other subtypes here - e.g. activity_type_id
1971 CRM_Utils_Array
::value('contact_sub_type', $params),
1980 foreach ($customfields as $key => $value) {
1981 // Regular fields have a 'name' property
1982 $value['name'] = 'custom_' . $key;
1983 $value['title'] = $value['label'];
1984 if ($value['data_type'] == 'Date' && CRM_Utils_Array
::value('time_format', $value, 0) > 0) {
1985 $value['data_type'] = 'DateTime';
1987 $value['type'] = CRM_Utils_Array
::value($value['data_type'], CRM_Core_BAO_CustomField
::dataToType());
1988 $ret['custom_' . $key] = $value;
1994 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
1996 * If multiple aliases the last takes precedence
1998 * Function also swaps unique fields for non-unique fields & vice versa.
2000 * @param $apiRequest
2003 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
2004 foreach ($fields as $field => $values) {
2005 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
2006 if (!empty($values['api.aliases'])) {
2007 // if aliased field is not set we try to use field alias
2008 if (!isset($apiRequest['params'][$field])) {
2009 foreach ($values['api.aliases'] as $alias) {
2010 if (isset($apiRequest['params'][$alias])) {
2011 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
2013 //unset original field nb - need to be careful with this as it may bring inconsistencies
2014 // out of the woodwork but will be implementing only as _spec function extended
2015 unset($apiRequest['params'][$alias]);
2019 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
2020 && isset($apiRequest['params'][$values['name']])
2022 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
2023 // note that it would make sense to unset the original field here but tests need to be in place first
2024 if ($field != 'domain_version') {
2025 unset($apiRequest['params'][$values['name']]);
2028 if (!isset($apiRequest['params'][$field])
2030 && $field != $uniqueName
2031 && array_key_exists($uniqueName, $apiRequest['params'])
2033 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
2034 // note that it would make sense to unset the original field here but tests need to be in place first
2041 * Validate integer fields being passed into API.
2043 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
2045 * @param array $params
2046 * Params from civicrm_api.
2047 * @param string $fieldName
2048 * Uniquename of field being checked.
2049 * @param array $fieldInfo
2050 * Array of fields from getfields function.
2051 * @param string $entity
2053 * @throws API_Exception
2055 function _civicrm_api3_validate_integer(&$params, $fieldName, &$fieldInfo, $entity) {
2056 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2057 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2061 if (!empty($fieldValue) ||
$fieldValue === '0' ||
$fieldValue === 0) {
2062 // if value = 'user_contact_id' (or similar), replace value with contact id
2063 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
2064 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
2065 if ('unknown-user' === $realContactId) {
2066 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, ['error_field' => $fieldName, "type" => "integer"]);
2068 elseif (is_numeric($realContactId)) {
2069 $fieldValue = $realContactId;
2071 elseif (is_null($realContactId) && empty($fieldInfo['api.required']) && $fieldValue === 'user_contact_id') {
2072 // If not mandatory this will be OK. If mandatory it should fail.
2076 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2077 $additional_lookup_params = [];
2078 if (strtolower($entity) == 'address' && $fieldName == 'state_province_id') {
2079 $country_id = _civicrm_api3_resolve_country_id($params);
2080 if (!empty($country_id)) {
2081 $additional_lookup_params = ['country_id' => $country_id];
2084 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op, $additional_lookup_params);
2087 // After swapping options, ensure we have an integer(s)
2088 foreach ((array) ($fieldValue) as $value) {
2089 if ($value && !is_numeric($value) && $value !== 'null' && $value !== NULL && !is_array($value)) {
2090 throw new API_Exception("$fieldName is not a valid integer", 2001, ['error_field' => $fieldName, "type" => "integer"]);
2094 // Check our field length
2095 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
2097 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
2098 2100, ['field' => $fieldName, "max_length" => $fieldInfo['maxlength']]
2104 $params[$fieldName][$op] = $fieldValue;
2107 $params[$fieldName] = $fieldValue;
2112 * Helper function to determine country_id given the myriad of values for country_id or country that are supported
2117 function _civicrm_api3_resolve_country_id($params) {
2118 if (!empty($params['country_id'])) {
2119 if (is_numeric($params['country_id'])) {
2120 $country_id = $params['country_id'];
2123 $country = new CRM_Core_DAO_Country();
2124 $country->name
= $params['country_id'];
2125 if (!$country->find(TRUE)) {
2126 $country->name
= NULL;
2127 $country->iso_code
= $params['country_id'];
2128 $country->find(TRUE);
2130 if (!empty($country->id
)) {
2131 $country_id = $country->id
;
2135 elseif (!empty($params['country'])) {
2136 if (is_numeric($params['country'])) {
2137 $country_id = $params['country'];
2140 $country = new CRM_Core_DAO_Country();
2141 $country->name
= $params['country'];
2142 if (!$country->find(TRUE)) {
2143 $country->name
= NULL;
2144 $country->iso_code
= $params['country'];
2145 $country->find(TRUE);
2147 if (!empty($country->id
)) {
2148 $country_id = $country->id
;
2152 return !empty($country_id) ?
$country_id : NULL;
2156 * Determine a contact ID using a string expression.
2158 * @param string $contactIdExpr
2159 * E.g. "user_contact_id" or "@user:username".
2161 * @return int|null|'unknown-user'
2162 * @throws \CRM_Core_Exception
2164 function _civicrm_api3_resolve_contactID($contactIdExpr) {
2165 // If value = 'user_contact_id' replace value with logged in user id.
2166 if ($contactIdExpr == "user_contact_id") {
2167 return CRM_Core_Session
::getLoggedInContactID();
2169 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
2170 $config = CRM_Core_Config
::singleton();
2172 $ufID = $config->userSystem
->getUfId($matches[1]);
2174 return 'unknown-user';
2177 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
2179 return 'unknown-user';
2188 * Validate html (check for scripting attack).
2190 * @param array $params
2191 * @param string $fieldName
2192 * @param array $fieldInfo
2194 * @throws API_Exception
2196 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
2197 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2198 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
2202 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2203 throw new API_Exception('Input contains illegal SCRIPT tag.', ["field" => $fieldName, "error_code" => "xss"]);
2209 * Validate string fields being passed into API.
2211 * @param array $params
2212 * Params from civicrm_api.
2213 * @param string $fieldName
2214 * Uniquename of field being checked.
2215 * @param array $fieldInfo
2216 * Array of fields from getfields function.
2217 * @param string $entity
2219 * @throws API_Exception
2222 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2223 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName, 'String');
2224 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
2228 if (!is_array($fieldValue)) {
2229 $fieldValue = (string) $fieldValue;
2233 foreach ((array) $fieldValue as $key => $value) {
2234 foreach ([$fieldValue, $key, $value] as $input) {
2235 if (!CRM_Utils_Rule
::xssString($input)) {
2236 throw new Exception('Input contains illegal SCRIPT tag.');
2239 if ($fieldName == 'currency') {
2240 //When using IN operator $fieldValue is a array of currency codes
2241 if (!CRM_Utils_Rule
::currencyCode($value)) {
2242 throw new Exception("Currency not a valid code: $currency");
2247 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2248 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op);
2250 // Check our field length
2251 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2252 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2253 2100, ['field' => $fieldName]
2258 $params[$fieldName][$op] = $fieldValue;
2261 $params[$fieldName] = $fieldValue;
2266 * Validate & swap out any pseudoconstants / options.
2268 * @param mixed $fieldValue
2269 * @param string $entity : api entity name
2270 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2271 * @param array $fieldInfo : getfields meta-data
2273 * @param array $additional_lookup_params
2275 * @throws \API_Exception
2277 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo, $op = '=', $additional_lookup_params = []) {
2278 if (in_array($op, ['>', '<', '>=', '<=', 'LIKE', 'NOT LIKE'])) {
2282 $options = CRM_Utils_Array
::value('options', $fieldInfo);
2285 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2286 // We need to get the options from the entity the field relates to.
2287 $entity = $fieldInfo['entity'];
2289 $options_lookup_params = [
2291 'field' => $fieldInfo['name'],
2292 'context' => 'validate',
2294 if (!empty($additional_lookup_params)) {
2295 $options_lookup_params = array_merge($additional_lookup_params, $options_lookup_params);
2297 $options = civicrm_api($entity, 'getoptions', $options_lookup_params);
2299 $options = CRM_Utils_Array
::value('values', $options, []);
2302 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2304 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2305 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
2308 // If passed multiple options, validate each.
2309 if (is_array($fieldValue)) {
2310 foreach ($fieldValue as &$value) {
2311 if (!is_array($value)) {
2312 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName, CRM_Utils_Array
::value('api.required', $fieldInfo));
2315 // TODO: unwrap the call to implodePadded from the conditional and do it always
2316 // need to verify that this is safe and doesn't break anything though.
2317 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2319 CRM_Utils_Array
::implodePadded($fieldValue);
2323 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName, CRM_Utils_Array
::value('api.required', $fieldInfo));
2328 * Validate & swap a single option value for a field.
2330 * @param string $value field value
2331 * @param array $options array of options for this field
2332 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2333 * @param bool $isRequired
2334 * Is this a required field or is 'null' an acceptable option. We allow 'null' last
2335 * in case we have the weird situation of it being a valid option in which case our
2336 * brains will probably explode.
2338 * @throws API_Exception
2340 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName, $isRequired) {
2341 // If option is a key, no need to translate
2342 // or if no options are avaiable for pseudoconstant 'table' property
2343 if (array_key_exists($value, $options) ||
!$options) {
2347 // Hack for Profile formatting fields
2348 if ($fieldName === 'field_name' && (strpos($value, 'formatting') === 0)) {
2352 // Translate value into key
2353 // Cast $value to string to avoid a bug in array_search
2354 $newValue = array_search((string) $value, $options);
2355 if ($newValue !== FALSE) {
2359 // Case-insensitive matching
2360 $newValue = strtolower($value);
2361 $options = array_map("strtolower", $options);
2362 $newValue = array_search($newValue, $options);
2363 if ($newValue === FALSE) {
2364 if ($value === 'null' && !$isRequired) {
2365 // CiviMagic syntax for Nulling out the field - let it through.
2368 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, ['error_field' => $fieldName]);
2374 * Returns the canonical name of a field.
2377 * api entity name (string should already be standardized - no camelCase).
2379 * any variation of a field's name (name, unique_name, api.alias).
2381 * @param string $action
2383 * @return bool|string
2384 * FieldName or FALSE if the field does not exist
2386 function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') {
2390 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2393 if ($fieldName == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
2396 $result = civicrm_api($entity, 'getfields', [
2398 'action' => $action,
2400 $meta = $result['values'];
2401 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2402 $fieldName = $fieldName . '_id';
2404 if (isset($meta[$fieldName])) {
2405 return $meta[$fieldName]['name'];
2407 foreach ($meta as $info) {
2408 if ($fieldName == $info['name'] ||
$fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2409 return $info['name'];
2411 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, [])) !== FALSE) {
2412 return $info['name'];
2415 // Create didn't work, try with get
2416 if ($action == 'create') {
2417 return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get');
2423 * Check if the function is deprecated.
2425 * @param string $entity
2426 * @param array $result
2428 * @return string|array|null
2430 function _civicrm_api3_deprecation_check($entity, $result = []) {
2432 $apiFile = "api/v3/$entity.php";
2433 if (CRM_Utils_File
::isIncludable($apiFile)) {
2434 require_once $apiFile;
2436 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
2437 $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation";
2438 if (function_exists($fnName)) {
2439 return $fnName($result);
2445 * Get the actual field value.
2447 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2448 * So this function returns the actual field value.
2450 * @param array $params
2451 * @param string $fieldName
2452 * @param string $type
2456 function _civicrm_api3_field_value_check(&$params, $fieldName, $type = NULL) {
2457 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2460 if (!empty($fieldValue) && is_array($fieldValue) &&
2461 (array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators()) ||
2462 $type == 'String' && strstr(key($fieldValue), 'EMPTY'))
2464 $op = key($fieldValue);
2465 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2467 return [$fieldValue, $op];
2471 * A generic "get" API based on simple array data. This is comparable to
2472 * _civicrm_api3_basic_get but does not use DAO/BAO. This is useful for
2473 * small/mid-size data loaded from external JSON or XML documents.
2476 * @param array $params
2478 * @param array $records
2479 * List of all records.
2480 * @param string $idCol
2481 * The property which defines the ID of a record
2482 * @param array $filterableFields
2483 * List of filterable fields.
2486 * @throws \API_Exception
2488 function _civicrm_api3_basic_array_get($entity, $params, $records, $idCol, $filterableFields) {
2489 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
2490 // TODO // $sort = CRM_Utils_Array::value('sort', $options, NULL);
2491 $offset = CRM_Utils_Array
::value('offset', $options);
2492 $limit = CRM_Utils_Array
::value('limit', $options);
2497 foreach ($records as $record) {
2498 if ($idCol != 'id') {
2499 $record['id'] = $record[$idCol];
2502 foreach ($params as $k => $v) {
2506 if (in_array($k, $filterableFields) && $record[$k] != $v) {
2512 if ($currentOffset >= $offset) {
2513 $matches[$record[$idCol]] = $record;
2515 if ($limit && count($matches) >= $limit) {
2522 $return = CRM_Utils_Array
::value('return', $options, []);
2523 if (!empty($return)) {
2525 $matches = CRM_Utils_Array
::filterColumns($matches, array_keys($return));
2528 return civicrm_api3_create_success($matches, $params);
2532 * @param string $bao_name
2533 * @param array $params
2534 * @throws \Civi\API\Exception\UnauthorizedException
2536 function _civicrm_api3_check_edit_permissions($bao_name, $params) {
2537 // For lack of something more clever, here's a whitelist of entities whos permissions
2538 // are inherited from a contact record.
2539 // Note, when adding here, also remember to modify _civicrm_api3_permissions()
2540 $contactEntities = [
2541 'CRM_Core_BAO_Email',
2542 'CRM_Core_BAO_Phone',
2543 'CRM_Core_BAO_Address',
2545 'CRM_Core_BAO_Website',
2546 'CRM_Core_BAO_OpenID',
2548 if (!empty($params['check_permissions']) && in_array($bao_name, $contactEntities)) {
2549 $cid = !empty($params['contact_id']) ?
$params['contact_id'] : CRM_Core_DAO
::getFieldValue($bao_name, $params['id'], 'contact_id');
2550 if (!CRM_Contact_BAO_Contact_Permission
::allow($cid, CRM_Core_Permission
::EDIT
)) {
2551 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify contact record');
2557 * Check if an entity has been modified since the last known modified_date
2558 * @param string $modifiedDate Last knowm modified_date
2559 * @param int $id Id of record to check
2560 * @param string $entity API Entity
2563 function _civicrm_api3_compare_timestamps($modifiedDate, $id, $entity) {
2564 $currentDbInfo = civicrm_api3($entity, 'getsingle', ['id' => $id]);
2565 if (strtotime($currentDbInfo['modified_date']) <= strtotime($modifiedDate)) {