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['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 $dao = _civicrm_api3_get_DAO($name);
397 $bao = str_replace("DAO", "BAO", $dao);
398 $file = strtr($bao, '_', '/') . '.php';
399 // Check if this entity actually has a BAO. Fall back on the DAO if not.
400 return stream_resolve_include_path($file) ?
$bao : $dao;
404 * Recursive function to explode value-separated strings into arrays.
408 function _civicrm_api3_separate_values(&$values) {
409 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
410 foreach ($values as $key => & $value) {
411 if (is_array($value)) {
412 _civicrm_api3_separate_values($value);
414 elseif (is_string($value)) {
415 // This is to honor the way case API was originally written.
416 if ($key == 'case_type_id') {
417 $value = trim(str_replace($sp, ',', $value), ',');
419 elseif (strpos($value, $sp) !== FALSE) {
420 $value = explode($sp, trim($value, $sp));
427 * This is a legacy wrapper for api_store_values.
429 * It checks suitable fields using getfields rather than DAO->fields.
431 * Getfields has handling for how to deal with unique names which dao->fields doesn't
433 * Note this is used by BAO type create functions - eg. contribution
435 * @param string $entity
436 * @param array $params
437 * @param array $values
439 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
440 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'create']);
441 $fields = $fields['values'];
442 _civicrm_api3_store_values($fields, $params, $values);
448 * @param array $fields
449 * @param array $params
450 * @param array $values
454 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
457 $keys = array_intersect_key($params, $fields);
458 foreach ($keys as $name => $value) {
459 if ($name !== 'id') {
460 $values[$name] = $value;
468 * Returns field names of the given entity fields.
470 * @param array $fields
471 * Fields array to retrieve the field names for.
474 function _civicrm_api3_field_names($fields) {
476 foreach ($fields as $key => $value) {
477 if (!empty($value['name'])) {
478 $result[] = $value['name'];
485 * Get function for query object api.
487 * The API supports 2 types of get request. The more complex uses the BAO query object.
488 * This is a generic function for those functions that call it
490 * At the moment only called by contact we should extend to contribution &
491 * others that use the query object. Note that this function passes permission information in.
494 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
498 * @param array $params
499 * As passed into api get or getcount function.
500 * @param array $additional_options
501 * Array of options (so we can modify the filter).
502 * @param bool $getCount
503 * Are we just after the count.
505 * This basically correlates to the component.
506 * @param null|array $defaultReturnProperties
507 * Default return properties for the entity
508 * (used if return not set - but don't do that - set return!).
511 * @throws API_Exception
513 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = [], $getCount = NULL, $mode = 1, $defaultReturnProperties = NULL) {
514 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
515 // Convert id to e.g. contact_id
516 if (empty($params[$lowercase_entity . '_id']) && isset($params['id'])) {
517 $params[$lowercase_entity . '_id'] = $params['id'];
519 unset($params['id']);
521 $options = _civicrm_api3_get_options_from_params($params, TRUE);
523 $inputParams = array_merge(
524 CRM_Utils_Array
::value('input_params', $options, []),
525 CRM_Utils_Array
::value('input_params', $additional_options, [])
527 $returnProperties = array_merge(
528 CRM_Utils_Array
::value('return', $options, []),
529 CRM_Utils_Array
::value('return', $additional_options, [])
531 if (empty($returnProperties)) {
532 $returnProperties = $defaultReturnProperties;
534 if (!empty($params['check_permissions'])) {
535 // we will filter query object against getfields
536 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'get']);
537 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
538 $fields['values'][$lowercase_entity . '_id'] = [];
539 $varsToFilter = ['returnProperties', 'inputParams'];
540 foreach ($varsToFilter as $varToFilter) {
541 if (!is_array($
$varToFilter)) {
544 //I was going to throw an exception rather than silently filter out - but
545 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
546 //so we are silently ignoring parts of their request
547 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
548 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
551 $options = array_merge($options, $additional_options);
552 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
553 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
554 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
555 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
559 $returnProperties = NULL;
562 if (substr($sort, 0, 2) == 'id') {
563 $sort = $lowercase_entity . "_" . $sort;
566 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
568 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
570 list($entities) = CRM_Contact_BAO_Query
::apiQuery(
589 * Get dao query object based on input params.
591 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
594 * @param array $params
595 * @param string $mode
596 * @param string $entity
599 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
601 function _civicrm_api3_get_query_object($params, $mode, $entity) {
602 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
603 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
604 $offset = CRM_Utils_Array
::value('offset', $options);
605 $rowCount = CRM_Utils_Array
::value('limit', $options);
606 $inputParams = CRM_Utils_Array
::value('input_params', $options, []);
607 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
608 if (empty($returnProperties)) {
609 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
612 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
613 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
615 empty($params['check_permissions']),
616 TRUE, TRUE, NULL, 'AND', 'NULL', TRUE
618 list($select, $from, $where, $having) = $query->query();
620 $sql = "$select $from $where $having";
623 $sort = CRM_Utils_Type
::escape($sort, 'MysqlOrderBy');
624 $sql .= " ORDER BY $sort ";
626 if (!empty($rowCount)) {
627 $sql .= " LIMIT $offset, $rowCount ";
629 $dao = CRM_Core_DAO
::executeQuery($sql);
630 return [$dao, $query];
634 * Function transfers the filters being passed into the DAO onto the params object.
636 * @deprecated DAO based retrieval is being phased out.
638 * @param CRM_Core_DAO $dao
639 * @param array $params
640 * @param bool $unique
641 * @param array $extraSql
642 * API specific queries eg for event isCurrent would be converted to
643 * $extraSql['where'] = array('civicrm_event' => array('(start_date >= CURDATE() || end_date >= CURDATE())'));
645 * @throws API_Exception
648 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $extraSql = []) {
649 $entity = _civicrm_api_get_entity_name_from_dao($dao);
650 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
651 if (!empty($params[$lowercase_entity . "_id"]) && empty($params['id'])) {
652 //if entity_id is set then treat it as ID (will be overridden by id if set)
653 $params['id'] = $params[$lowercase_entity . "_id"];
655 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
656 $fields = array_intersect(array_keys($allfields), array_keys($params));
658 $options = _civicrm_api3_get_options_from_params($params);
659 //apply options like sort
660 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
662 //accept filters like filter.activity_date_time_high
663 // std is now 'filters' => ..
664 if (strstr(implode(',', array_keys($params)), 'filter')) {
665 if (isset($params['filters']) && is_array($params['filters'])) {
666 foreach ($params['filters'] as $paramkey => $paramvalue) {
667 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
671 foreach ($params as $paramkey => $paramvalue) {
672 if (strstr($paramkey, 'filter')) {
673 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
682 foreach ($fields as $field) {
683 if (is_array($params[$field])) {
684 //get the actual fieldname from db
685 $fieldName = $allfields[$field]['name'];
686 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
687 if (!empty($where)) {
688 $dao->whereAdd($where);
693 $daoFieldName = $allfields[$field]['name'];
694 if (empty($daoFieldName)) {
695 throw new API_Exception("Failed to determine field name for \"$field\"");
697 $dao->{$daoFieldName} = $params[$field];
700 $dao->$field = $params[$field];
704 if (!empty($extraSql['where'])) {
705 foreach ($extraSql['where'] as $table => $sqlWhere) {
706 foreach ($sqlWhere as $where) {
707 $dao->whereAdd($where);
711 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
713 // Ensure 'id' is included.
714 $options['return']['id'] = TRUE;
715 $allfields = _civicrm_api3_get_unique_name_array($dao);
716 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
717 foreach ($returnMatched as $returnValue) {
718 $dao->selectAdd($returnValue);
721 // Not already matched on the field names.
722 $unmatchedFields = array_diff(
723 array_keys($options['return']),
727 $returnUniqueMatched = array_intersect(
729 // But a match for the field keys.
730 array_flip($allfields)
732 foreach ($returnUniqueMatched as $uniqueVal) {
733 $dao->selectAdd($allfields[$uniqueVal]);
736 $dao->setApiFilter($params);
740 * Apply filters (e.g. high, low) to DAO object (prior to find).
742 * @param string $filterField
743 * Field name of filter.
744 * @param string $filterValue
745 * Field value of filter.
749 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
750 if (strstr($filterField, 'high')) {
751 $fieldName = substr($filterField, 0, -5);
752 $dao->whereAdd("($fieldName <= $filterValue )");
754 if (strstr($filterField, 'low')) {
755 $fieldName = substr($filterField, 0, -4);
756 $dao->whereAdd("($fieldName >= $filterValue )");
758 if ($filterField == 'is_current' && $filterValue == 1) {
759 $todayStart = date('Ymd000000', strtotime('now'));
760 $todayEnd = date('Ymd235959', strtotime('now'));
761 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
762 if (property_exists($dao, 'is_active')) {
763 $dao->whereAdd('is_active = 1');
769 * Get sort, limit etc options from the params - supporting old & new formats.
771 * Get returnProperties for legacy
773 * @param array $params
774 * Params array as passed into civicrm_api.
775 * @param bool $queryObject
776 * Is this supporting a queryObject api (e.g contact) - if so we support more options.
777 * for legacy report & return a unique fields array
779 * @param string $entity
780 * @param string $action
782 * @throws API_Exception
784 * options extracted from params
786 function _civicrm_api3_get_options_from_params($params, $queryObject = FALSE, $entity = '', $action = '') {
787 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
789 $sort = CRM_Utils_Array
::value('sort', $params, 0);
790 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
791 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
793 $offset = CRM_Utils_Array
::value('offset', $params, 0);
794 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
795 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
796 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
798 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
799 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
800 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
802 if (is_array(CRM_Utils_Array
::value('options', $params))) {
803 // is count is set by generic getcount not user
804 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
805 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
806 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
807 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
810 $returnProperties = [];
811 // handle the format return =sort_name,display_name...
812 if (array_key_exists('return', $params)) {
813 if (is_array($params['return'])) {
814 $returnProperties = array_fill_keys($params['return'], 1);
817 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
818 $returnProperties = array_fill_keys($returnProperties, 1);
821 if ($entity && $action == 'get') {
822 if (!empty($returnProperties['id'])) {
823 $returnProperties[$lowercase_entity . '_id'] = 1;
824 unset($returnProperties['id']);
829 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
830 'limit' => (!$is_count && CRM_Utils_Rule
::integer($limit)) ?
$limit : NULL,
831 'is_count' => $is_count,
832 'return' => !empty($returnProperties) ?
$returnProperties : [],
836 $options['sort'] = NULL;
838 if (!is_array($sort)) {
839 $sort = array_map('trim', explode(',', $sort));
841 foreach ($sort as $s) {
842 if ($s == '(1)' || CRM_Utils_Rule
::mysqlOrderBy($s)) {
843 if ($entity && $action == 'get') {
844 switch (trim(strtolower($s))) {
848 $s = str_replace('id', $lowercase_entity . '_id', $s);
854 throw new API_Exception("Unknown field specified for sort. Cannot order by '$s'");
857 $options['sort'] = implode(', ', $finalSort);
860 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
861 throw new API_Exception('invalid string in sort options');
867 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
868 // if the query object is being used this should be used
870 $legacyreturnProperties = [];
872 'sort', 'offset', 'rowCount', 'options', 'return',
873 'version', 'prettyprint', 'check_permissions', 'sequential',
875 foreach ($params as $n => $v) {
876 if (substr($n, 0, 7) == 'return.') {
877 $legacyreturnProperties[substr($n, 7)] = $v;
879 elseif ($n == 'id') {
880 $inputParams[$lowercase_entity . '_id'] = $v;
882 elseif (in_array($n, $otherVars)) {
885 $inputParams[$n] = $v;
886 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
887 throw new API_Exception('invalid string');
891 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
892 $options['input_params'] = $inputParams;
897 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
899 * @param array $params
900 * Params array as passed into civicrm_api.
905 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
907 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
908 if (!$options['is_count']) {
909 if (!empty($options['limit'])) {
910 $dao->limit((int) $options['offset'], (int) $options['limit']);
912 if (!empty($options['sort'])) {
913 $options['sort'] = CRM_Utils_Type
::escape($options['sort'], 'MysqlOrderBy');
914 $dao->orderBy($options['sort']);
920 * Build fields array.
922 * This is the array of fields as it relates to the given DAO
923 * returns unique fields as keys by default but if set but can return by DB fields
925 * @param CRM_Core_DAO $bao
926 * @param bool $unique
930 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
931 $fields = $bao->fields();
933 if (empty($fields['id'])) {
934 $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
935 if (isset($fields[$lowercase_entity . '_id'])) {
936 $fields['id'] = $fields[$lowercase_entity . '_id'];
937 unset($fields[$lowercase_entity . '_id']);
943 foreach ($fields as $field) {
944 $dbFields[$field['name']] = $field;
950 * Build fields array.
952 * This is the array of fields as it relates to the given DAO
953 * returns unique fields as keys by default but if set but can return by DB fields
955 * @param CRM_Core_DAO $bao
959 function _civicrm_api3_get_unique_name_array(&$bao) {
960 $fields = $bao->fields();
961 foreach ($fields as $field => $values) {
962 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
964 return $uniqueFields;
968 * Converts an DAO object to an array.
970 * @deprecated - DAO based retrieval is being phased out.
972 * @param CRM_Core_DAO $dao
974 * @param array $params
975 * @param bool $uniqueFields
976 * @param string $entity
977 * @param bool $autoFind
981 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
983 if (isset($params['options']) && !empty($params['options']['is_count'])) {
984 return $dao->count();
989 if ($autoFind && !$dao->find()) {
993 if (isset($dao->count
)) {
997 $fields = array_keys(_civicrm_api3_build_fields_array($dao, FALSE));
998 while ($dao->fetch()) {
1000 foreach ($fields as $key) {
1001 if (array_key_exists($key, $dao)) {
1002 // not sure on that one
1003 if ($dao->$key !== NULL) {
1004 $tmp[$key] = $dao->$key;
1008 $result[$dao->id
] = $tmp;
1010 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
1011 _civicrm_api3_custom_data_get($result[$dao->id
], $params['check_permissions'], $entity, $dao->id
);
1019 * Determine if custom fields need to be retrieved.
1021 * We currently retrieve all custom fields or none at this level so if we know the entity
1022 * && 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
1023 * @todo filter so only required fields are queried
1025 * @param string $entity
1026 * Entity name in CamelCase.
1027 * @param array $params
1031 function _civicrm_api3_custom_fields_are_required($entity, $params) {
1032 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
1035 $options = _civicrm_api3_get_options_from_params($params);
1036 // We check for possibility of 'custom' => 1 as well as specific custom fields.
1037 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
1038 if (stristr($returnString, 'custom')) {
1044 * Converts an object to an array.
1046 * @param object $dao
1047 * (reference) object to convert.
1048 * @param array $values
1049 * (reference) array.
1050 * @param array|bool $uniqueFields
1052 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
1054 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
1055 foreach ($fields as $key => $value) {
1056 if (array_key_exists($key, $dao)) {
1057 $values[$key] = $dao->$key;
1063 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1070 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1071 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1075 * Format custom parameters.
1077 * @param array $params
1078 * @param array $values
1079 * @param string $extends
1080 * Entity that this custom field extends (e.g. contribution, event, contact).
1081 * @param string $entityId
1082 * ID of entity per $extends.
1084 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1085 $values['custom'] = [];
1086 $checkCheckBoxField = FALSE;
1088 if (in_array($extends, ['Household', 'Individual', 'Organization'])) {
1089 $entity = 'Contact';
1092 $fields = civicrm_api($entity, 'getfields', ['version' => 3, 'action' => 'create']);
1093 if (!$fields['is_error']) {
1094 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1095 $fields = $fields['values'];
1096 $checkCheckBoxField = TRUE;
1099 foreach ($params as $key => $value) {
1100 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
1101 if ($customFieldID && (!is_null($value))) {
1102 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1103 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1106 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1107 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1114 * Format parameters for create action.
1116 * @param array $params
1119 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1120 $nonGenericEntities = ['Contact', 'Individual', 'Household', 'Organization'];
1122 $customFieldEntities = array_diff_key(CRM_Core_SelectValues
::customGroupExtends(), array_fill_keys($nonGenericEntities, 1));
1123 if (!array_key_exists($entity, $customFieldEntities)) {
1127 _civicrm_api3_custom_format_params($params, $values, $entity);
1128 $params = array_merge($params, $values);
1132 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1134 * We should look at pushing to BAO function
1135 * 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
1136 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1138 * 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
1139 * don't touch - lots of very cautious code in here
1141 * The resulting array should look like
1147 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1149 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1150 * be fixed in future
1152 * @param mixed $checkboxFieldValue
1153 * @param string $customFieldLabel
1154 * @param string $entity
1156 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1158 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1159 // We can assume it's pre-formatted.
1162 $options = civicrm_api($entity, 'getoptions', ['field' => $customFieldLabel, 'version' => 3]);
1163 if (!empty($options['is_error'])) {
1164 // The check is precautionary - can probably be removed later.
1168 $options = $options['values'];
1170 if (is_array($checkboxFieldValue)) {
1171 foreach ($checkboxFieldValue as $key => $value) {
1172 if (!array_key_exists($key, $options)) {
1173 $validValue = FALSE;
1177 // we have been passed an array that is already in the 'odd' custom field format
1182 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1183 // if the array only has one item we'll treat it like any other string
1184 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1185 $possibleValue = reset($checkboxFieldValue);
1187 if (is_string($checkboxFieldValue)) {
1188 $possibleValue = $checkboxFieldValue;
1190 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1191 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1194 elseif (is_array($checkboxFieldValue)) {
1195 // so this time around we are considering the values in the array
1196 $possibleValues = $checkboxFieldValue;
1197 $formatValue = TRUE;
1199 elseif (stristr($checkboxFieldValue, ',')) {
1200 $formatValue = TRUE;
1201 //lets see if we should separate it - we do this near the end so we
1202 // ensure we have already checked that the comma is not part of a legitimate match
1203 // and of course, we don't make any changes if we don't now have matches
1204 $possibleValues = explode(',', $checkboxFieldValue);
1207 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1211 foreach ($possibleValues as $index => $possibleValue) {
1212 if (array_key_exists($possibleValue, $options)) {
1213 // 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)
1215 elseif (array_key_exists(trim($possibleValue), $options)) {
1216 $possibleValues[$index] = trim($possibleValue);
1219 $formatValue = FALSE;
1223 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1228 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1230 * @param string $bao_name
1232 * @param array $params
1234 * @param bool $returnAsSuccess
1235 * Return in api success format.
1236 * @param string $entity
1237 * @param CRM_Utils_SQL_Select|NULL $sql
1238 * Extra SQL bits to add to the query. For filtering current events, this might be:
1239 * CRM_Utils_SQL_Select::fragment()->where('(start_date >= CURDATE() || end_date >= CURDATE())');
1240 * @param bool $uniqueFields
1241 * Should unique field names be returned (for backward compatibility)
1245 function _civicrm_api3_basic_get($bao_name, $params, $returnAsSuccess = TRUE, $entity = "", $sql = NULL, $uniqueFields = FALSE) {
1246 $entity = $entity ?
: CRM_Core_DAO_AllCoreTables
::getBriefName(str_replace('_BAO_', '_DAO_', $bao_name));
1247 $options = _civicrm_api3_get_options_from_params($params);
1249 $query = new \Civi\API\
Api3SelectQuery($entity, CRM_Utils_Array
::value('check_permissions', $params, FALSE));
1250 $query->where
= $params;
1251 if ($options['is_count']) {
1252 $query->select
= ['count_rows'];
1255 $query->select
= array_keys(array_filter($options['return']));
1256 $query->orderBy
= $options['sort'];
1257 $query->isFillUniqueFields
= $uniqueFields;
1259 $query->limit
= $options['limit'];
1260 $query->offset
= $options['offset'];
1261 $query->merge($sql);
1262 $result = $query->run();
1264 if ($returnAsSuccess) {
1265 return civicrm_api3_create_success($result, $params, $entity, 'get');
1271 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1273 * @param string $bao_name
1274 * Name of BAO Class.
1275 * @param array $params
1276 * Parameters passed into the api call.
1277 * @param string $entity
1278 * Entity - pass in if entity is non-standard & required $ids array.
1280 * @throws API_Exception
1281 * @throws \Civi\API\Exception\UnauthorizedException
1284 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1285 _civicrm_api3_check_edit_permissions($bao_name, $params);
1286 _civicrm_api3_format_params_for_create($params, $entity);
1287 $args = array(&$params);
1289 $ids = [$entity => CRM_Utils_Array
::value('id', $params)];
1293 if (method_exists($bao_name, 'create')) {
1295 $fct_name = $bao_name . '::' . $fct;
1296 $bao = call_user_func_array([$bao_name, $fct], $args);
1298 elseif (method_exists($bao_name, 'add')) {
1300 $fct_name = $bao_name . '::' . $fct;
1301 $bao = call_user_func_array([$bao_name, $fct], $args);
1304 $fct_name = '_civicrm_api3_basic_create_fallback';
1305 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1308 if (is_null($bao)) {
1309 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1311 elseif (is_a($bao, 'CRM_Core_Error')) {
1312 //some weird circular thing means the error takes itself as an argument
1313 $msg = $bao->getMessages($bao);
1314 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1315 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1316 // so we need to reset the error object here to avoid getting concatenated errors
1317 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1318 CRM_Core_Error
::singleton()->reset();
1319 throw new API_Exception($msg);
1322 // If we have custom fields the BAO may have taken care of it or we may have to.
1323 // $extendsMap provides a pretty good hard-coded list of BAOs that take care of the custom data.
1324 if (isset($params['custom']) && empty(CRM_Core_BAO_CustomQuery
::$extendsMap[$entity])) {
1325 CRM_Core_BAO_CustomValueTable
::store($params['custom'], CRM_Core_DAO_AllCoreTables
::getTableForClass(CRM_Core_DAO_AllCoreTables
::getFullName($entity)), $bao->id
);
1328 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1329 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1334 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1336 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1337 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1339 * @param string $bao_name
1340 * @param array $params
1342 * @throws API_Exception
1344 * @return CRM_Core_DAO|NULL
1345 * An instance of the BAO
1347 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1348 $dao_name = get_parent_class($bao_name);
1349 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1350 $dao_name = $bao_name;
1352 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1353 if (empty($entityName)) {
1354 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", [
1355 'class_name' => $bao_name,
1358 $hook = empty($params['id']) ?
'create' : 'edit';
1360 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1361 $instance = new $dao_name();
1362 $instance->copyValues($params, TRUE);
1364 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1370 * Function to do a 'standard' api del.
1372 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1374 * @param string $bao_name
1375 * @param array $params
1379 * @throws API_Exception
1380 * @throws \Civi\API\Exception\UnauthorizedException
1382 function _civicrm_api3_basic_delete($bao_name, &$params) {
1383 civicrm_api3_verify_mandatory($params, NULL, ['id']);
1384 _civicrm_api3_check_edit_permissions($bao_name, ['id' => $params['id']]);
1385 $args = array(&$params['id']);
1386 if (method_exists($bao_name, 'del')) {
1387 $dao = new $bao_name();
1388 $dao->id
= $params['id'];
1390 $bao = call_user_func_array([$bao_name, 'del'], $args);
1391 if ($bao !== FALSE) {
1392 return civicrm_api3_create_success();
1394 throw new API_Exception('Could not delete entity id ' . $params['id']);
1396 throw new API_Exception('Could not delete entity id ' . $params['id']);
1398 elseif (method_exists($bao_name, 'delete')) {
1399 $dao = new $bao_name();
1400 $dao->id
= $params['id'];
1402 while ($dao->fetch()) {
1404 return civicrm_api3_create_success();
1408 throw new API_Exception('Could not delete entity id ' . $params['id']);
1412 throw new API_Exception('no delete method found');
1416 * Get custom data for the given entity & Add it to the returnArray.
1418 * This looks like 'custom_123' = 'custom string' AND
1419 * 'custom_123_1' = 'custom string'
1420 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1422 * @param array $returnArray
1423 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1424 * @param $checkPermission
1425 * @param string $entity
1426 * E.g membership, event.
1427 * @param int $entity_id
1428 * @param int $groupID
1429 * Per CRM_Core_BAO_CustomGroup::getTree.
1430 * @param int $subType
1431 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1432 * @param string $subName
1433 * Subtype of entity.
1435 function _civicrm_api3_custom_data_get(&$returnArray, $checkPermission, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1436 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1447 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1);
1449 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1451 foreach ($groupTree as $set) {
1452 $fieldInfo +
= $set['fields'];
1454 if (!empty($customValues)) {
1455 foreach ($customValues as $key => $val) {
1456 // per standard - return custom_fieldID
1457 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1458 $returnArray['custom_' . $id] = $val;
1460 //not standard - but some api did this so guess we should keep - cheap as chips
1461 $returnArray[$key] = $val;
1463 // Shim to restore legacy behavior of ContactReference custom fields
1464 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1465 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1466 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1473 * Used by the Validate API.
1474 * @param string $entity
1475 * @param string $action
1476 * @param array $params
1478 * @return array $errors
1480 function _civicrm_api3_validate($entity, $action, $params) {
1482 $fields = civicrm_api3($entity, 'getfields', ['sequential' => 1, 'api_action' => $action]);
1483 $fields = $fields['values'];
1485 // Check for required fields.
1486 foreach ($fields as $values) {
1487 if (!empty($values['api.required']) && empty($params[$values['name']])) {
1488 $errors[$values['name']] = [
1489 'message' => "Mandatory key(s) missing from params array: " . $values['name'],
1490 'code' => "mandatory_missing",
1495 // Select only the fields which have been input as a param.
1497 foreach ($fields as $values) {
1498 if (array_key_exists($values['name'], $params)) {
1499 $finalfields[] = $values;
1503 // This derives heavily from the function "_civicrm_api3_validate_fields".
1504 // However, the difference is that try-catch blocks are nested in the loop, making it
1505 // possible for us to get all errors in one go.
1506 foreach ($finalfields as $fieldInfo) {
1507 $fieldName = $fieldInfo['name'];
1509 _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params);
1511 catch (Exception
$e) {
1512 $errors[$fieldName] = [
1513 'message' => $e->getMessage(),
1514 'code' => 'incorrect_value',
1523 * Used by the Validate API.
1525 * @param array $fieldInfo
1526 * @param string $entity
1527 * @param array $params
1529 * @throws API_Exception
1532 function _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params) {
1533 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1534 case CRM_Utils_Type
::T_INT
:
1535 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1538 case CRM_Utils_Type
::T_DATE
:
1539 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1540 case CRM_Utils_Type
::T_TIMESTAMP
:
1541 //field is of type date or datetime
1542 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1545 case CRM_Utils_Type
::T_TEXT
:
1546 case CRM_Utils_Type
::T_STRING
:
1547 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1550 case CRM_Utils_Type
::T_MONEY
:
1551 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1553 foreach ((array) $fieldValue as $fieldvalue) {
1554 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1555 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1563 * Validate fields being passed into API.
1565 * This function relies on the getFields function working accurately
1566 * for the given API.
1568 * As of writing only date was implemented.
1570 * @param string $entity
1571 * @param string $action
1572 * @param array $params
1574 * @param array $fields
1575 * Response from getfields all variables are the same as per civicrm_api.
1579 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields) {
1580 //CRM-15792 handle datetime for custom fields below code handles chain api call
1581 $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params)));
1582 if (!empty($chainApikeys) && is_array($chainApikeys)) {
1583 foreach ($chainApikeys as $key => $value) {
1584 if (is_array($params[$key])) {
1585 $chainApiParams = array_intersect_key($fields, $params[$key]);
1586 $customFields = array_fill_keys(array_keys($params[$key]), $key);
1590 $fields = array_intersect_key($fields, $params);
1591 if (!empty($chainApiParams)) {
1592 $fields = array_merge($fields, $chainApiParams);
1594 foreach ($fields as $fieldName => $fieldInfo) {
1595 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1596 case CRM_Utils_Type
::T_INT
:
1597 //field is of type integer
1598 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1601 case CRM_Utils_Type
::T_DATE
:
1602 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1603 case CRM_Utils_Type
::T_TIMESTAMP
:
1604 //field is of type date or datetime
1605 if (!empty($customFields) && array_key_exists($fieldName, $customFields)) {
1606 $dateParams = &$params[$customFields[$fieldName]];
1609 $dateParams = &$params;
1611 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
1614 case CRM_Utils_Type
::T_TEXT
:
1615 case CRM_Utils_Type
::T_STRING
:
1616 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1619 case CRM_Utils_Type
::T_MONEY
:
1620 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1621 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1624 foreach ((array) $fieldValue as $fieldvalue) {
1625 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1626 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1635 * Validate foreign key values of fields being passed into API.
1637 * This function relies on the getFields function working accurately
1638 * for the given API.
1640 * @param string $entity
1641 * @param string $action
1642 * @param array $params
1644 * @param array $fields
1645 * Response from getfields all variables are the same as per civicrm_api.
1649 function _civicrm_api3_validate_foreign_keys($entity, $action, &$params, $fields) {
1650 // intensive checks - usually only called after DB level fail
1651 foreach ($fields as $fieldName => $fieldInfo) {
1652 if (!empty($fieldInfo['FKClassName'])) {
1653 if (!empty($params[$fieldName])) {
1654 foreach ((array) $params[$fieldName] as $fieldValue) {
1655 _civicrm_api3_validate_constraint($fieldValue, $fieldName, $fieldInfo);
1658 elseif (!empty($fieldInfo['required'])) {
1659 throw new Exception("DB Constraint Violation - $fieldName should possibly be marked as mandatory for $entity,$action API. If so, please raise a bug report.");
1662 if (!empty($fieldInfo['api.unique'])) {
1663 $params['entity'] = $entity;
1664 _civicrm_api3_validate_unique_key($params, $fieldName);
1670 * Validate date fields being passed into API.
1672 * It currently converts both unique fields and DB field names to a mysql date.
1673 * @todo - probably the unique field handling & the if exists handling is now done before this
1674 * function is reached in the wrapper - can reduce this code down to assume we
1675 * are only checking the passed in field
1677 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1678 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1680 * @param array $params
1681 * Params from civicrm_api.
1682 * @param string $fieldName
1683 * Uniquename of field being checked.
1684 * @param array $fieldInfo
1685 * Array of fields from getfields function.
1689 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1690 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1691 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1695 if ($fieldValue === 'null' && empty($fieldInfo['api.required'])) {
1696 // This is the wierd & wonderful way PEAR sets null.
1700 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1701 if (!empty($params[$fieldInfo['name']])) {
1702 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1704 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1705 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1709 $params[$fieldName][$op] = $fieldValue;
1712 $params[$fieldName] = $fieldValue;
1717 * Convert date into BAO friendly date.
1719 * We accept 'whatever strtotime accepts'
1721 * @param string $dateValue
1722 * @param string $fieldName
1728 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1729 if (is_array($dateValue)) {
1730 foreach ($dateValue as $key => $value) {
1731 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1735 if (strtotime($dateValue) === FALSE) {
1736 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1738 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1739 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1743 * Validate foreign constraint fields being passed into API.
1745 * @param mixed $fieldValue
1746 * @param string $fieldName
1747 * Uniquename of field being checked.
1748 * @param array $fieldInfo
1749 * Array of fields from getfields function.
1751 * @throws \API_Exception
1753 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1754 $daoName = $fieldInfo['FKClassName'];
1755 $dao = new $daoName();
1756 $dao->id
= $fieldValue;
1758 $dao->selectAdd('id');
1759 if (!$dao->find()) {
1760 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1765 * Validate foreign constraint fields being passed into API.
1767 * @param array $params
1768 * Params from civicrm_api.
1769 * @param string $fieldName
1770 * Uniquename of field being checked.
1774 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1775 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1776 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1779 $existing = civicrm_api($params['entity'], 'get', [
1780 'version' => $params['version'],
1781 $fieldName => $fieldValue,
1783 // an entry already exists for this unique field
1784 if ($existing['count'] == 1) {
1785 // question - could this ever be a security issue?
1786 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1791 * Generic implementation of the "replace" action.
1793 * Replace the old set of entities (matching some given keys) with a new set of
1794 * entities (matching the same keys).
1796 * @note This will verify that 'values' is present, but it does not directly verify
1797 * any other parameters.
1799 * @param string $entity
1801 * @param array $params
1802 * Params from civicrm_api, including:.
1803 * - 'values': an array of records to save
1804 * - all other items: keys which identify new/pre-existing records.
1808 function _civicrm_api3_generic_replace($entity, $params) {
1810 $transaction = new CRM_Core_Transaction();
1812 if (!is_array($params['values'])) {
1813 throw new Exception("Mandatory key(s) missing from params array: values");
1816 // Extract the keys -- somewhat scary, don't think too hard about it
1817 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1819 // Lookup pre-existing records
1820 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1821 if (civicrm_error($preexisting)) {
1822 $transaction->rollback();
1823 return $preexisting;
1826 // Save the new/updated records
1828 foreach ($params['values'] as $replacement) {
1829 // Sugar: Don't force clients to duplicate the 'key' data
1830 $replacement = array_merge($baseParams, $replacement);
1831 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1832 $create = civicrm_api($entity, $action, $replacement);
1833 if (civicrm_error($create)) {
1834 $transaction->rollback();
1837 foreach ($create['values'] as $entity_id => $entity_value) {
1838 $creates[$entity_id] = $entity_value;
1842 // Remove stale records
1843 $staleIDs = array_diff(
1844 array_keys($preexisting['values']),
1845 array_keys($creates)
1847 foreach ($staleIDs as $staleID) {
1848 $delete = civicrm_api($entity, 'delete', [
1849 'version' => $params['version'],
1852 if (civicrm_error($delete)) {
1853 $transaction->rollback();
1858 return civicrm_api3_create_success($creates, $params);
1860 catch (PEAR_Exception
$e) {
1861 $transaction->rollback();
1862 return civicrm_api3_create_error($e->getMessage());
1864 catch (Exception
$e) {
1865 $transaction->rollback();
1866 return civicrm_api3_create_error($e->getMessage());
1871 * Replace base parameters.
1873 * @param array $params
1877 function _civicrm_api3_generic_replace_base_params($params) {
1878 $baseParams = $params;
1879 unset($baseParams['values']);
1880 unset($baseParams['sequential']);
1881 unset($baseParams['options']);
1886 * Returns fields allowable by api.
1889 * String Entity to query.
1890 * @param bool $unique
1891 * Index by unique fields?.
1892 * @param array $params
1896 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = []) {
1904 $dao = _civicrm_api3_get_DAO($entity);
1909 $fields = $d->fields();
1911 foreach ($fields as $name => &$field) {
1912 // Denote as core field
1913 $field['is_core_field'] = TRUE;
1914 // Set html attributes for text fields
1915 if (isset($field['html'])) {
1916 $field['html'] +
= (array) $d::makeAttribute($field);
1920 // replace uniqueNames by the normal names as the key
1921 if (empty($unique)) {
1922 foreach ($fields as $name => &$field) {
1923 //getting rid of unused attributes
1924 foreach ($unsetIfEmpty as $attr) {
1925 if (empty($field[$attr])) {
1926 unset($field[$attr]);
1929 if ($name == $field['name']) {
1932 if (array_key_exists($field['name'], $fields)) {
1933 $field['error'] = 'name conflict';
1934 // it should never happen, but better safe than sorry
1937 $fields[$field['name']] = $field;
1938 $fields[$field['name']]['uniqueName'] = $name;
1939 unset($fields[$name]);
1942 // Translate FKClassName to the corresponding api
1943 foreach ($fields as $name => &$field) {
1944 if (!empty($field['FKClassName'])) {
1945 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1947 $field['FKApiName'] = $FKApi;
1951 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1956 * Return an array of fields for a given entity.
1958 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1961 * @param array $params
1965 function _civicrm_api_get_custom_fields($entity, &$params) {
1966 $entity = _civicrm_api_get_camel_name($entity);
1967 if ($entity == 'Contact') {
1968 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1969 $entity = CRM_Utils_Array
::value('contact_type', $params);
1971 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1974 // we could / should probably test for other subtypes here - e.g. activity_type_id
1975 CRM_Utils_Array
::value('contact_sub_type', $params),
1984 foreach ($customfields as $key => $value) {
1985 // Regular fields have a 'name' property
1986 $value['name'] = 'custom_' . $key;
1987 $value['title'] = $value['label'];
1988 if ($value['data_type'] == 'Date' && CRM_Utils_Array
::value('time_format', $value, 0) > 0) {
1989 $value['data_type'] = 'DateTime';
1991 $value['type'] = CRM_Utils_Array
::value($value['data_type'], CRM_Core_BAO_CustomField
::dataToType());
1992 $ret['custom_' . $key] = $value;
1998 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
2000 * If multiple aliases the last takes precedence
2002 * Function also swaps unique fields for non-unique fields & vice versa.
2004 * @param $apiRequest
2007 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
2008 foreach ($fields as $field => $values) {
2009 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
2010 if (!empty($values['api.aliases'])) {
2011 // if aliased field is not set we try to use field alias
2012 if (!isset($apiRequest['params'][$field])) {
2013 foreach ($values['api.aliases'] as $alias) {
2014 if (isset($apiRequest['params'][$alias])) {
2015 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
2017 //unset original field nb - need to be careful with this as it may bring inconsistencies
2018 // out of the woodwork but will be implementing only as _spec function extended
2019 unset($apiRequest['params'][$alias]);
2023 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
2024 && isset($apiRequest['params'][$values['name']])
2026 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
2027 // note that it would make sense to unset the original field here but tests need to be in place first
2028 if ($field != 'domain_version') {
2029 unset($apiRequest['params'][$values['name']]);
2032 if (!isset($apiRequest['params'][$field])
2034 && $field != $uniqueName
2035 && array_key_exists($uniqueName, $apiRequest['params'])
2037 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
2038 // note that it would make sense to unset the original field here but tests need to be in place first
2045 * Validate integer fields being passed into API.
2047 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
2049 * @param array $params
2050 * Params from civicrm_api.
2051 * @param string $fieldName
2052 * Uniquename of field being checked.
2053 * @param array $fieldInfo
2054 * Array of fields from getfields function.
2055 * @param string $entity
2057 * @throws API_Exception
2059 function _civicrm_api3_validate_integer(&$params, $fieldName, &$fieldInfo, $entity) {
2060 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2061 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2065 if (!empty($fieldValue) ||
$fieldValue === '0' ||
$fieldValue === 0) {
2066 // if value = 'user_contact_id' (or similar), replace value with contact id
2067 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
2068 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
2069 if ('unknown-user' === $realContactId) {
2070 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, ['error_field' => $fieldName, "type" => "integer"]);
2072 elseif (is_numeric($realContactId)) {
2073 $fieldValue = $realContactId;
2075 elseif (is_null($realContactId) && empty($fieldInfo['api.required']) && $fieldValue === 'user_contact_id') {
2076 // If not mandatory this will be OK. If mandatory it should fail.
2080 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2081 $additional_lookup_params = [];
2082 if (strtolower($entity) == 'address' && $fieldName == 'state_province_id') {
2083 $country_id = _civicrm_api3_resolve_country_id($params);
2084 if (!empty($country_id)) {
2085 $additional_lookup_params = ['country_id' => $country_id];
2088 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op, $additional_lookup_params);
2091 // After swapping options, ensure we have an integer(s)
2092 foreach ((array) ($fieldValue) as $value) {
2093 if ($value && !is_numeric($value) && $value !== 'null' && $value !== NULL && !is_array($value)) {
2094 throw new API_Exception("$fieldName is not a valid integer", 2001, ['error_field' => $fieldName, "type" => "integer"]);
2098 // Check our field length
2099 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
2101 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
2102 2100, ['field' => $fieldName, "max_length" => $fieldInfo['maxlength']]
2108 $params[$fieldName][$op] = $fieldValue;
2111 $params[$fieldName] = $fieldValue;
2116 * Helper function to determine country_id given the myriad of values for country_id or country that are supported
2121 function _civicrm_api3_resolve_country_id($params) {
2122 if (!empty($params['country_id'])) {
2123 if (is_numeric($params['country_id'])) {
2124 $country_id = $params['country_id'];
2127 $country = new CRM_Core_DAO_Country();
2128 $country->name
= $params['country_id'];
2129 if (!$country->find(TRUE)) {
2130 $country->name
= NULL;
2131 $country->iso_code
= $params['country_id'];
2132 $country->find(TRUE);
2134 if (!empty($country->id
)) {
2135 $country_id = $country->id
;
2139 elseif (!empty($params['country'])) {
2140 if (is_numeric($params['country'])) {
2141 $country_id = $params['country'];
2144 $country = new CRM_Core_DAO_Country();
2145 $country->name
= $params['country'];
2146 if (!$country->find(TRUE)) {
2147 $country->name
= NULL;
2148 $country->iso_code
= $params['country'];
2149 $country->find(TRUE);
2151 if (!empty($country->id
)) {
2152 $country_id = $country->id
;
2156 return !empty($country_id) ?
$country_id : NULL;
2160 * Determine a contact ID using a string expression.
2162 * @param string $contactIdExpr
2163 * E.g. "user_contact_id" or "@user:username".
2165 * @return int|null|'unknown-user'
2166 * @throws \CRM_Core_Exception
2168 function _civicrm_api3_resolve_contactID($contactIdExpr) {
2169 // If value = 'user_contact_id' replace value with logged in user id.
2170 if ($contactIdExpr == "user_contact_id") {
2171 return CRM_Core_Session
::getLoggedInContactID();
2173 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
2174 $config = CRM_Core_Config
::singleton();
2176 $ufID = $config->userSystem
->getUfId($matches[1]);
2178 return 'unknown-user';
2181 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
2183 return 'unknown-user';
2192 * Validate html (check for scripting attack).
2194 * @param array $params
2195 * @param string $fieldName
2196 * @param array $fieldInfo
2198 * @throws API_Exception
2200 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
2201 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2202 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
2206 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2207 throw new API_Exception('Input contains illegal SCRIPT tag.', ["field" => $fieldName, "error_code" => "xss"]);
2213 * Validate string fields being passed into API.
2215 * @param array $params
2216 * Params from civicrm_api.
2217 * @param string $fieldName
2218 * Uniquename of field being checked.
2219 * @param array $fieldInfo
2220 * Array of fields from getfields function.
2221 * @param string $entity
2223 * @throws API_Exception
2226 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2227 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName, 'String');
2228 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
2232 if (!is_array($fieldValue)) {
2233 $fieldValue = (string) $fieldValue;
2237 foreach ((array) $fieldValue as $key => $value) {
2238 foreach ([$fieldValue, $key, $value] as $input) {
2239 if (!CRM_Utils_Rule
::xssString($input)) {
2240 throw new Exception('Input contains illegal SCRIPT tag.');
2243 if ($fieldName == 'currency') {
2244 //When using IN operator $fieldValue is a array of currency codes
2245 if (!CRM_Utils_Rule
::currencyCode($value)) {
2246 throw new Exception("Currency not a valid code: $currency");
2251 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2252 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op);
2254 // Check our field length
2255 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2256 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2257 2100, ['field' => $fieldName]
2262 $params[$fieldName][$op] = $fieldValue;
2265 $params[$fieldName] = $fieldValue;
2270 * Validate & swap out any pseudoconstants / options.
2272 * @param mixed $fieldValue
2273 * @param string $entity : api entity name
2274 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2275 * @param array $fieldInfo : getfields meta-data
2277 * @param array $additional_lookup_params
2279 * @throws \API_Exception
2281 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo, $op = '=', $additional_lookup_params = []) {
2282 if (in_array($op, ['>', '<', '>=', '<=', 'LIKE', 'NOT LIKE'])) {
2286 $options = CRM_Utils_Array
::value('options', $fieldInfo);
2289 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2290 // We need to get the options from the entity the field relates to.
2291 $entity = $fieldInfo['entity'];
2293 $options_lookup_params = [
2295 'field' => $fieldInfo['name'],
2296 'context' => 'validate',
2298 if (!empty($additional_lookup_params)) {
2299 $options_lookup_params = array_merge($additional_lookup_params, $options_lookup_params);
2301 $options = civicrm_api($entity, 'getoptions', $options_lookup_params);
2303 $options = CRM_Utils_Array
::value('values', $options, []);
2306 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2308 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2309 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
2312 // If passed multiple options, validate each.
2313 if (is_array($fieldValue)) {
2314 foreach ($fieldValue as &$value) {
2315 if (!is_array($value)) {
2316 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName, CRM_Utils_Array
::value('api.required', $fieldInfo));
2319 // TODO: unwrap the call to implodePadded from the conditional and do it always
2320 // need to verify that this is safe and doesn't break anything though.
2321 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2323 CRM_Utils_Array
::implodePadded($fieldValue);
2327 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName, CRM_Utils_Array
::value('api.required', $fieldInfo));
2332 * Validate & swap a single option value for a field.
2334 * @param string $value field value
2335 * @param array $options array of options for this field
2336 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2337 * @param bool $isRequired
2338 * Is this a required field or is 'null' an acceptable option. We allow 'null' last
2339 * in case we have the weird situation of it being a valid option in which case our
2340 * brains will probably explode.
2342 * @throws API_Exception
2344 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName, $isRequired) {
2345 // If option is a key, no need to translate
2346 // or if no options are avaiable for pseudoconstant 'table' property
2347 if (array_key_exists($value, $options) ||
!$options) {
2351 // Hack for Profile formatting fields
2352 if ($fieldName === 'field_name' && (strpos($value, 'formatting') === 0)) {
2356 // Translate value into key
2357 // Cast $value to string to avoid a bug in array_search
2358 $newValue = array_search((string) $value, $options);
2359 if ($newValue !== FALSE) {
2363 // Case-insensitive matching
2364 $newValue = strtolower($value);
2365 $options = array_map("strtolower", $options);
2366 $newValue = array_search($newValue, $options);
2367 if ($newValue === FALSE) {
2368 if ($value === 'null' && !$isRequired) {
2369 // CiviMagic syntax for Nulling out the field - let it through.
2372 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, ['error_field' => $fieldName]);
2378 * Returns the canonical name of a field.
2381 * api entity name (string should already be standardized - no camelCase).
2383 * any variation of a field's name (name, unique_name, api.alias).
2385 * @param string $action
2387 * @return bool|string
2388 * FieldName or FALSE if the field does not exist
2390 function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') {
2394 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2397 if ($fieldName == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
2400 $result = civicrm_api($entity, 'getfields', [
2402 'action' => $action,
2404 $meta = $result['values'];
2405 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2406 $fieldName = $fieldName . '_id';
2408 if (isset($meta[$fieldName])) {
2409 return $meta[$fieldName]['name'];
2411 foreach ($meta as $info) {
2412 if ($fieldName == $info['name'] ||
$fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2413 return $info['name'];
2415 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, [])) !== FALSE) {
2416 return $info['name'];
2419 // Create didn't work, try with get
2420 if ($action == 'create') {
2421 return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get');
2427 * Check if the function is deprecated.
2429 * @param string $entity
2430 * @param array $result
2432 * @return string|array|null
2434 function _civicrm_api3_deprecation_check($entity, $result = []) {
2436 $apiFile = "api/v3/$entity.php";
2437 if (CRM_Utils_File
::isIncludable($apiFile)) {
2438 require_once $apiFile;
2440 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
2441 $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation";
2442 if (function_exists($fnName)) {
2443 return $fnName($result);
2449 * Get the actual field value.
2451 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2452 * So this function returns the actual field value.
2454 * @param array $params
2455 * @param string $fieldName
2456 * @param string $type
2460 function _civicrm_api3_field_value_check(&$params, $fieldName, $type = NULL) {
2461 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2464 if (!empty($fieldValue) && is_array($fieldValue) &&
2465 (array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators()) ||
2466 $type == 'String' && strstr(key($fieldValue), 'EMPTY'))
2468 $op = key($fieldValue);
2469 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2471 return [$fieldValue, $op];
2475 * A generic "get" API based on simple array data. This is comparable to
2476 * _civicrm_api3_basic_get but does not use DAO/BAO. This is useful for
2477 * small/mid-size data loaded from external JSON or XML documents.
2480 * @param array $params
2482 * @param array $records
2483 * List of all records.
2484 * @param string $idCol
2485 * The property which defines the ID of a record
2486 * @param array $filterableFields
2487 * List of filterable fields.
2490 * @throws \API_Exception
2492 function _civicrm_api3_basic_array_get($entity, $params, $records, $idCol, $filterableFields) {
2493 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
2494 // TODO // $sort = CRM_Utils_Array::value('sort', $options, NULL);
2495 $offset = CRM_Utils_Array
::value('offset', $options);
2496 $limit = CRM_Utils_Array
::value('limit', $options);
2501 foreach ($records as $record) {
2502 if ($idCol != 'id') {
2503 $record['id'] = $record[$idCol];
2506 foreach ($params as $k => $v) {
2510 if (in_array($k, $filterableFields) && $record[$k] != $v) {
2516 if ($currentOffset >= $offset) {
2517 $matches[$record[$idCol]] = $record;
2519 if ($limit && count($matches) >= $limit) {
2526 $return = CRM_Utils_Array
::value('return', $options, []);
2527 if (!empty($return)) {
2529 $matches = CRM_Utils_Array
::filterColumns($matches, array_keys($return));
2532 return civicrm_api3_create_success($matches, $params);
2536 * @param string $bao_name
2537 * @param array $params
2538 * @throws \Civi\API\Exception\UnauthorizedException
2540 function _civicrm_api3_check_edit_permissions($bao_name, $params) {
2541 // For lack of something more clever, here's a whitelist of entities whos permissions
2542 // are inherited from a contact record.
2543 // Note, when adding here, also remember to modify _civicrm_api3_permissions()
2544 $contactEntities = [
2545 'CRM_Core_BAO_Email',
2546 'CRM_Core_BAO_Phone',
2547 'CRM_Core_BAO_Address',
2549 'CRM_Core_BAO_Website',
2550 'CRM_Core_BAO_OpenID',
2552 if (!empty($params['check_permissions']) && in_array($bao_name, $contactEntities)) {
2553 $cid = !empty($params['contact_id']) ?
$params['contact_id'] : CRM_Core_DAO
::getFieldValue($bao_name, $params['id'], 'contact_id');
2554 if (!CRM_Contact_BAO_Contact_Permission
::allow($cid, CRM_Core_Permission
::EDIT
)) {
2555 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify contact record');
2561 * Check if an entity has been modified since the last known modified_date
2562 * @param string $modifiedDate Last knowm modified_date
2563 * @param int $id Id of record to check
2564 * @param string $entity API Entity
2567 function _civicrm_api3_compare_timestamps($modifiedDate, $id, $entity) {
2568 $currentDbInfo = civicrm_api3($entity, 'getsingle', ['id' => $id]);
2569 if (strtotime($currentDbInfo['modified_date']) <= strtotime($modifiedDate)) {