3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 ($daoName != NULL && $verifyDAO && empty($params['id'])) {
78 $unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
79 if (!is_array($unmatched)) {
84 if (!empty($params['id'])) {
85 $keys = array('version');
88 if (!in_array('version', $keys)) {
89 // required from v3 onwards
93 foreach ($keys as $key) {
97 foreach ($key as $subkey) {
98 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
99 $optionset[] = $subkey;
102 // as long as there is one match then we don't need to rtn anything
106 if (empty($match) && !empty($optionset)) {
107 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
111 // Disallow empty values except for the number zero.
112 // TODO: create a utility for this since it's needed in many places
113 if (!array_key_exists($key, $params) ||
(empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
118 if (!empty($unmatched)) {
119 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched), "mandatory_missing", array("fields" => $unmatched));
124 * Create error array.
131 function civicrm_api3_create_error($msg, $data = array()) {
132 $data['is_error'] = 1;
133 $data['error_message'] = $msg;
134 // we will show sql to privileged user only (not sure of a specific
135 // security hole here but seems sensible - perhaps should apply to the trace as well?)
136 if (isset($data['sql']) && CRM_Core_Permission
::check('Administer CiviCRM')) {
137 // Isn't this redundant?
138 $data['debug_information'] = $data['sql'];
147 * Format array in result output style.
149 * @param array|int $values values generated by API operation (the result)
150 * @param array $params
151 * Parameters passed into API call.
152 * @param string $entity
153 * The entity being acted on.
154 * @param string $action
155 * The action passed to the API.
157 * DAO object to be freed here.
158 * @param array $extraReturnValues
159 * Additional values to be added to top level of result array(.
160 * - this param is currently used for legacy behaviour support
164 function civicrm_api3_create_success($values = 1, $params = array(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
166 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
167 // TODO: This shouldn't be necessary but this fn sometimes gets called with lowercase entity
168 $entity = _civicrm_api_get_camel_name($entity);
169 $result['is_error'] = 0;
170 //lets set the ['id'] field if it's not set & we know what the entity is
171 if (is_array($values) && $entity && $action != 'getfields') {
172 foreach ($values as $key => $item) {
173 if (empty($item['id']) && !empty($item[$lowercase_entity . "_id"])) {
174 $values[$key]['id'] = $item[$lowercase_entity . "_id"];
176 if (!empty($item['financial_type_id'])) {
177 //4.3 legacy handling
178 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
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', array('version' => 3, 'action' => $action) +
$params);
191 elseif ($action != 'getfields') {
192 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
198 $allFields = array();
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), array(
222 $result['undefined_fields'] = array_merge($undefined);
225 if (is_object($dao)) {
229 $result['version'] = 3;
230 if (is_array($values)) {
231 $result['count'] = (int) count($values);
233 // Convert value-separated strings to array
234 if ($action != 'getfields') {
235 _civicrm_api3_separate_values($values);
238 if ($result['count'] == 1) {
239 list($result['id']) = array_keys($values);
241 elseif (!empty($values['id']) && is_int($values['id'])) {
242 $result['id'] = $values['id'];
246 $result['count'] = !empty($values) ?
1 : 0;
249 if (is_array($values) && isset($params['sequential']) &&
250 $params['sequential'] == 1
252 $result['values'] = array_values($values);
255 $result['values'] = $values;
257 if (!empty($params['options']['metadata'])) {
258 // We've made metadata an array but only supporting 'fields' atm.
259 if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
260 $fields = civicrm_api3($entity, 'getfields', array(
261 'action' => substr($action, 0, 3) == 'get' ?
'get' : 'create',
263 $result['metadata']['fields'] = $fields['values'];
266 // Report deprecations.
267 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
268 // The "setvalue" action is deprecated but still in use, so report it only on "getactions".
269 if (!is_string($deprecated) && $action == 'getactions') {
270 $deprecated = ((array) $deprecated) +
array('setvalue' => 'The "setvalue" action is deprecated. Use "create" with an id instead.');
272 // Always report "update" action as deprecated.
273 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'update')) {
274 $deprecated = ((array) $deprecated) +
array('update' => 'The "update" action is deprecated. Use "create" with an id instead.');
277 // Metadata-level deprecations or wholesale entity deprecations.
278 if ($entity == 'Entity' ||
$action == 'getactions' ||
is_string($deprecated)) {
279 $result['deprecated'] = $deprecated;
281 // Action-specific deprecations
282 elseif (!empty($deprecated[$action])) {
283 $result['deprecated'] = $deprecated[$action];
286 return array_merge($result, $extraReturnValues);
290 * Load the DAO of the entity.
296 function _civicrm_api3_load_DAO($entity) {
297 $dao = _civicrm_api3_get_DAO($entity);
306 * Return the DAO of the function or Entity.
308 * @param string $name
309 * Either a function of the api (civicrm_{entity}_create or the entity name.
310 * return the DAO name to manipulate this function
311 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
313 * @return mixed|string
315 function _civicrm_api3_get_DAO($name) {
316 if (strpos($name, 'civicrm_api3') !== FALSE) {
317 $last = strrpos($name, '_');
318 // len ('civicrm_api3_') == 13
319 $name = substr($name, 13, $last - 13);
322 $name = _civicrm_api_get_camel_name($name);
324 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
328 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
330 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
331 if ($name == 'MailingEventQueue') {
332 return 'CRM_Mailing_Event_DAO_Queue';
334 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
335 // but am not confident mailing_recipients is tested so have not tackled.
336 if ($name == 'MailingRecipients') {
337 return 'CRM_Mailing_DAO_Recipients';
339 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
340 if ($name == 'MailingComponent') {
341 return 'CRM_Mailing_DAO_Component';
343 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
344 if ($name == 'AclRole') {
345 return 'CRM_ACL_DAO_EntityRole';
347 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
348 // But this would impact SMS extensions so need to coordinate
349 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
350 if ($name == 'SmsProvider') {
351 return 'CRM_SMS_DAO_Provider';
353 // FIXME: DAO names should follow CamelCase convention
354 if ($name == 'Im' ||
$name == 'Acl') {
355 $name = strtoupper($name);
357 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
358 if ($dao ||
!$name) {
362 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
363 if (file_exists("api/v3/$name.php")) {
364 include_once "api/v3/$name.php";
367 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
368 if (function_exists($daoFn)) {
376 * Return the BAO name of the function or Entity.
378 * @param string $name
379 * Is either a function of the api (civicrm_{entity}_create or the entity name.
380 * return the DAO name to manipulate this function
381 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
385 function _civicrm_api3_get_BAO($name) {
386 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
387 if ($name == 'PrintLabel') {
388 return 'CRM_Badge_BAO_Layout';
390 $dao = _civicrm_api3_get_DAO($name);
394 $bao = str_replace("DAO", "BAO", $dao);
395 $file = strtr($bao, '_', '/') . '.php';
396 // Check if this entity actually has a BAO. Fall back on the DAO if not.
397 return stream_resolve_include_path($file) ?
$bao : $dao;
401 * Recursive function to explode value-separated strings into arrays.
405 function _civicrm_api3_separate_values(&$values) {
406 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
407 foreach ($values as $key => & $value) {
408 if (is_array($value)) {
409 _civicrm_api3_separate_values($value);
411 elseif (is_string($value)) {
412 // This is to honor the way case API was originally written.
413 if ($key == 'case_type_id') {
414 $value = trim(str_replace($sp, ',', $value), ',');
416 elseif (strpos($value, $sp) !== FALSE) {
417 $value = explode($sp, trim($value, $sp));
424 * This is a legacy wrapper for api_store_values.
426 * It checks suitable fields using getfields rather than DAO->fields.
428 * Getfields has handling for how to deal with unique names which dao->fields doesn't
430 * Note this is used by BAO type create functions - eg. contribution
432 * @param string $entity
433 * @param array $params
434 * @param array $values
436 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
437 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
438 $fields = $fields['values'];
439 _civicrm_api3_store_values($fields, $params, $values);
444 * @param array $fields
445 * @param array $params
446 * @param array $values
450 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
453 $keys = array_intersect_key($params, $fields);
454 foreach ($keys as $name => $value) {
455 if ($name !== 'id') {
456 $values[$name] = $value;
464 * Returns field names of the given entity fields.
466 * @param array $fields
467 * Fields array to retrieve the field names for.
470 function _civicrm_api3_field_names($fields) {
472 foreach ($fields as $key => $value) {
473 if (!empty($value['name'])) {
474 $result[] = $value['name'];
481 * Returns an array with database information for the custom fields of an
484 * Something similar might already exist in CiviCRM. But I was not
487 * @param string $entity
490 * an array that maps the custom field ID's to table name and
494 * 'table_name' => 'table_name_1',
495 * 'column_name' => 'column_name_1',
496 * 'data_type' => 'data_type_1',
500 function _civicrm_api3_custom_fields_for_entity($entity) {
504 SELECT f.id, f.label, f.data_type,
505 f.html_type, f.is_search_range,
506 f.option_group_id, f.custom_group_id,
507 f.column_name, g.table_name,
508 f.date_format,f.time_format
509 FROM civicrm_custom_field f
510 JOIN civicrm_custom_group g ON f.custom_group_id = g.id
511 WHERE g.is_active = 1
516 '1' => array($entity, 'String'),
519 $dao = CRM_Core_DAO
::executeQuery($query, $params);
520 while ($dao->fetch()) {
521 $result[$dao->id
] = array(
522 'table_name' => $dao->table_name
,
523 'column_name' => $dao->column_name
,
524 'data_type' => $dao->data_type
,
533 * Get function for query object api.
535 * The API supports 2 types of get request. The more complex uses the BAO query object.
536 * This is a generic function for those functions that call it
538 * At the moment only called by contact we should extend to contribution &
539 * others that use the query object. Note that this function passes permission information in.
542 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
546 * @param array $params
547 * As passed into api get or getcount function.
548 * @param array $additional_options
549 * Array of options (so we can modify the filter).
550 * @param bool $getCount
551 * Are we just after the count.
553 * This basically correlates to the component.
554 * @param null|array $defaultReturnProperties
555 * Default return properties for the entity
556 * (used if return not set - but don't do that - set return!).
559 * @throws API_Exception
561 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL, $mode = 1, $defaultReturnProperties = NULL) {
562 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
563 // Convert id to e.g. contact_id
564 if (empty($params[$lowercase_entity . '_id']) && isset($params['id'])) {
565 $params[$lowercase_entity . '_id'] = $params['id'];
567 unset($params['id']);
569 $options = _civicrm_api3_get_options_from_params($params, TRUE);
571 $inputParams = array_merge(
572 CRM_Utils_Array
::value('input_params', $options, array()),
573 CRM_Utils_Array
::value('input_params', $additional_options, array())
575 $returnProperties = array_merge(
576 CRM_Utils_Array
::value('return', $options, array()),
577 CRM_Utils_Array
::value('return', $additional_options, array())
579 if (empty($returnProperties)) {
580 $returnProperties = $defaultReturnProperties;
582 if (!empty($params['check_permissions'])) {
583 // we will filter query object against getfields
584 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
585 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
586 $fields['values'][$lowercase_entity . '_id'] = array();
587 $varsToFilter = array('returnProperties', 'inputParams');
588 foreach ($varsToFilter as $varToFilter) {
589 if (!is_array($
$varToFilter)) {
592 //I was going to throw an exception rather than silently filter out - but
593 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
594 //so we are silently ignoring parts of their request
595 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
596 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
599 $options = array_merge($options, $additional_options);
600 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
601 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
602 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
603 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
607 $returnProperties = NULL;
610 if (substr($sort, 0, 2) == 'id') {
611 $sort = $lowercase_entity . "_" . $sort;
614 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
616 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
618 list($entities) = CRM_Contact_BAO_Query
::apiQuery(
631 // only return the count of contacts
639 * Get dao query object based on input params.
641 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
644 * @param array $params
645 * @param string $mode
646 * @param string $entity
649 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
651 function _civicrm_api3_get_query_object($params, $mode, $entity) {
652 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
653 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
654 $offset = CRM_Utils_Array
::value('offset', $options);
655 $rowCount = CRM_Utils_Array
::value('limit', $options);
656 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
657 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
658 if (empty($returnProperties)) {
659 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
662 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
663 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
665 empty($params['check_permissions'])
667 list($select, $from, $where, $having) = $query->query();
669 $sql = "$select $from $where $having";
672 $sort = CRM_Utils_Type
::escape($sort, 'MysqlOrderBy');
673 $sql .= " ORDER BY $sort ";
675 if (!empty($rowCount)) {
676 $sql .= " LIMIT $offset, $rowCount ";
678 $dao = CRM_Core_DAO
::executeQuery($sql);
679 return array($dao, $query);
683 * Function transfers the filters being passed into the DAO onto the params object.
685 * @deprecated DAO based retrieval is being phased out.
687 * @param CRM_Core_DAO $dao
688 * @param array $params
689 * @param bool $unique
690 * @param array $extraSql
691 * API specific queries eg for event isCurrent would be converted to
692 * $extraSql['where'] = array('civicrm_event' => array('(start_date >= CURDATE() || end_date >= CURDATE())'));
694 * @throws API_Exception
697 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $extraSql = array()) {
698 $entity = _civicrm_api_get_entity_name_from_dao($dao);
699 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
700 if (!empty($params[$lowercase_entity . "_id"]) && empty($params['id'])) {
701 //if entity_id is set then treat it as ID (will be overridden by id if set)
702 $params['id'] = $params[$lowercase_entity . "_id"];
704 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
705 $fields = array_intersect(array_keys($allfields), array_keys($params));
707 $options = _civicrm_api3_get_options_from_params($params);
708 //apply options like sort
709 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
711 //accept filters like filter.activity_date_time_high
712 // std is now 'filters' => ..
713 if (strstr(implode(',', array_keys($params)), 'filter')) {
714 if (isset($params['filters']) && is_array($params['filters'])) {
715 foreach ($params['filters'] as $paramkey => $paramvalue) {
716 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
720 foreach ($params as $paramkey => $paramvalue) {
721 if (strstr($paramkey, 'filter')) {
722 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
731 foreach ($fields as $field) {
732 if (is_array($params[$field])) {
733 //get the actual fieldname from db
734 $fieldName = $allfields[$field]['name'];
735 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
736 if (!empty($where)) {
737 $dao->whereAdd($where);
742 $daoFieldName = $allfields[$field]['name'];
743 if (empty($daoFieldName)) {
744 throw new API_Exception("Failed to determine field name for \"$field\"");
746 $dao->{$daoFieldName} = $params[$field];
749 $dao->$field = $params[$field];
753 if (!empty($extraSql['where'])) {
754 foreach ($extraSql['where'] as $table => $sqlWhere) {
755 foreach ($sqlWhere as $where) {
756 $dao->whereAdd($where);
760 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
762 // Ensure 'id' is included.
763 $options['return']['id'] = TRUE;
764 $allfields = _civicrm_api3_get_unique_name_array($dao);
765 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
766 foreach ($returnMatched as $returnValue) {
767 $dao->selectAdd($returnValue);
770 // Not already matched on the field names.
771 $unmatchedFields = array_diff(
772 array_keys($options['return']),
776 $returnUniqueMatched = array_intersect(
778 // But a match for the field keys.
779 array_flip($allfields)
781 foreach ($returnUniqueMatched as $uniqueVal) {
782 $dao->selectAdd($allfields[$uniqueVal]);
785 $dao->setApiFilter($params);
789 * Apply filters (e.g. high, low) to DAO object (prior to find).
791 * @param string $filterField
792 * Field name of filter.
793 * @param string $filterValue
794 * Field value of filter.
798 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
799 if (strstr($filterField, 'high')) {
800 $fieldName = substr($filterField, 0, -5);
801 $dao->whereAdd("($fieldName <= $filterValue )");
803 if (strstr($filterField, 'low')) {
804 $fieldName = substr($filterField, 0, -4);
805 $dao->whereAdd("($fieldName >= $filterValue )");
807 if ($filterField == 'is_current' && $filterValue == 1) {
808 $todayStart = date('Ymd000000', strtotime('now'));
809 $todayEnd = date('Ymd235959', strtotime('now'));
810 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
811 if (property_exists($dao, 'is_active')) {
812 $dao->whereAdd('is_active = 1');
818 * Get sort, limit etc options from the params - supporting old & new formats.
820 * Get returnProperties for legacy
822 * @param array $params
823 * Params array as passed into civicrm_api.
824 * @param bool $queryObject
825 * Is this supporting a queryObject api (e.g contact) - if so we support more options.
826 * for legacy report & return a unique fields array
828 * @param string $entity
829 * @param string $action
831 * @throws API_Exception
833 * options extracted from params
835 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
836 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
838 $sort = CRM_Utils_Array
::value('sort', $params, 0);
839 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
840 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
842 $offset = CRM_Utils_Array
::value('offset', $params, 0);
843 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
844 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
845 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
847 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
848 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
849 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
851 if (is_array(CRM_Utils_Array
::value('options', $params))) {
852 // is count is set by generic getcount not user
853 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
854 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
855 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
856 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
859 $returnProperties = array();
860 // handle the format return =sort_name,display_name...
861 if (array_key_exists('return', $params)) {
862 if (is_array($params['return'])) {
863 $returnProperties = array_fill_keys($params['return'], 1);
866 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
867 $returnProperties = array_fill_keys($returnProperties, 1);
870 if ($entity && $action == 'get') {
871 if (!empty($returnProperties['id'])) {
872 $returnProperties[$lowercase_entity . '_id'] = 1;
873 unset($returnProperties['id']);
875 switch (trim(strtolower($sort))) {
879 $sort = str_replace('id', $lowercase_entity . '_id', $sort);
884 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
885 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
886 'is_count' => $is_count,
887 'return' => !empty($returnProperties) ?
$returnProperties : array(),
890 $finalSort = array();
891 $options['sort'] = NULL;
893 foreach ((array) $sort as $s) {
894 if (CRM_Utils_Rule
::mysqlOrderBy($s)) {
898 throw new API_Exception("Unknown field specified for sort. Cannot order by '$s'");
901 $options['sort'] = implode(', ', $finalSort);
904 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
905 throw new API_Exception('invalid string in sort options');
911 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
912 // if the query object is being used this should be used
913 $inputParams = array();
914 $legacyreturnProperties = array();
916 'sort', 'offset', 'rowCount', 'options', 'return',
917 'version', 'prettyprint', 'check_permissions', 'sequential',
919 foreach ($params as $n => $v) {
920 if (substr($n, 0, 7) == 'return.') {
921 $legacyreturnProperties[substr($n, 7)] = $v;
923 elseif ($n == 'id') {
924 $inputParams[$lowercase_entity . '_id'] = $v;
926 elseif (in_array($n, $otherVars)) {
929 $inputParams[$n] = $v;
930 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
931 throw new API_Exception('invalid string');
935 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
936 $options['input_params'] = $inputParams;
941 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
943 * @param array $params
944 * Params array as passed into civicrm_api.
949 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
951 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
952 if (!$options['is_count']) {
953 if (!empty($options['limit'])) {
954 $dao->limit((int) $options['offset'], (int) $options['limit']);
956 if (!empty($options['sort'])) {
957 $options['sort'] = CRM_Utils_Type
::escape($options['sort'], 'MysqlOrderBy');
958 $dao->orderBy($options['sort']);
964 * Build fields array.
966 * This is the array of fields as it relates to the given DAO
967 * returns unique fields as keys by default but if set but can return by DB fields
969 * @param CRM_Core_DAO $bao
970 * @param bool $unique
974 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
975 $fields = $bao->fields();
977 if (empty($fields['id'])) {
978 $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
979 $fields['id'] = $fields[$lowercase_entity . '_id'];
980 unset($fields[$lowercase_entity . '_id']);
985 foreach ($fields as $field) {
986 $dbFields[$field['name']] = $field;
992 * Build fields array.
994 * This is the array of fields as it relates to the given DAO
995 * returns unique fields as keys by default but if set but can return by DB fields
997 * @param CRM_Core_DAO $bao
1001 function _civicrm_api3_get_unique_name_array(&$bao) {
1002 $fields = $bao->fields();
1003 foreach ($fields as $field => $values) {
1004 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
1006 return $uniqueFields;
1010 * Converts an DAO object to an array.
1012 * @deprecated - DAO based retrieval is being phased out.
1014 * @param CRM_Core_DAO $dao
1015 * Object to convert.
1016 * @param array $params
1017 * @param bool $uniqueFields
1018 * @param string $entity
1019 * @param bool $autoFind
1023 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
1025 if (isset($params['options']) && !empty($params['options']['is_count'])) {
1026 return $dao->count();
1031 if ($autoFind && !$dao->find()) {
1035 if (isset($dao->count
)) {
1039 $fields = array_keys(_civicrm_api3_build_fields_array($dao, FALSE));
1040 while ($dao->fetch()) {
1042 foreach ($fields as $key) {
1043 if (array_key_exists($key, $dao)) {
1044 // not sure on that one
1045 if ($dao->$key !== NULL) {
1046 $tmp[$key] = $dao->$key;
1050 $result[$dao->id
] = $tmp;
1052 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
1053 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
1061 * Determine if custom fields need to be retrieved.
1063 * We currently retrieve all custom fields or none at this level so if we know the entity
1064 * && 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
1065 * @todo filter so only required fields are queried
1067 * @param string $entity
1068 * Entity name in CamelCase.
1069 * @param array $params
1073 function _civicrm_api3_custom_fields_are_required($entity, $params) {
1074 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
1077 $options = _civicrm_api3_get_options_from_params($params);
1078 // We check for possibility of 'custom' => 1 as well as specific custom fields.
1079 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
1080 if (stristr($returnString, 'custom')) {
1086 * Converts an object to an array.
1088 * @param object $dao
1089 * (reference) object to convert.
1090 * @param array $values
1091 * (reference) array.
1092 * @param array|bool $uniqueFields
1094 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
1096 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
1097 foreach ($fields as $key => $value) {
1098 if (array_key_exists($key, $dao)) {
1099 $values[$key] = $dao->$key;
1105 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1112 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1113 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1117 * Format custom parameters.
1119 * @param array $params
1120 * @param array $values
1121 * @param string $extends
1122 * Entity that this custom field extends (e.g. contribution, event, contact).
1123 * @param string $entityId
1124 * ID of entity per $extends.
1126 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1127 $values['custom'] = array();
1128 $checkCheckBoxField = FALSE;
1130 if (in_array($extends, array('Household', 'Individual', 'Organization'))) {
1131 $entity = 'Contact';
1134 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
1135 if (!$fields['is_error']) {
1136 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1137 $fields = $fields['values'];
1138 $checkCheckBoxField = TRUE;
1141 foreach ($params as $key => $value) {
1142 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
1143 if ($customFieldID && (!is_null($value))) {
1144 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1145 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1148 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1149 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1156 * Format parameters for create action.
1158 * @param array $params
1161 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1162 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1164 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery
::$extendsMap, array_fill_keys($nonGenericEntities, 1));
1165 if (!array_key_exists($entity, $customFieldEntities)) {
1169 _civicrm_api3_custom_format_params($params, $values, $entity);
1170 $params = array_merge($params, $values);
1174 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1176 * We should look at pushing to BAO function
1177 * 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
1178 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1180 * 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
1181 * don't touch - lots of very cautious code in here
1183 * The resulting array should look like
1189 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1191 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1192 * be fixed in future
1194 * @param mixed $checkboxFieldValue
1195 * @param string $customFieldLabel
1196 * @param string $entity
1198 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1200 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1201 // We can assume it's pre-formatted.
1204 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1205 if (!empty($options['is_error'])) {
1206 // The check is precautionary - can probably be removed later.
1210 $options = $options['values'];
1212 if (is_array($checkboxFieldValue)) {
1213 foreach ($checkboxFieldValue as $key => $value) {
1214 if (!array_key_exists($key, $options)) {
1215 $validValue = FALSE;
1219 // we have been passed an array that is already in the 'odd' custom field format
1224 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1225 // if the array only has one item we'll treat it like any other string
1226 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1227 $possibleValue = reset($checkboxFieldValue);
1229 if (is_string($checkboxFieldValue)) {
1230 $possibleValue = $checkboxFieldValue;
1232 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1233 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1236 elseif (is_array($checkboxFieldValue)) {
1237 // so this time around we are considering the values in the array
1238 $possibleValues = $checkboxFieldValue;
1239 $formatValue = TRUE;
1241 elseif (stristr($checkboxFieldValue, ',')) {
1242 $formatValue = TRUE;
1243 //lets see if we should separate it - we do this near the end so we
1244 // ensure we have already checked that the comma is not part of a legitimate match
1245 // and of course, we don't make any changes if we don't now have matches
1246 $possibleValues = explode(',', $checkboxFieldValue);
1249 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1253 foreach ($possibleValues as $index => $possibleValue) {
1254 if (array_key_exists($possibleValue, $options)) {
1255 // 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)
1257 elseif (array_key_exists(trim($possibleValue), $options)) {
1258 $possibleValues[$index] = trim($possibleValue);
1261 $formatValue = FALSE;
1265 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1270 * This function ensures that we have the right input parameters.
1274 * This function is only called when $dao is passed into verify_mandatory.
1275 * The practice of passing $dao into verify_mandatory turned out to be
1276 * unsatisfactory as the required fields @ the dao level is so different to the abstract
1277 * api level. Hence the intention is to remove this function
1278 * & the associated param from verify_mandatory
1280 * @param array $params
1281 * Associative array of property name/value.
1282 * pairs to insert in new history.
1283 * @param string $daoName
1284 * @param bool $return
1286 * @daoName string DAO to check params against
1289 * Should the missing fields be returned as an array (core error created as default)
1290 * true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1292 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1293 //@deprecated - see notes
1294 if (isset($params['extends'])) {
1295 if (($params['extends'] == 'Activity' ||
1296 $params['extends'] == 'Phonecall' ||
1297 $params['extends'] == 'Meeting' ||
1298 $params['extends'] == 'Group' ||
1299 $params['extends'] == 'Contribution'
1301 ($params['style'] == 'Tab')
1303 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1307 $dao = new $daoName();
1308 $fields = $dao->fields();
1311 foreach ($fields as $k => $v) {
1312 if ($v['name'] == 'id') {
1316 if (!empty($v['required'])) {
1317 // 0 is a valid input for numbers, CRM-8122
1318 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1324 if (!empty($missing)) {
1325 if (!empty($return)) {
1329 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1337 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1339 * @param string $bao_name
1341 * @param array $params
1343 * @param bool $returnAsSuccess
1344 * Return in api success format.
1345 * @param string $entity
1346 * @param CRM_Utils_SQL_Select|NULL $sql
1347 * Extra SQL bits to add to the query. For filtering current events, this might be:
1348 * CRM_Utils_SQL_Select::fragment()->where('(start_date >= CURDATE() || end_date >= CURDATE())');
1349 * @param bool $uniqueFields
1350 * Should unique field names be returned (for backward compatibility)
1354 function _civicrm_api3_basic_get($bao_name, $params, $returnAsSuccess = TRUE, $entity = "", $sql = NULL, $uniqueFields = FALSE) {
1355 $query = new \Civi\API\
SelectQuery($bao_name, $params, $uniqueFields);
1356 $query->merge($sql);
1357 $result = $query->run();
1358 if ($returnAsSuccess) {
1359 return civicrm_api3_create_success($result, $params, $entity, 'get');
1365 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1367 * @param string $bao_name
1368 * Name of BAO Class.
1369 * @param array $params
1370 * Parameters passed into the api call.
1371 * @param string $entity
1372 * Entity - pass in if entity is non-standard & required $ids array.
1374 * @throws API_Exception
1377 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1378 _civicrm_api3_format_params_for_create($params, $entity);
1379 $args = array(&$params);
1381 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1385 if (method_exists($bao_name, 'create')) {
1387 $fct_name = $bao_name . '::' . $fct;
1388 $bao = call_user_func_array(array($bao_name, $fct), $args);
1390 elseif (method_exists($bao_name, 'add')) {
1392 $fct_name = $bao_name . '::' . $fct;
1393 $bao = call_user_func_array(array($bao_name, $fct), $args);
1396 $fct_name = '_civicrm_api3_basic_create_fallback';
1397 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1400 if (is_null($bao)) {
1401 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1403 elseif (is_a($bao, 'CRM_Core_Error')) {
1404 //some weird circular thing means the error takes itself as an argument
1405 $msg = $bao->getMessages($bao);
1406 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1407 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1408 // so we need to reset the error object here to avoid getting concatenated errors
1409 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1410 CRM_Core_Error
::singleton()->reset();
1411 throw new API_Exception($msg);
1415 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1416 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1421 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1423 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1424 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1426 * @param string $bao_name
1427 * @param array $params
1429 * @throws API_Exception
1431 * @return CRM_Core_DAO|NULL
1432 * An instance of the BAO
1434 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1435 $dao_name = get_parent_class($bao_name);
1436 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1437 $dao_name = $bao_name;
1439 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1440 if (empty($entityName)) {
1441 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1442 'class_name' => $bao_name,
1445 $hook = empty($params['id']) ?
'create' : 'edit';
1447 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1448 $instance = new $dao_name();
1449 $instance->copyValues($params);
1451 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1457 * Function to do a 'standard' api del.
1459 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1461 * @param string $bao_name
1462 * @param array $params
1466 * @throws API_Exception
1468 function _civicrm_api3_basic_delete($bao_name, &$params) {
1470 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1471 $args = array(&$params['id']);
1472 if (method_exists($bao_name, 'del')) {
1473 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1474 if ($bao !== FALSE) {
1475 return civicrm_api3_create_success(TRUE);
1477 throw new API_Exception('Could not delete entity id ' . $params['id']);
1479 elseif (method_exists($bao_name, 'delete')) {
1480 $dao = new $bao_name();
1481 $dao->id
= $params['id'];
1483 while ($dao->fetch()) {
1485 return civicrm_api3_create_success();
1489 throw new API_Exception('Could not delete entity id ' . $params['id']);
1493 throw new API_Exception('no delete method found');
1497 * Get custom data for the given entity & Add it to the returnArray.
1499 * This looks like 'custom_123' = 'custom string' AND
1500 * 'custom_123_1' = 'custom string'
1501 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1503 * @param array $returnArray
1504 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1505 * @param string $entity
1506 * E.g membership, event.
1507 * @param int $entity_id
1508 * @param int $groupID
1509 * Per CRM_Core_BAO_CustomGroup::getTree.
1510 * @param int $subType
1511 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1512 * @param string $subName
1513 * Subtype of entity.
1515 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1516 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1523 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1524 $customValues = array();
1525 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1526 $fieldInfo = array();
1527 foreach ($groupTree as $set) {
1528 $fieldInfo +
= $set['fields'];
1530 if (!empty($customValues)) {
1531 foreach ($customValues as $key => $val) {
1532 // per standard - return custom_fieldID
1533 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1534 $returnArray['custom_' . $id] = $val;
1536 //not standard - but some api did this so guess we should keep - cheap as chips
1537 $returnArray[$key] = $val;
1539 // Shim to restore legacy behavior of ContactReference custom fields
1540 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1541 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1542 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1549 * Validate fields being passed into API.
1551 * This function relies on the getFields function working accurately
1552 * for the given API. If error mode is set to TRUE then it will also check
1555 * As of writing only date was implemented.
1557 * @param string $entity
1558 * @param string $action
1559 * @param array $params
1561 * @param array $fields
1562 * Response from getfields all variables are the same as per civicrm_api.
1563 * @param bool $errorMode
1564 * ErrorMode do intensive post fail checks?.
1568 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = FALSE) {
1569 //CRM-15792 handle datetime for custom fields below code handles chain api call
1570 $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params)));
1571 if (!empty($chainApikeys) && is_array($chainApikeys)) {
1572 foreach ($chainApikeys as $key => $value) {
1573 if (is_array($params[$key])) {
1574 $chainApiParams = array_intersect_key($fields, $params[$key]);
1575 $customFields = array_fill_keys(array_keys($params[$key]), $key);
1579 $fields = array_intersect_key($fields, $params);
1580 if (!empty($chainApiParams)) {
1581 $fields = array_merge($fields, $chainApiParams);
1583 foreach ($fields as $fieldName => $fieldInfo) {
1584 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1585 case CRM_Utils_Type
::T_INT
:
1586 //field is of type integer
1587 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1590 case CRM_Utils_Type
::T_DATE
:
1591 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1592 case CRM_Utils_Type
::T_TIMESTAMP
:
1593 //field is of type date or datetime
1594 if (!empty($customFields) && array_key_exists($fieldName, $customFields)) {
1595 $dateParams = &$params[$customFields[$fieldName]];
1598 $dateParams = &$params;
1600 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
1605 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1608 case CRM_Utils_Type
::T_STRING
:
1609 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1612 case CRM_Utils_Type
::T_MONEY
:
1613 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1614 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1617 foreach ((array) $fieldValue as $fieldvalue) {
1618 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1619 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1625 // intensive checks - usually only called after DB level fail
1626 if (!empty($errorMode) && strtolower($action) == 'create') {
1627 if (!empty($fieldInfo['FKClassName'])) {
1628 if (!empty($fieldValue)) {
1629 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1631 elseif (!empty($fieldInfo['required'])) {
1632 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1635 if (!empty($fieldInfo['api.unique'])) {
1636 $params['entity'] = $entity;
1637 _civicrm_api3_validate_unique_key($params, $fieldName);
1644 * Validate date fields being passed into API.
1646 * It currently converts both unique fields and DB field names to a mysql date.
1647 * @todo - probably the unique field handling & the if exists handling is now done before this
1648 * function is reached in the wrapper - can reduce this code down to assume we
1649 * are only checking the passed in field
1651 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1652 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1654 * @param array $params
1655 * Params from civicrm_api.
1656 * @param string $fieldName
1657 * Uniquename of field being checked.
1658 * @param array $fieldInfo
1659 * Array of fields from getfields function.
1663 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1664 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1665 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1668 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1669 if (!empty($params[$fieldInfo['name']])) {
1670 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1672 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1673 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1677 $params[$fieldName][$op] = $fieldValue;
1680 $params[$fieldName] = $fieldValue;
1685 * Convert date into BAO friendly date.
1687 * We accept 'whatever strtotime accepts'
1689 * @param string $dateValue
1690 * @param string $fieldName
1696 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1697 if (is_array($dateValue)) {
1698 foreach ($dateValue as $key => $value) {
1699 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1703 if (strtotime($dateValue) === FALSE) {
1704 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1706 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1707 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1711 * Validate foreign constraint fields being passed into API.
1713 * @param mixed $fieldValue
1714 * @param string $fieldName
1715 * Uniquename of field being checked.
1716 * @param array $fieldInfo
1717 * Array of fields from getfields function.
1719 * @throws \API_Exception
1721 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1722 $daoName = $fieldInfo['FKClassName'];
1723 $dao = new $daoName();
1724 $dao->id
= $fieldValue;
1726 $dao->selectAdd('id');
1727 if (!$dao->find()) {
1728 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1733 * Validate foreign constraint fields being passed into API.
1735 * @param array $params
1736 * Params from civicrm_api.
1737 * @param string $fieldName
1738 * Uniquename of field being checked.
1742 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1743 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1744 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1747 $existing = civicrm_api($params['entity'], 'get', array(
1748 'version' => $params['version'],
1749 $fieldName => $fieldValue,
1751 // an entry already exists for this unique field
1752 if ($existing['count'] == 1) {
1753 // question - could this ever be a security issue?
1754 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1759 * Generic implementation of the "replace" action.
1761 * Replace the old set of entities (matching some given keys) with a new set of
1762 * entities (matching the same keys).
1764 * @note This will verify that 'values' is present, but it does not directly verify
1765 * any other parameters.
1767 * @param string $entity
1769 * @param array $params
1770 * Params from civicrm_api, including:.
1771 * - 'values': an array of records to save
1772 * - all other items: keys which identify new/pre-existing records.
1776 function _civicrm_api3_generic_replace($entity, $params) {
1778 $transaction = new CRM_Core_Transaction();
1780 if (!is_array($params['values'])) {
1781 throw new Exception("Mandatory key(s) missing from params array: values");
1784 // Extract the keys -- somewhat scary, don't think too hard about it
1785 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1787 // Lookup pre-existing records
1788 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1789 if (civicrm_error($preexisting)) {
1790 $transaction->rollback();
1791 return $preexisting;
1794 // Save the new/updated records
1796 foreach ($params['values'] as $replacement) {
1797 // Sugar: Don't force clients to duplicate the 'key' data
1798 $replacement = array_merge($baseParams, $replacement);
1799 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1800 $create = civicrm_api($entity, $action, $replacement);
1801 if (civicrm_error($create)) {
1802 $transaction->rollback();
1805 foreach ($create['values'] as $entity_id => $entity_value) {
1806 $creates[$entity_id] = $entity_value;
1810 // Remove stale records
1811 $staleIDs = array_diff(
1812 array_keys($preexisting['values']),
1813 array_keys($creates)
1815 foreach ($staleIDs as $staleID) {
1816 $delete = civicrm_api($entity, 'delete', array(
1817 'version' => $params['version'],
1820 if (civicrm_error($delete)) {
1821 $transaction->rollback();
1826 return civicrm_api3_create_success($creates, $params);
1828 catch(PEAR_Exception
$e) {
1829 $transaction->rollback();
1830 return civicrm_api3_create_error($e->getMessage());
1832 catch(Exception
$e) {
1833 $transaction->rollback();
1834 return civicrm_api3_create_error($e->getMessage());
1839 * Replace base parameters.
1841 * @param array $params
1845 function _civicrm_api3_generic_replace_base_params($params) {
1846 $baseParams = $params;
1847 unset($baseParams['values']);
1848 unset($baseParams['sequential']);
1849 unset($baseParams['options']);
1854 * Returns fields allowable by api.
1857 * String Entity to query.
1858 * @param bool $unique
1859 * Index by unique fields?.
1860 * @param array $params
1864 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1865 $unsetIfEmpty = array(
1872 $dao = _civicrm_api3_get_DAO($entity);
1877 $fields = $d->fields();
1878 // replace uniqueNames by the normal names as the key
1879 if (empty($unique)) {
1880 foreach ($fields as $name => &$field) {
1881 //getting rid of unused attributes
1882 foreach ($unsetIfEmpty as $attr) {
1883 if (empty($field[$attr])) {
1884 unset($field[$attr]);
1887 if ($name == $field['name']) {
1890 if (array_key_exists($field['name'], $fields)) {
1891 $field['error'] = 'name conflict';
1892 // it should never happen, but better safe than sorry
1895 $fields[$field['name']] = $field;
1896 $fields[$field['name']]['uniqueName'] = $name;
1897 unset($fields[$name]);
1900 // Translate FKClassName to the corresponding api
1901 foreach ($fields as $name => &$field) {
1902 if (!empty($field['FKClassName'])) {
1903 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1905 $field['FKApiName'] = $FKApi;
1909 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1910 if ($entity == 'Contact') {
1911 $fields +
= _civicrm_api_get_fields('Address');
1917 * Return an array of fields for a given entity.
1919 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1922 * @param array $params
1926 function _civicrm_api_get_custom_fields($entity, &$params) {
1927 $entity = _civicrm_api_get_camel_name($entity);
1928 if ($entity == 'Contact') {
1929 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1930 $entity = CRM_Utils_Array
::value('contact_type', $params);
1932 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1935 // we could / should probably test for other subtypes here - e.g. activity_type_id
1936 CRM_Utils_Array
::value('contact_sub_type', $params),
1945 foreach ($customfields as $key => $value) {
1946 // Regular fields have a 'name' property
1947 $value['name'] = 'custom_' . $key;
1948 $value['title'] = $value['label'];
1949 $value['type'] = _getStandardTypeFromCustomDataType($value);
1950 $ret['custom_' . $key] = $value;
1956 * Translate the custom field data_type attribute into a std 'type'.
1958 * @param array $value
1962 function _getStandardTypeFromCustomDataType($value) {
1963 $dataType = $value['data_type'];
1964 //CRM-15792 - If date custom field contains timeformat change type to DateTime
1965 if ($value['data_type'] == 'Date' && isset($value['time_format']) && $value['time_format'] > 0) {
1966 $dataType = 'DateTime';
1969 'String' => CRM_Utils_Type
::T_STRING
,
1970 'Int' => CRM_Utils_Type
::T_INT
,
1971 'Money' => CRM_Utils_Type
::T_MONEY
,
1972 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1973 'Float' => CRM_Utils_Type
::T_FLOAT
,
1974 'Date' => CRM_Utils_Type
::T_DATE
,
1975 'DateTime' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
1976 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1977 'StateProvince' => CRM_Utils_Type
::T_INT
,
1978 'File' => CRM_Utils_Type
::T_STRING
,
1979 'Link' => CRM_Utils_Type
::T_STRING
,
1980 'ContactReference' => CRM_Utils_Type
::T_INT
,
1981 'Country' => CRM_Utils_Type
::T_INT
,
1983 return $mapping[$dataType];
1988 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
1990 * If multiple aliases the last takes precedence
1992 * Function also swaps unique fields for non-unique fields & vice versa.
1994 * @param $apiRequest
1997 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1998 foreach ($fields as $field => $values) {
1999 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
2000 if (!empty($values['api.aliases'])) {
2001 // if aliased field is not set we try to use field alias
2002 if (!isset($apiRequest['params'][$field])) {
2003 foreach ($values['api.aliases'] as $alias) {
2004 if (isset($apiRequest['params'][$alias])) {
2005 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
2007 //unset original field nb - need to be careful with this as it may bring inconsistencies
2008 // out of the woodwork but will be implementing only as _spec function extended
2009 unset($apiRequest['params'][$alias]);
2013 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
2014 && isset($apiRequest['params'][$values['name']])
2016 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
2017 // note that it would make sense to unset the original field here but tests need to be in place first
2018 if ($field != 'domain_version') {
2019 unset($apiRequest['params'][$values['name']]);
2022 if (!isset($apiRequest['params'][$field])
2024 && $field != $uniqueName
2025 && array_key_exists($uniqueName, $apiRequest['params'])
2027 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
2028 // note that it would make sense to unset the original field here but tests need to be in place first
2035 * Validate integer fields being passed into API.
2037 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
2039 * @param array $params
2040 * Params from civicrm_api.
2041 * @param string $fieldName
2042 * Uniquename of field being checked.
2043 * @param array $fieldInfo
2044 * Array of fields from getfields function.
2045 * @param string $entity
2047 * @throws API_Exception
2049 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
2050 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2051 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2055 if (!empty($fieldValue)) {
2056 // if value = 'user_contact_id' (or similar), replace value with contact id
2057 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
2058 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
2059 if ('unknown-user' === $realContactId) {
2060 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName, "type" => "integer"));
2062 elseif (is_numeric($realContactId)) {
2063 $fieldValue = $realContactId;
2066 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2067 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
2070 // After swapping options, ensure we have an integer(s)
2071 foreach ((array) ($fieldValue) as $value) {
2072 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
2073 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
2077 // Check our field length
2078 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
2080 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
2081 2100, array('field' => $fieldName, "max_length" => $fieldInfo['maxlength'])
2087 $params[$fieldName][$op] = $fieldValue;
2090 $params[$fieldName] = $fieldValue;
2095 * Determine a contact ID using a string expression.
2097 * @param string $contactIdExpr
2098 * E.g. "user_contact_id" or "@user:username".
2100 * @return int|NULL|'unknown-user'
2102 function _civicrm_api3_resolve_contactID($contactIdExpr) {
2103 // If value = 'user_contact_id' replace value with logged in user id.
2104 if ($contactIdExpr == "user_contact_id") {
2105 return CRM_Core_Session
::getLoggedInContactID();
2107 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
2108 $config = CRM_Core_Config
::singleton();
2110 $ufID = $config->userSystem
->getUfId($matches[1]);
2112 return 'unknown-user';
2115 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
2117 return 'unknown-user';
2126 * Validate html (check for scripting attack).
2128 * @param array $params
2129 * @param string $fieldName
2130 * @param array $fieldInfo
2132 * @throws API_Exception
2134 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
2135 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2136 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
2140 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2141 throw new API_Exception('Input contains illegal SCRIPT tag.', array("field" => $fieldName, "error_code" => "xss"));
2147 * Validate string fields being passed into API.
2149 * @param array $params
2150 * Params from civicrm_api.
2151 * @param string $fieldName
2152 * Uniquename of field being checked.
2153 * @param array $fieldInfo
2154 * Array of fields from getfields function.
2155 * @param string $entity
2157 * @throws API_Exception
2160 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2161 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2162 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
2166 if (!is_array($fieldValue)) {
2167 $fieldValue = (string) $fieldValue;
2170 //@todo what do we do about passed in arrays. For many of these fields
2171 // the missing piece of functionality is separating them to a separated string
2172 // & many save incorrectly. But can we change them wholesale?
2175 foreach ((array) $fieldValue as $value) {
2176 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2177 throw new Exception('Input contains illegal SCRIPT tag.');
2179 if ($fieldName == 'currency') {
2180 //When using IN operator $fieldValue is a array of currency codes
2181 if (!CRM_Utils_Rule
::currencyCode($value)) {
2182 throw new Exception("Currency not a valid code: $currency");
2187 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2188 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
2190 // Check our field length
2191 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2192 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2193 2100, array('field' => $fieldName)
2198 $params[$fieldName][$op] = $fieldValue;
2201 $params[$fieldName] = $fieldValue;
2206 * Validate & swap out any pseudoconstants / options.
2208 * @param mixed $fieldValue
2209 * @param string $entity : api entity name
2210 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2211 * @param array $fieldInfo : getfields meta-data
2213 * @throws \API_Exception
2215 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo) {
2216 $options = CRM_Utils_Array
::value('options', $fieldInfo);
2219 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2220 // We need to get the options from the entity the field relates to.
2221 $entity = $fieldInfo['entity'];
2223 $options = civicrm_api($entity, 'getoptions', array(
2225 'field' => $fieldInfo['name'],
2226 'context' => 'validate',
2228 $options = CRM_Utils_Array
::value('values', $options, array());
2231 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2233 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2234 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
2237 // If passed multiple options, validate each.
2238 if (is_array($fieldValue)) {
2239 foreach ($fieldValue as &$value) {
2240 if (!is_array($value)) {
2241 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
2244 // TODO: unwrap the call to implodePadded from the conditional and do it always
2245 // need to verify that this is safe and doesn't break anything though.
2246 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2248 CRM_Utils_Array
::implodePadded($fieldValue);
2252 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName);
2257 * Validate & swap a single option value for a field.
2259 * @param string $value field value
2260 * @param array $options array of options for this field
2261 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2263 * @throws API_Exception
2265 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
2266 // If option is a key, no need to translate
2267 // or if no options are avaiable for pseudoconstant 'table' property
2268 if (array_key_exists($value, $options) ||
!$options) {
2272 // Translate value into key
2273 $newValue = array_search($value, $options);
2274 if ($newValue !== FALSE) {
2278 // Case-insensitive matching
2279 $newValue = strtolower($value);
2280 $options = array_map("strtolower", $options);
2281 $newValue = array_search($newValue, $options);
2282 if ($newValue === FALSE) {
2283 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
2289 * Returns the canonical name of a field.
2292 * api entity name (string should already be standardized - no camelCase).
2294 * any variation of a field's name (name, unique_name, api.alias).
2296 * @return bool|string
2297 * fieldName or FALSE if the field does not exist
2299 function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') {
2303 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2306 if ($fieldName == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
2309 $result = civicrm_api($entity, 'getfields', array(
2311 'action' => $action,
2313 $meta = $result['values'];
2314 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2315 $fieldName = $fieldName . '_id';
2317 if (isset($meta[$fieldName])) {
2318 return $meta[$fieldName]['name'];
2320 foreach ($meta as $info) {
2321 if ($fieldName == $info['name'] ||
$fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2322 return $info['name'];
2324 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
2325 return $info['name'];
2328 // Create didn't work, try with get
2329 if ($action == 'create') {
2330 return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get');
2336 * Check if the function is deprecated.
2338 * @param string $entity
2339 * @param array $result
2341 * @return string|array|null
2343 function _civicrm_api3_deprecation_check($entity, $result = array()) {
2345 $apiFile = "api/v3/$entity.php";
2346 if (CRM_Utils_File
::isIncludable($apiFile)) {
2347 require_once $apiFile;
2349 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
2350 $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation";
2351 if (function_exists($fnName)) {
2352 return $fnName($result);
2358 * Get the actual field value.
2360 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2361 * So this function returns the actual field value
2363 * @param array $params
2364 * @param string $fieldName
2368 function _civicrm_api3_field_value_check(&$params, $fieldName) {
2369 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2372 if (!empty($fieldValue) && is_array($fieldValue) && array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators())) {
2373 $op = key($fieldValue);
2374 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2376 return array($fieldValue, $op);
2380 * A generic "get" API based on simple array data. This is comparable to
2381 * _civicrm_api3_basic_get but does not use DAO/BAO. This is useful for
2382 * small/mid-size data loaded from external JSON or XML documents.
2385 * @param array $params
2387 * @param array $records
2388 * List of all records.
2389 * @param string $idCol
2390 * The property which defines the ID of a record
2391 * @param array $fields
2392 * List of filterable fields.
2395 * @throws \API_Exception
2397 function _civicrm_api3_basic_array_get($entity, $params, $records, $idCol, $fields) {
2398 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
2399 // TODO // $sort = CRM_Utils_Array::value('sort', $options, NULL);
2400 $offset = CRM_Utils_Array
::value('offset', $options);
2401 $limit = CRM_Utils_Array
::value('limit', $options);
2406 foreach ($records as $record) {
2407 if ($idCol != 'id') {
2408 $record['id'] = $record[$idCol];
2411 foreach ($params as $k => $v) {
2415 if (in_array($k, $fields) && $record[$k] != $v) {
2421 if ($currentOffset >= $offset) {
2422 $matches[$record[$idCol]] = $record;
2424 if ($limit && count($matches) >= $limit) {
2431 $return = CRM_Utils_Array
::value('return', $options, array());
2432 if (!empty($return)) {
2434 $matches = CRM_Utils_Array
::filterColumns($matches, array_keys($return));
2437 return civicrm_api3_create_success($matches, $params);