3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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 = array()) {
54 $keys = array(array());
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 = array(), $verifyDAO = TRUE) {
77 if (!empty($params['id'])) {
78 $keys = array('version');
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", array("fields" => $unmatched));
117 * Create error array.
124 function civicrm_api3_create_error($msg, $data = array()) {
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 = array(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
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', array('version' => 3, 'action' => $action) +
$params);
187 elseif ($action != 'getfields') {
188 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
194 $allFields = array();
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), array(
218 $result['undefined_fields'] = array_merge($undefined);
221 if (is_object($dao)) {
225 $result['version'] = 3;
226 if (is_array($values)) {
227 $result['count'] = (int) count($values);
229 // Convert value-separated strings to array
230 if ($action != 'getfields') {
231 _civicrm_api3_separate_values($values);
234 if ($result['count'] == 1) {
235 list($result['id']) = array_keys($values);
237 elseif (!empty($values['id']) && is_int($values['id'])) {
238 $result['id'] = $values['id'];
242 $result['count'] = !empty($values) ?
1 : 0;
245 if (is_array($values) && isset($params['sequential']) &&
246 $params['sequential'] == 1
248 $result['values'] = array_values($values);
251 $result['values'] = $values;
253 if (!empty($params['options']['metadata'])) {
254 // We've made metadata an array but only supporting 'fields' atm.
255 if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
256 $fields = civicrm_api3($entity, 'getfields', array(
257 'action' => substr($action, 0, 3) == 'get' ?
'get' : 'create',
259 $result['metadata']['fields'] = $fields['values'];
262 // Report deprecations.
263 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
264 // Always report "setvalue" action as deprecated.
265 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'setvalue')) {
266 $deprecated = ((array) $deprecated) +
array('setvalue' => 'The "setvalue" action is deprecated. Use "create" with an id instead.');
268 // Always report "update" action as deprecated.
269 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'update')) {
270 $deprecated = ((array) $deprecated) +
array('update' => 'The "update" action is deprecated. Use "create" with an id instead.');
273 // Metadata-level deprecations or wholesale entity deprecations.
274 if ($entity == 'Entity' ||
$action == 'getactions' ||
is_string($deprecated)) {
275 $result['deprecated'] = $deprecated;
277 // Action-specific deprecations
278 elseif (!empty($deprecated[$action])) {
279 $result['deprecated'] = $deprecated[$action];
282 return array_merge($result, $extraReturnValues);
286 * Load the DAO of the entity.
292 function _civicrm_api3_load_DAO($entity) {
293 $dao = _civicrm_api3_get_DAO($entity);
302 * Return the DAO of the function or Entity.
304 * @param string $name
305 * Either a function of the api (civicrm_{entity}_create or the entity name.
306 * return the DAO name to manipulate this function
307 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
309 * @return mixed|string
311 function _civicrm_api3_get_DAO($name) {
312 if (strpos($name, 'civicrm_api3') !== FALSE) {
313 $last = strrpos($name, '_');
314 // len ('civicrm_api3_') == 13
315 $name = substr($name, 13, $last - 13);
318 $name = _civicrm_api_get_camel_name($name);
320 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
324 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
326 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
327 if ($name == 'MailingEventQueue') {
328 return 'CRM_Mailing_Event_DAO_Queue';
330 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
331 // but am not confident mailing_recipients is tested so have not tackled.
332 if ($name == 'MailingRecipients') {
333 return 'CRM_Mailing_DAO_Recipients';
335 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
336 if ($name == 'MailingComponent') {
337 return 'CRM_Mailing_DAO_Component';
339 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
340 if ($name == 'AclRole') {
341 return 'CRM_ACL_DAO_EntityRole';
343 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
344 // But this would impact SMS extensions so need to coordinate
345 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
346 if ($name == 'SmsProvider') {
347 return 'CRM_SMS_DAO_Provider';
349 // FIXME: DAO names should follow CamelCase convention
350 if ($name == 'Im' ||
$name == 'Acl' ||
$name == 'Pcp') {
351 $name = strtoupper($name);
353 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
354 if ($dao ||
!$name) {
358 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
359 if (file_exists("api/v3/$name.php")) {
360 include_once "api/v3/$name.php";
363 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
364 if (function_exists($daoFn)) {
372 * Return the BAO name of the function or Entity.
374 * @param string $name
375 * Is either a function of the api (civicrm_{entity}_create or the entity name.
376 * return the DAO name to manipulate this function
377 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
379 * @return string|null
381 function _civicrm_api3_get_BAO($name) {
382 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
383 if ($name == 'PrintLabel') {
384 return 'CRM_Badge_BAO_Layout';
386 $dao = _civicrm_api3_get_DAO($name);
390 $bao = str_replace("DAO", "BAO", $dao);
391 $file = strtr($bao, '_', '/') . '.php';
392 // Check if this entity actually has a BAO. Fall back on the DAO if not.
393 return stream_resolve_include_path($file) ?
$bao : $dao;
397 * Recursive function to explode value-separated strings into arrays.
401 function _civicrm_api3_separate_values(&$values) {
402 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
403 foreach ($values as $key => & $value) {
404 if (is_array($value)) {
405 _civicrm_api3_separate_values($value);
407 elseif (is_string($value)) {
408 // This is to honor the way case API was originally written.
409 if ($key == 'case_type_id') {
410 $value = trim(str_replace($sp, ',', $value), ',');
412 elseif (strpos($value, $sp) !== FALSE) {
413 $value = explode($sp, trim($value, $sp));
420 * This is a legacy wrapper for api_store_values.
422 * It checks suitable fields using getfields rather than DAO->fields.
424 * Getfields has handling for how to deal with unique names which dao->fields doesn't
426 * Note this is used by BAO type create functions - eg. contribution
428 * @param string $entity
429 * @param array $params
430 * @param array $values
432 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
433 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
434 $fields = $fields['values'];
435 _civicrm_api3_store_values($fields, $params, $values);
440 * @param array $fields
441 * @param array $params
442 * @param array $values
446 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
449 $keys = array_intersect_key($params, $fields);
450 foreach ($keys as $name => $value) {
451 if ($name !== 'id') {
452 $values[$name] = $value;
460 * Returns field names of the given entity fields.
462 * @param array $fields
463 * Fields array to retrieve the field names for.
466 function _civicrm_api3_field_names($fields) {
468 foreach ($fields as $key => $value) {
469 if (!empty($value['name'])) {
470 $result[] = $value['name'];
477 * Get function for query object api.
479 * The API supports 2 types of get request. The more complex uses the BAO query object.
480 * This is a generic function for those functions that call it
482 * At the moment only called by contact we should extend to contribution &
483 * others that use the query object. Note that this function passes permission information in.
486 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
490 * @param array $params
491 * As passed into api get or getcount function.
492 * @param array $additional_options
493 * Array of options (so we can modify the filter).
494 * @param bool $getCount
495 * Are we just after the count.
497 * This basically correlates to the component.
498 * @param null|array $defaultReturnProperties
499 * Default return properties for the entity
500 * (used if return not set - but don't do that - set return!).
503 * @throws API_Exception
505 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL, $mode = 1, $defaultReturnProperties = NULL) {
506 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
507 // Convert id to e.g. contact_id
508 if (empty($params[$lowercase_entity . '_id']) && isset($params['id'])) {
509 $params[$lowercase_entity . '_id'] = $params['id'];
511 unset($params['id']);
513 $options = _civicrm_api3_get_options_from_params($params, TRUE);
515 $inputParams = array_merge(
516 CRM_Utils_Array
::value('input_params', $options, array()),
517 CRM_Utils_Array
::value('input_params', $additional_options, array())
519 $returnProperties = array_merge(
520 CRM_Utils_Array
::value('return', $options, array()),
521 CRM_Utils_Array
::value('return', $additional_options, array())
523 if (empty($returnProperties)) {
524 $returnProperties = $defaultReturnProperties;
526 if (!empty($params['check_permissions'])) {
527 // we will filter query object against getfields
528 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
529 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
530 $fields['values'][$lowercase_entity . '_id'] = array();
531 $varsToFilter = array('returnProperties', 'inputParams');
532 foreach ($varsToFilter as $varToFilter) {
533 if (!is_array($
$varToFilter)) {
536 //I was going to throw an exception rather than silently filter out - but
537 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
538 //so we are silently ignoring parts of their request
539 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
540 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
543 $options = array_merge($options, $additional_options);
544 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
545 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
546 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
547 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
551 $returnProperties = NULL;
554 if (substr($sort, 0, 2) == 'id') {
555 $sort = $lowercase_entity . "_" . $sort;
558 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
560 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
562 list($entities) = CRM_Contact_BAO_Query
::apiQuery(
580 * Get dao query object based on input params.
582 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
585 * @param array $params
586 * @param string $mode
587 * @param string $entity
590 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
592 function _civicrm_api3_get_query_object($params, $mode, $entity) {
593 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
594 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
595 $offset = CRM_Utils_Array
::value('offset', $options);
596 $rowCount = CRM_Utils_Array
::value('limit', $options);
597 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
598 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
599 if (empty($returnProperties)) {
600 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
603 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
604 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
606 empty($params['check_permissions'])
608 list($select, $from, $where, $having) = $query->query();
610 $sql = "$select $from $where $having";
613 $sort = CRM_Utils_Type
::escape($sort, 'MysqlOrderBy');
614 $sql .= " ORDER BY $sort ";
616 if (!empty($rowCount)) {
617 $sql .= " LIMIT $offset, $rowCount ";
619 $dao = CRM_Core_DAO
::executeQuery($sql);
620 return array($dao, $query);
624 * Function transfers the filters being passed into the DAO onto the params object.
626 * @deprecated DAO based retrieval is being phased out.
628 * @param CRM_Core_DAO $dao
629 * @param array $params
630 * @param bool $unique
631 * @param array $extraSql
632 * API specific queries eg for event isCurrent would be converted to
633 * $extraSql['where'] = array('civicrm_event' => array('(start_date >= CURDATE() || end_date >= CURDATE())'));
635 * @throws API_Exception
638 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $extraSql = array()) {
639 $entity = _civicrm_api_get_entity_name_from_dao($dao);
640 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
641 if (!empty($params[$lowercase_entity . "_id"]) && empty($params['id'])) {
642 //if entity_id is set then treat it as ID (will be overridden by id if set)
643 $params['id'] = $params[$lowercase_entity . "_id"];
645 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
646 $fields = array_intersect(array_keys($allfields), array_keys($params));
648 $options = _civicrm_api3_get_options_from_params($params);
649 //apply options like sort
650 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
652 //accept filters like filter.activity_date_time_high
653 // std is now 'filters' => ..
654 if (strstr(implode(',', array_keys($params)), 'filter')) {
655 if (isset($params['filters']) && is_array($params['filters'])) {
656 foreach ($params['filters'] as $paramkey => $paramvalue) {
657 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
661 foreach ($params as $paramkey => $paramvalue) {
662 if (strstr($paramkey, 'filter')) {
663 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
672 foreach ($fields as $field) {
673 if (is_array($params[$field])) {
674 //get the actual fieldname from db
675 $fieldName = $allfields[$field]['name'];
676 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
677 if (!empty($where)) {
678 $dao->whereAdd($where);
683 $daoFieldName = $allfields[$field]['name'];
684 if (empty($daoFieldName)) {
685 throw new API_Exception("Failed to determine field name for \"$field\"");
687 $dao->{$daoFieldName} = $params[$field];
690 $dao->$field = $params[$field];
694 if (!empty($extraSql['where'])) {
695 foreach ($extraSql['where'] as $table => $sqlWhere) {
696 foreach ($sqlWhere as $where) {
697 $dao->whereAdd($where);
701 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
703 // Ensure 'id' is included.
704 $options['return']['id'] = TRUE;
705 $allfields = _civicrm_api3_get_unique_name_array($dao);
706 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
707 foreach ($returnMatched as $returnValue) {
708 $dao->selectAdd($returnValue);
711 // Not already matched on the field names.
712 $unmatchedFields = array_diff(
713 array_keys($options['return']),
717 $returnUniqueMatched = array_intersect(
719 // But a match for the field keys.
720 array_flip($allfields)
722 foreach ($returnUniqueMatched as $uniqueVal) {
723 $dao->selectAdd($allfields[$uniqueVal]);
726 $dao->setApiFilter($params);
730 * Apply filters (e.g. high, low) to DAO object (prior to find).
732 * @param string $filterField
733 * Field name of filter.
734 * @param string $filterValue
735 * Field value of filter.
739 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
740 if (strstr($filterField, 'high')) {
741 $fieldName = substr($filterField, 0, -5);
742 $dao->whereAdd("($fieldName <= $filterValue )");
744 if (strstr($filterField, 'low')) {
745 $fieldName = substr($filterField, 0, -4);
746 $dao->whereAdd("($fieldName >= $filterValue )");
748 if ($filterField == 'is_current' && $filterValue == 1) {
749 $todayStart = date('Ymd000000', strtotime('now'));
750 $todayEnd = date('Ymd235959', strtotime('now'));
751 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
752 if (property_exists($dao, 'is_active')) {
753 $dao->whereAdd('is_active = 1');
759 * Get sort, limit etc options from the params - supporting old & new formats.
761 * Get returnProperties for legacy
763 * @param array $params
764 * Params array as passed into civicrm_api.
765 * @param bool $queryObject
766 * Is this supporting a queryObject api (e.g contact) - if so we support more options.
767 * for legacy report & return a unique fields array
769 * @param string $entity
770 * @param string $action
772 * @throws API_Exception
774 * options extracted from params
776 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
777 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
779 $sort = CRM_Utils_Array
::value('sort', $params, 0);
780 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
781 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
783 $offset = CRM_Utils_Array
::value('offset', $params, 0);
784 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
785 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
786 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
788 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
789 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
790 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
792 if (is_array(CRM_Utils_Array
::value('options', $params))) {
793 // is count is set by generic getcount not user
794 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
795 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
796 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
797 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
800 $returnProperties = array();
801 // handle the format return =sort_name,display_name...
802 if (array_key_exists('return', $params)) {
803 if (is_array($params['return'])) {
804 $returnProperties = array_fill_keys($params['return'], 1);
807 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
808 $returnProperties = array_fill_keys($returnProperties, 1);
811 if ($entity && $action == 'get') {
812 if (!empty($returnProperties['id'])) {
813 $returnProperties[$lowercase_entity . '_id'] = 1;
814 unset($returnProperties['id']);
819 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
820 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
821 'is_count' => $is_count,
822 'return' => !empty($returnProperties) ?
$returnProperties : array(),
825 $finalSort = array();
826 $options['sort'] = NULL;
828 foreach ((array) $sort as $s) {
829 if (CRM_Utils_Rule
::mysqlOrderBy($s)) {
830 if ($entity && $action == 'get') {
831 switch (trim(strtolower($s))) {
835 $s = str_replace('id', $lowercase_entity . '_id', $s);
841 throw new API_Exception("Unknown field specified for sort. Cannot order by '$s'");
844 $options['sort'] = implode(', ', $finalSort);
847 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
848 throw new API_Exception('invalid string in sort options');
854 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
855 // if the query object is being used this should be used
856 $inputParams = array();
857 $legacyreturnProperties = array();
859 'sort', 'offset', 'rowCount', 'options', 'return',
860 'version', 'prettyprint', 'check_permissions', 'sequential',
862 foreach ($params as $n => $v) {
863 if (substr($n, 0, 7) == 'return.') {
864 $legacyreturnProperties[substr($n, 7)] = $v;
866 elseif ($n == 'id') {
867 $inputParams[$lowercase_entity . '_id'] = $v;
869 elseif (in_array($n, $otherVars)) {
872 $inputParams[$n] = $v;
873 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
874 throw new API_Exception('invalid string');
878 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
879 $options['input_params'] = $inputParams;
884 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
886 * @param array $params
887 * Params array as passed into civicrm_api.
892 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
894 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
895 if (!$options['is_count']) {
896 if (!empty($options['limit'])) {
897 $dao->limit((int) $options['offset'], (int) $options['limit']);
899 if (!empty($options['sort'])) {
900 $options['sort'] = CRM_Utils_Type
::escape($options['sort'], 'MysqlOrderBy');
901 $dao->orderBy($options['sort']);
907 * Build fields array.
909 * This is the array of fields as it relates to the given DAO
910 * returns unique fields as keys by default but if set but can return by DB fields
912 * @param CRM_Core_DAO $bao
913 * @param bool $unique
917 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
918 $fields = $bao->fields();
920 if (empty($fields['id'])) {
921 $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
922 $fields['id'] = $fields[$lowercase_entity . '_id'];
923 unset($fields[$lowercase_entity . '_id']);
928 foreach ($fields as $field) {
929 $dbFields[$field['name']] = $field;
935 * Build fields array.
937 * This is the array of fields as it relates to the given DAO
938 * returns unique fields as keys by default but if set but can return by DB fields
940 * @param CRM_Core_DAO $bao
944 function _civicrm_api3_get_unique_name_array(&$bao) {
945 $fields = $bao->fields();
946 foreach ($fields as $field => $values) {
947 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
949 return $uniqueFields;
953 * Converts an DAO object to an array.
955 * @deprecated - DAO based retrieval is being phased out.
957 * @param CRM_Core_DAO $dao
959 * @param array $params
960 * @param bool $uniqueFields
961 * @param string $entity
962 * @param bool $autoFind
966 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
968 if (isset($params['options']) && !empty($params['options']['is_count'])) {
969 return $dao->count();
974 if ($autoFind && !$dao->find()) {
978 if (isset($dao->count
)) {
982 $fields = array_keys(_civicrm_api3_build_fields_array($dao, FALSE));
983 while ($dao->fetch()) {
985 foreach ($fields as $key) {
986 if (array_key_exists($key, $dao)) {
987 // not sure on that one
988 if ($dao->$key !== NULL) {
989 $tmp[$key] = $dao->$key;
993 $result[$dao->id
] = $tmp;
995 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
996 _civicrm_api3_custom_data_get($result[$dao->id
], $params['check_permissions'], $entity, $dao->id
);
1004 * Determine if custom fields need to be retrieved.
1006 * We currently retrieve all custom fields or none at this level so if we know the entity
1007 * && 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
1008 * @todo filter so only required fields are queried
1010 * @param string $entity
1011 * Entity name in CamelCase.
1012 * @param array $params
1016 function _civicrm_api3_custom_fields_are_required($entity, $params) {
1017 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
1020 $options = _civicrm_api3_get_options_from_params($params);
1021 // We check for possibility of 'custom' => 1 as well as specific custom fields.
1022 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
1023 if (stristr($returnString, 'custom')) {
1029 * Converts an object to an array.
1031 * @param object $dao
1032 * (reference) object to convert.
1033 * @param array $values
1034 * (reference) array.
1035 * @param array|bool $uniqueFields
1037 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
1039 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
1040 foreach ($fields as $key => $value) {
1041 if (array_key_exists($key, $dao)) {
1042 $values[$key] = $dao->$key;
1048 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1055 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1056 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1060 * Format custom parameters.
1062 * @param array $params
1063 * @param array $values
1064 * @param string $extends
1065 * Entity that this custom field extends (e.g. contribution, event, contact).
1066 * @param string $entityId
1067 * ID of entity per $extends.
1069 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1070 $values['custom'] = array();
1071 $checkCheckBoxField = FALSE;
1073 if (in_array($extends, array('Household', 'Individual', 'Organization'))) {
1074 $entity = 'Contact';
1077 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
1078 if (!$fields['is_error']) {
1079 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1080 $fields = $fields['values'];
1081 $checkCheckBoxField = TRUE;
1084 foreach ($params as $key => $value) {
1085 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
1086 if ($customFieldID && (!is_null($value))) {
1087 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1088 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1091 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1092 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1099 * Format parameters for create action.
1101 * @param array $params
1104 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1105 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1107 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery
::$extendsMap, array_fill_keys($nonGenericEntities, 1));
1108 if (!array_key_exists($entity, $customFieldEntities)) {
1112 _civicrm_api3_custom_format_params($params, $values, $entity);
1113 $params = array_merge($params, $values);
1117 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1119 * We should look at pushing to BAO function
1120 * 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
1121 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1123 * 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
1124 * don't touch - lots of very cautious code in here
1126 * The resulting array should look like
1132 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1134 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1135 * be fixed in future
1137 * @param mixed $checkboxFieldValue
1138 * @param string $customFieldLabel
1139 * @param string $entity
1141 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1143 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1144 // We can assume it's pre-formatted.
1147 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1148 if (!empty($options['is_error'])) {
1149 // The check is precautionary - can probably be removed later.
1153 $options = $options['values'];
1155 if (is_array($checkboxFieldValue)) {
1156 foreach ($checkboxFieldValue as $key => $value) {
1157 if (!array_key_exists($key, $options)) {
1158 $validValue = FALSE;
1162 // we have been passed an array that is already in the 'odd' custom field format
1167 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1168 // if the array only has one item we'll treat it like any other string
1169 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1170 $possibleValue = reset($checkboxFieldValue);
1172 if (is_string($checkboxFieldValue)) {
1173 $possibleValue = $checkboxFieldValue;
1175 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1176 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1179 elseif (is_array($checkboxFieldValue)) {
1180 // so this time around we are considering the values in the array
1181 $possibleValues = $checkboxFieldValue;
1182 $formatValue = TRUE;
1184 elseif (stristr($checkboxFieldValue, ',')) {
1185 $formatValue = TRUE;
1186 //lets see if we should separate it - we do this near the end so we
1187 // ensure we have already checked that the comma is not part of a legitimate match
1188 // and of course, we don't make any changes if we don't now have matches
1189 $possibleValues = explode(',', $checkboxFieldValue);
1192 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1196 foreach ($possibleValues as $index => $possibleValue) {
1197 if (array_key_exists($possibleValue, $options)) {
1198 // 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)
1200 elseif (array_key_exists(trim($possibleValue), $options)) {
1201 $possibleValues[$index] = trim($possibleValue);
1204 $formatValue = FALSE;
1208 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1213 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1215 * @param string $bao_name
1217 * @param array $params
1219 * @param bool $returnAsSuccess
1220 * Return in api success format.
1221 * @param string $entity
1222 * @param CRM_Utils_SQL_Select|NULL $sql
1223 * Extra SQL bits to add to the query. For filtering current events, this might be:
1224 * CRM_Utils_SQL_Select::fragment()->where('(start_date >= CURDATE() || end_date >= CURDATE())');
1225 * @param bool $uniqueFields
1226 * Should unique field names be returned (for backward compatibility)
1230 function _civicrm_api3_basic_get($bao_name, $params, $returnAsSuccess = TRUE, $entity = "", $sql = NULL, $uniqueFields = FALSE) {
1231 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(str_replace('_BAO_', '_DAO_', $bao_name));
1232 $options = _civicrm_api3_get_options_from_params($params);
1234 $query = new \Civi\API\
Api3SelectQuery($entity, CRM_Utils_Array
::value('check_permissions', $params, FALSE));
1235 $query->where
= $params;
1236 if ($options['is_count']) {
1237 $query->select
= array('count_rows');
1240 $query->select
= array_keys(array_filter($options['return']));
1241 $query->orderBy
= $options['sort'];
1242 $query->isFillUniqueFields
= $uniqueFields;
1244 $query->limit
= $options['limit'];
1245 $query->offset
= $options['offset'];
1246 $query->merge($sql);
1247 $result = $query->run();
1249 if ($returnAsSuccess) {
1250 return civicrm_api3_create_success($result, $params, $entity, 'get');
1256 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1258 * @param string $bao_name
1259 * Name of BAO Class.
1260 * @param array $params
1261 * Parameters passed into the api call.
1262 * @param string $entity
1263 * Entity - pass in if entity is non-standard & required $ids array.
1265 * @throws API_Exception
1266 * @throws \Civi\API\Exception\UnauthorizedException
1269 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1270 _civicrm_api3_check_edit_permissions($bao_name, $params);
1271 _civicrm_api3_format_params_for_create($params, $entity);
1272 $args = array(&$params);
1274 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1278 if (method_exists($bao_name, 'create')) {
1280 $fct_name = $bao_name . '::' . $fct;
1281 $bao = call_user_func_array(array($bao_name, $fct), $args);
1283 elseif (method_exists($bao_name, 'add')) {
1285 $fct_name = $bao_name . '::' . $fct;
1286 $bao = call_user_func_array(array($bao_name, $fct), $args);
1289 $fct_name = '_civicrm_api3_basic_create_fallback';
1290 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1293 if (is_null($bao)) {
1294 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1296 elseif (is_a($bao, 'CRM_Core_Error')) {
1297 //some weird circular thing means the error takes itself as an argument
1298 $msg = $bao->getMessages($bao);
1299 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1300 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1301 // so we need to reset the error object here to avoid getting concatenated errors
1302 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1303 CRM_Core_Error
::singleton()->reset();
1304 throw new API_Exception($msg);
1308 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1309 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1314 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1316 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1317 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1319 * @param string $bao_name
1320 * @param array $params
1322 * @throws API_Exception
1324 * @return CRM_Core_DAO|NULL
1325 * An instance of the BAO
1327 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1328 $dao_name = get_parent_class($bao_name);
1329 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1330 $dao_name = $bao_name;
1332 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1333 if (empty($entityName)) {
1334 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1335 'class_name' => $bao_name,
1338 $hook = empty($params['id']) ?
'create' : 'edit';
1340 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1341 $instance = new $dao_name();
1342 $instance->copyValues($params);
1344 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1350 * Function to do a 'standard' api del.
1352 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1354 * @param string $bao_name
1355 * @param array $params
1359 * @throws API_Exception
1360 * @throws \Civi\API\Exception\UnauthorizedException
1362 function _civicrm_api3_basic_delete($bao_name, &$params) {
1363 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1364 _civicrm_api3_check_edit_permissions($bao_name, array('id' => $params['id']));
1365 $args = array(&$params['id']);
1366 if (method_exists($bao_name, 'del')) {
1367 $dao = new $bao_name();
1368 $dao->id
= $params['id'];
1370 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1371 if ($bao !== FALSE) {
1372 return civicrm_api3_create_success();
1374 throw new API_Exception('Could not delete entity id ' . $params['id']);
1376 throw new API_Exception('Could not delete entity id ' . $params['id']);
1378 elseif (method_exists($bao_name, 'delete')) {
1379 $dao = new $bao_name();
1380 $dao->id
= $params['id'];
1382 while ($dao->fetch()) {
1384 return civicrm_api3_create_success();
1388 throw new API_Exception('Could not delete entity id ' . $params['id']);
1392 throw new API_Exception('no delete method found');
1396 * Get custom data for the given entity & Add it to the returnArray.
1398 * This looks like 'custom_123' = 'custom string' AND
1399 * 'custom_123_1' = 'custom string'
1400 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1402 * @param array $returnArray
1403 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1404 * @param $checkPermission
1405 * @param string $entity
1406 * E.g membership, event.
1407 * @param int $entity_id
1408 * @param int $groupID
1409 * Per CRM_Core_BAO_CustomGroup::getTree.
1410 * @param int $subType
1411 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1412 * @param string $subName
1413 * Subtype of entity.
1415 function _civicrm_api3_custom_data_get(&$returnArray, $checkPermission, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1416 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1427 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1);
1428 $customValues = array();
1429 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1430 $fieldInfo = array();
1431 foreach ($groupTree as $set) {
1432 $fieldInfo +
= $set['fields'];
1434 if (!empty($customValues)) {
1435 foreach ($customValues as $key => $val) {
1436 // per standard - return custom_fieldID
1437 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1438 $returnArray['custom_' . $id] = $val;
1440 //not standard - but some api did this so guess we should keep - cheap as chips
1441 $returnArray[$key] = $val;
1443 // Shim to restore legacy behavior of ContactReference custom fields
1444 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1445 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1446 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1453 * Used by the Validate API.
1454 * @param string $entity
1455 * @param string $action
1456 * @param array $params
1458 * @return array $errors
1460 function _civicrm_api3_validate($entity, $action, $params) {
1462 $fields = civicrm_api3($entity, 'getfields', array('sequential' => 1, 'api_action' => $action));
1463 $fields = $fields['values'];
1465 // Check for required fields.
1466 foreach ($fields as $values) {
1467 if (!empty($values['api.required']) && empty($params[$values['name']])) {
1468 $errors[$values['name']] = array(
1469 'message' => "Mandatory key(s) missing from params array: " . $values['name'],
1470 'code' => "mandatory_missing",
1475 // Select only the fields which have been input as a param.
1476 $finalfields = array();
1477 foreach ($fields as $values) {
1478 if (array_key_exists($values['name'], $params)) {
1479 $finalfields[] = $values;
1483 // This derives heavily from the function "_civicrm_api3_validate_fields".
1484 // However, the difference is that try-catch blocks are nested in the loop, making it
1485 // possible for us to get all errors in one go.
1486 foreach ($finalfields as $fieldInfo) {
1487 $fieldName = $fieldInfo['name'];
1489 _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params);
1491 catch (Exception
$e) {
1492 $errors[$fieldName] = array(
1493 'message' => $e->getMessage(),
1494 'code' => 'incorrect_value',
1499 return array($errors);
1503 * Used by the Validate API.
1505 * @param array $fieldInfo
1506 * @param string $entity
1507 * @param array $params
1509 * @throws API_Exception
1512 function _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params) {
1513 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1514 case CRM_Utils_Type
::T_INT
:
1515 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1518 case CRM_Utils_Type
::T_DATE
:
1519 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1520 case CRM_Utils_Type
::T_TIMESTAMP
:
1521 //field is of type date or datetime
1522 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1525 case CRM_Utils_Type
::T_TEXT
:
1526 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1529 case CRM_Utils_Type
::T_STRING
:
1530 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1533 case CRM_Utils_Type
::T_MONEY
:
1534 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1536 foreach ((array) $fieldValue as $fieldvalue) {
1537 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1538 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1546 * Validate fields being passed into API.
1548 * This function relies on the getFields function working accurately
1549 * for the given API.
1551 * As of writing only date was implemented.
1553 * @param string $entity
1554 * @param string $action
1555 * @param array $params
1557 * @param array $fields
1558 * Response from getfields all variables are the same as per civicrm_api.
1562 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields) {
1563 //CRM-15792 handle datetime for custom fields below code handles chain api call
1564 $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params)));
1565 if (!empty($chainApikeys) && is_array($chainApikeys)) {
1566 foreach ($chainApikeys as $key => $value) {
1567 if (is_array($params[$key])) {
1568 $chainApiParams = array_intersect_key($fields, $params[$key]);
1569 $customFields = array_fill_keys(array_keys($params[$key]), $key);
1573 $fields = array_intersect_key($fields, $params);
1574 if (!empty($chainApiParams)) {
1575 $fields = array_merge($fields, $chainApiParams);
1577 foreach ($fields as $fieldName => $fieldInfo) {
1578 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1579 case CRM_Utils_Type
::T_INT
:
1580 //field is of type integer
1581 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1584 case CRM_Utils_Type
::T_DATE
:
1585 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1586 case CRM_Utils_Type
::T_TIMESTAMP
:
1587 //field is of type date or datetime
1588 if (!empty($customFields) && array_key_exists($fieldName, $customFields)) {
1589 $dateParams = &$params[$customFields[$fieldName]];
1592 $dateParams = &$params;
1594 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
1597 case CRM_Utils_Type
::T_TEXT
:
1599 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1602 case CRM_Utils_Type
::T_STRING
:
1603 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1606 case CRM_Utils_Type
::T_MONEY
:
1607 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1608 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1611 foreach ((array) $fieldValue as $fieldvalue) {
1612 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1613 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1622 * Validate foreign key values of fields being passed into API.
1624 * This function relies on the getFields function working accurately
1625 * for the given API.
1627 * @param string $entity
1628 * @param string $action
1629 * @param array $params
1631 * @param array $fields
1632 * Response from getfields all variables are the same as per civicrm_api.
1636 function _civicrm_api3_validate_foreign_keys($entity, $action, &$params, $fields) {
1637 // intensive checks - usually only called after DB level fail
1638 foreach ($fields as $fieldName => $fieldInfo) {
1639 if (!empty($fieldInfo['FKClassName'])) {
1640 if (!empty($params[$fieldName])) {
1641 _civicrm_api3_validate_constraint($params[$fieldName], $fieldName, $fieldInfo);
1643 elseif (!empty($fieldInfo['required'])) {
1644 throw new Exception("DB Constraint Violation - $fieldName should possibly be marked as mandatory for $entity,$action API. If so, please raise a bug report.");
1647 if (!empty($fieldInfo['api.unique'])) {
1648 $params['entity'] = $entity;
1649 _civicrm_api3_validate_unique_key($params, $fieldName);
1655 * Validate date fields being passed into API.
1657 * It currently converts both unique fields and DB field names to a mysql date.
1658 * @todo - probably the unique field handling & the if exists handling is now done before this
1659 * function is reached in the wrapper - can reduce this code down to assume we
1660 * are only checking the passed in field
1662 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1663 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1665 * @param array $params
1666 * Params from civicrm_api.
1667 * @param string $fieldName
1668 * Uniquename of field being checked.
1669 * @param array $fieldInfo
1670 * Array of fields from getfields function.
1674 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1675 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1676 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1679 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1680 if (!empty($params[$fieldInfo['name']])) {
1681 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1683 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1684 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1688 $params[$fieldName][$op] = $fieldValue;
1691 $params[$fieldName] = $fieldValue;
1696 * Convert date into BAO friendly date.
1698 * We accept 'whatever strtotime accepts'
1700 * @param string $dateValue
1701 * @param string $fieldName
1707 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1708 if (is_array($dateValue)) {
1709 foreach ($dateValue as $key => $value) {
1710 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1714 if (strtotime($dateValue) === FALSE) {
1715 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1717 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1718 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1722 * Validate foreign constraint fields being passed into API.
1724 * @param mixed $fieldValue
1725 * @param string $fieldName
1726 * Uniquename of field being checked.
1727 * @param array $fieldInfo
1728 * Array of fields from getfields function.
1730 * @throws \API_Exception
1732 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1733 $daoName = $fieldInfo['FKClassName'];
1734 $dao = new $daoName();
1735 $dao->id
= $fieldValue;
1737 $dao->selectAdd('id');
1738 if (!$dao->find()) {
1739 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1744 * Validate foreign constraint fields being passed into API.
1746 * @param array $params
1747 * Params from civicrm_api.
1748 * @param string $fieldName
1749 * Uniquename of field being checked.
1753 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1754 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1755 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1758 $existing = civicrm_api($params['entity'], 'get', array(
1759 'version' => $params['version'],
1760 $fieldName => $fieldValue,
1762 // an entry already exists for this unique field
1763 if ($existing['count'] == 1) {
1764 // question - could this ever be a security issue?
1765 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1770 * Generic implementation of the "replace" action.
1772 * Replace the old set of entities (matching some given keys) with a new set of
1773 * entities (matching the same keys).
1775 * @note This will verify that 'values' is present, but it does not directly verify
1776 * any other parameters.
1778 * @param string $entity
1780 * @param array $params
1781 * Params from civicrm_api, including:.
1782 * - 'values': an array of records to save
1783 * - all other items: keys which identify new/pre-existing records.
1787 function _civicrm_api3_generic_replace($entity, $params) {
1789 $transaction = new CRM_Core_Transaction();
1791 if (!is_array($params['values'])) {
1792 throw new Exception("Mandatory key(s) missing from params array: values");
1795 // Extract the keys -- somewhat scary, don't think too hard about it
1796 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1798 // Lookup pre-existing records
1799 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1800 if (civicrm_error($preexisting)) {
1801 $transaction->rollback();
1802 return $preexisting;
1805 // Save the new/updated records
1807 foreach ($params['values'] as $replacement) {
1808 // Sugar: Don't force clients to duplicate the 'key' data
1809 $replacement = array_merge($baseParams, $replacement);
1810 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1811 $create = civicrm_api($entity, $action, $replacement);
1812 if (civicrm_error($create)) {
1813 $transaction->rollback();
1816 foreach ($create['values'] as $entity_id => $entity_value) {
1817 $creates[$entity_id] = $entity_value;
1821 // Remove stale records
1822 $staleIDs = array_diff(
1823 array_keys($preexisting['values']),
1824 array_keys($creates)
1826 foreach ($staleIDs as $staleID) {
1827 $delete = civicrm_api($entity, 'delete', array(
1828 'version' => $params['version'],
1831 if (civicrm_error($delete)) {
1832 $transaction->rollback();
1837 return civicrm_api3_create_success($creates, $params);
1839 catch(PEAR_Exception
$e) {
1840 $transaction->rollback();
1841 return civicrm_api3_create_error($e->getMessage());
1843 catch(Exception
$e) {
1844 $transaction->rollback();
1845 return civicrm_api3_create_error($e->getMessage());
1850 * Replace base parameters.
1852 * @param array $params
1856 function _civicrm_api3_generic_replace_base_params($params) {
1857 $baseParams = $params;
1858 unset($baseParams['values']);
1859 unset($baseParams['sequential']);
1860 unset($baseParams['options']);
1865 * Returns fields allowable by api.
1868 * String Entity to query.
1869 * @param bool $unique
1870 * Index by unique fields?.
1871 * @param array $params
1875 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1876 $unsetIfEmpty = array(
1883 $dao = _civicrm_api3_get_DAO($entity);
1888 $fields = $d->fields();
1890 foreach ($fields as $name => &$field) {
1891 // Denote as core field
1892 $field['is_core_field'] = TRUE;
1893 // Set html attributes for text fields
1894 if (isset($field['html'])) {
1895 $field['html'] +
= (array) $d::makeAttribute($field);
1899 // replace uniqueNames by the normal names as the key
1900 if (empty($unique)) {
1901 foreach ($fields as $name => &$field) {
1902 //getting rid of unused attributes
1903 foreach ($unsetIfEmpty as $attr) {
1904 if (empty($field[$attr])) {
1905 unset($field[$attr]);
1908 if ($name == $field['name']) {
1911 if (array_key_exists($field['name'], $fields)) {
1912 $field['error'] = 'name conflict';
1913 // it should never happen, but better safe than sorry
1916 $fields[$field['name']] = $field;
1917 $fields[$field['name']]['uniqueName'] = $name;
1918 unset($fields[$name]);
1921 // Translate FKClassName to the corresponding api
1922 foreach ($fields as $name => &$field) {
1923 if (!empty($field['FKClassName'])) {
1924 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1926 $field['FKApiName'] = $FKApi;
1930 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1935 * Return an array of fields for a given entity.
1937 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1940 * @param array $params
1944 function _civicrm_api_get_custom_fields($entity, &$params) {
1945 $entity = _civicrm_api_get_camel_name($entity);
1946 if ($entity == 'Contact') {
1947 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1948 $entity = CRM_Utils_Array
::value('contact_type', $params);
1950 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1953 // we could / should probably test for other subtypes here - e.g. activity_type_id
1954 CRM_Utils_Array
::value('contact_sub_type', $params),
1963 foreach ($customfields as $key => $value) {
1964 // Regular fields have a 'name' property
1965 $value['name'] = 'custom_' . $key;
1966 $value['title'] = $value['label'];
1967 $value['type'] = _getStandardTypeFromCustomDataType($value);
1968 $ret['custom_' . $key] = $value;
1974 * Translate the custom field data_type attribute into a std 'type'.
1976 * @param array $value
1980 function _getStandardTypeFromCustomDataType($value) {
1981 $dataType = $value['data_type'];
1982 //CRM-15792 - If date custom field contains timeformat change type to DateTime
1983 if ($value['data_type'] == 'Date' && isset($value['time_format']) && $value['time_format'] > 0) {
1984 $dataType = 'DateTime';
1987 'String' => CRM_Utils_Type
::T_STRING
,
1988 'Int' => CRM_Utils_Type
::T_INT
,
1989 'Money' => CRM_Utils_Type
::T_MONEY
,
1990 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1991 'Float' => CRM_Utils_Type
::T_FLOAT
,
1992 'Date' => CRM_Utils_Type
::T_DATE
,
1993 'DateTime' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
1994 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1995 'StateProvince' => CRM_Utils_Type
::T_INT
,
1996 'File' => CRM_Utils_Type
::T_STRING
,
1997 'Link' => CRM_Utils_Type
::T_STRING
,
1998 'ContactReference' => CRM_Utils_Type
::T_INT
,
1999 'Country' => CRM_Utils_Type
::T_INT
,
2001 return $mapping[$dataType];
2006 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
2008 * If multiple aliases the last takes precedence
2010 * Function also swaps unique fields for non-unique fields & vice versa.
2012 * @param $apiRequest
2015 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
2016 foreach ($fields as $field => $values) {
2017 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
2018 if (!empty($values['api.aliases'])) {
2019 // if aliased field is not set we try to use field alias
2020 if (!isset($apiRequest['params'][$field])) {
2021 foreach ($values['api.aliases'] as $alias) {
2022 if (isset($apiRequest['params'][$alias])) {
2023 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
2025 //unset original field nb - need to be careful with this as it may bring inconsistencies
2026 // out of the woodwork but will be implementing only as _spec function extended
2027 unset($apiRequest['params'][$alias]);
2031 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
2032 && isset($apiRequest['params'][$values['name']])
2034 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
2035 // note that it would make sense to unset the original field here but tests need to be in place first
2036 if ($field != 'domain_version') {
2037 unset($apiRequest['params'][$values['name']]);
2040 if (!isset($apiRequest['params'][$field])
2042 && $field != $uniqueName
2043 && array_key_exists($uniqueName, $apiRequest['params'])
2045 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
2046 // note that it would make sense to unset the original field here but tests need to be in place first
2053 * Validate integer fields being passed into API.
2055 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
2057 * @param array $params
2058 * Params from civicrm_api.
2059 * @param string $fieldName
2060 * Uniquename of field being checked.
2061 * @param array $fieldInfo
2062 * Array of fields from getfields function.
2063 * @param string $entity
2065 * @throws API_Exception
2067 function _civicrm_api3_validate_integer(&$params, $fieldName, &$fieldInfo, $entity) {
2068 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2069 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2073 if (!empty($fieldValue) ||
$fieldValue === '0' ||
$fieldValue === 0) {
2074 // if value = 'user_contact_id' (or similar), replace value with contact id
2075 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
2076 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
2077 if ('unknown-user' === $realContactId) {
2078 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName, "type" => "integer"));
2080 elseif (is_numeric($realContactId)) {
2081 $fieldValue = $realContactId;
2084 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2085 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op);
2088 // After swapping options, ensure we have an integer(s)
2089 foreach ((array) ($fieldValue) as $value) {
2090 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
2091 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
2095 // Check our field length
2096 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
2098 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
2099 2100, array('field' => $fieldName, "max_length" => $fieldInfo['maxlength'])
2105 $params[$fieldName][$op] = $fieldValue;
2108 $params[$fieldName] = $fieldValue;
2113 * Determine a contact ID using a string expression.
2115 * @param string $contactIdExpr
2116 * E.g. "user_contact_id" or "@user:username".
2118 * @return int|NULL|'unknown-user'
2120 function _civicrm_api3_resolve_contactID($contactIdExpr) {
2121 // If value = 'user_contact_id' replace value with logged in user id.
2122 if ($contactIdExpr == "user_contact_id") {
2123 return CRM_Core_Session
::getLoggedInContactID();
2125 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
2126 $config = CRM_Core_Config
::singleton();
2128 $ufID = $config->userSystem
->getUfId($matches[1]);
2130 return 'unknown-user';
2133 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
2135 return 'unknown-user';
2144 * Validate html (check for scripting attack).
2146 * @param array $params
2147 * @param string $fieldName
2148 * @param array $fieldInfo
2150 * @throws API_Exception
2152 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
2153 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2154 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
2158 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2159 throw new API_Exception('Input contains illegal SCRIPT tag.', array("field" => $fieldName, "error_code" => "xss"));
2165 * Validate string fields being passed into API.
2167 * @param array $params
2168 * Params from civicrm_api.
2169 * @param string $fieldName
2170 * Uniquename of field being checked.
2171 * @param array $fieldInfo
2172 * Array of fields from getfields function.
2173 * @param string $entity
2175 * @throws API_Exception
2178 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2179 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName, 'String');
2180 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
2184 if (!is_array($fieldValue)) {
2185 $fieldValue = (string) $fieldValue;
2188 //@todo what do we do about passed in arrays. For many of these fields
2189 // the missing piece of functionality is separating them to a separated string
2190 // & many save incorrectly. But can we change them wholesale?
2193 foreach ((array) $fieldValue as $value) {
2194 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2195 throw new Exception('Input contains illegal SCRIPT tag.');
2197 if ($fieldName == 'currency') {
2198 //When using IN operator $fieldValue is a array of currency codes
2199 if (!CRM_Utils_Rule
::currencyCode($value)) {
2200 throw new Exception("Currency not a valid code: $currency");
2205 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2206 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op);
2208 // Check our field length
2209 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2210 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2211 2100, array('field' => $fieldName)
2216 $params[$fieldName][$op] = $fieldValue;
2219 $params[$fieldName] = $fieldValue;
2224 * Validate & swap out any pseudoconstants / options.
2226 * @param mixed $fieldValue
2227 * @param string $entity : api entity name
2228 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2229 * @param array $fieldInfo : getfields meta-data
2232 * @throws \API_Exception
2234 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo, $op = '=') {
2235 if (in_array($op, array('>', '<', '>=', '<=', 'LIKE', 'NOT LIKE'))) {
2239 $options = CRM_Utils_Array
::value('options', $fieldInfo);
2242 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2243 // We need to get the options from the entity the field relates to.
2244 $entity = $fieldInfo['entity'];
2246 $options = civicrm_api($entity, 'getoptions', array(
2248 'field' => $fieldInfo['name'],
2249 'context' => 'validate',
2251 $options = CRM_Utils_Array
::value('values', $options, array());
2254 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2256 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2257 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
2260 // If passed multiple options, validate each.
2261 if (is_array($fieldValue)) {
2262 foreach ($fieldValue as &$value) {
2263 if (!is_array($value)) {
2264 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
2267 // TODO: unwrap the call to implodePadded from the conditional and do it always
2268 // need to verify that this is safe and doesn't break anything though.
2269 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2271 CRM_Utils_Array
::implodePadded($fieldValue);
2275 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName);
2280 * Validate & swap a single option value for a field.
2282 * @param string $value field value
2283 * @param array $options array of options for this field
2284 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2286 * @throws API_Exception
2288 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
2289 // If option is a key, no need to translate
2290 // or if no options are avaiable for pseudoconstant 'table' property
2291 if (array_key_exists($value, $options) ||
!$options) {
2295 // Translate value into key
2296 // Cast $value to string to avoid a bug in array_search
2297 $newValue = array_search((string) $value, $options);
2298 if ($newValue !== FALSE) {
2302 // Case-insensitive matching
2303 $newValue = strtolower($value);
2304 $options = array_map("strtolower", $options);
2305 $newValue = array_search($newValue, $options);
2306 if ($newValue === FALSE) {
2307 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
2313 * Returns the canonical name of a field.
2316 * api entity name (string should already be standardized - no camelCase).
2318 * any variation of a field's name (name, unique_name, api.alias).
2320 * @param string $action
2322 * @return bool|string
2323 * FieldName or FALSE if the field does not exist
2325 function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') {
2329 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2332 if ($fieldName == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
2335 $result = civicrm_api($entity, 'getfields', array(
2337 'action' => $action,
2339 $meta = $result['values'];
2340 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2341 $fieldName = $fieldName . '_id';
2343 if (isset($meta[$fieldName])) {
2344 return $meta[$fieldName]['name'];
2346 foreach ($meta as $info) {
2347 if ($fieldName == $info['name'] ||
$fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2348 return $info['name'];
2350 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
2351 return $info['name'];
2354 // Create didn't work, try with get
2355 if ($action == 'create') {
2356 return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get');
2362 * Check if the function is deprecated.
2364 * @param string $entity
2365 * @param array $result
2367 * @return string|array|null
2369 function _civicrm_api3_deprecation_check($entity, $result = array()) {
2371 $apiFile = "api/v3/$entity.php";
2372 if (CRM_Utils_File
::isIncludable($apiFile)) {
2373 require_once $apiFile;
2375 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
2376 $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation";
2377 if (function_exists($fnName)) {
2378 return $fnName($result);
2384 * Get the actual field value.
2386 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2387 * So this function returns the actual field value.
2389 * @param array $params
2390 * @param string $fieldName
2391 * @param string $type
2395 function _civicrm_api3_field_value_check(&$params, $fieldName, $type = NULL) {
2396 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2399 if (!empty($fieldValue) && is_array($fieldValue) &&
2400 (array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators()) ||
2401 $type == 'String' && strstr(key($fieldValue), 'EMPTY'))
2403 $op = key($fieldValue);
2404 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2406 return array($fieldValue, $op);
2410 * A generic "get" API based on simple array data. This is comparable to
2411 * _civicrm_api3_basic_get but does not use DAO/BAO. This is useful for
2412 * small/mid-size data loaded from external JSON or XML documents.
2415 * @param array $params
2417 * @param array $records
2418 * List of all records.
2419 * @param string $idCol
2420 * The property which defines the ID of a record
2421 * @param array $fields
2422 * List of filterable fields.
2425 * @throws \API_Exception
2427 function _civicrm_api3_basic_array_get($entity, $params, $records, $idCol, $fields) {
2428 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
2429 // TODO // $sort = CRM_Utils_Array::value('sort', $options, NULL);
2430 $offset = CRM_Utils_Array
::value('offset', $options);
2431 $limit = CRM_Utils_Array
::value('limit', $options);
2436 foreach ($records as $record) {
2437 if ($idCol != 'id') {
2438 $record['id'] = $record[$idCol];
2441 foreach ($params as $k => $v) {
2445 if (in_array($k, $fields) && $record[$k] != $v) {
2451 if ($currentOffset >= $offset) {
2452 $matches[$record[$idCol]] = $record;
2454 if ($limit && count($matches) >= $limit) {
2461 $return = CRM_Utils_Array
::value('return', $options, array());
2462 if (!empty($return)) {
2464 $matches = CRM_Utils_Array
::filterColumns($matches, array_keys($return));
2467 return civicrm_api3_create_success($matches, $params);
2471 * @param string $bao_name
2472 * @param array $params
2473 * @throws \Civi\API\Exception\UnauthorizedException
2475 function _civicrm_api3_check_edit_permissions($bao_name, $params) {
2476 // For lack of something more clever, here's a whitelist of entities whos permissions
2477 // are inherited from a contact record.
2478 // Note, when adding here, also remember to modify _civicrm_api3_permissions()
2479 $contactEntities = array(
2480 'CRM_Core_BAO_Email',
2481 'CRM_Core_BAO_Phone',
2482 'CRM_Core_BAO_Address',
2484 'CRM_Core_BAO_Website',
2485 'CRM_Core_BAO_OpenID',
2487 if (!empty($params['check_permissions']) && in_array($bao_name, $contactEntities)) {
2488 $cid = !empty($params['contact_id']) ?
$params['contact_id'] : CRM_Core_DAO
::getFieldValue($bao_name, $params['id'], 'contact_id');
2489 if (!CRM_Contact_BAO_Contact_Permission
::allow($cid, CRM_Core_Permission
::EDIT
)) {
2490 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify contact record');