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 _civicrm_api3_separate_values($values);
236 if ($result['count'] == 1) {
237 list($result['id']) = array_keys($values);
239 elseif (!empty($values['id']) && is_int($values['id'])) {
240 $result['id'] = $values['id'];
244 $result['count'] = !empty($values) ?
1 : 0;
247 if (is_array($values) && isset($params['sequential']) &&
248 $params['sequential'] == 1
250 $result['values'] = array_values($values);
253 $result['values'] = $values;
255 if (!empty($params['options']['metadata'])) {
256 // We've made metadata an array but only supporting 'fields' atm.
257 if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
258 $fields = civicrm_api3($entity, 'getfields', array(
259 'action' => substr($action, 0, 3) == 'get' ?
'get' : 'create',
261 $result['metadata']['fields'] = $fields['values'];
264 // Report deprecations.
265 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
266 // The "setvalue" action is deprecated but still in use, so report it only on "getactions".
267 if (!is_string($deprecated) && $action == 'getactions') {
268 $deprecated = ((array) $deprecated) +
array('setvalue' => 'The "setvalue" action is deprecated. Use "create" with an id instead.');
270 // Always report "update" action as deprecated.
271 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'update')) {
272 $deprecated = ((array) $deprecated) +
array('update' => 'The "update" action is deprecated. Use "create" with an id instead.');
275 // Metadata-level deprecations or wholesale entity deprecations.
276 if ($entity == 'Entity' ||
$action == 'getactions' ||
is_string($deprecated)) {
277 $result['deprecated'] = $deprecated;
279 // Action-specific deprecations
280 elseif (!empty($deprecated[$action])) {
281 $result['deprecated'] = $deprecated[$action];
284 return array_merge($result, $extraReturnValues);
288 * Load the DAO of the entity.
294 function _civicrm_api3_load_DAO($entity) {
295 $dao = _civicrm_api3_get_DAO($entity);
304 * Return the DAO of the function or Entity.
306 * @param string $name
307 * Either a function of the api (civicrm_{entity}_create or the entity name.
308 * return the DAO name to manipulate this function
309 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
311 * @return mixed|string
313 function _civicrm_api3_get_DAO($name) {
314 if (strpos($name, 'civicrm_api3') !== FALSE) {
315 $last = strrpos($name, '_');
316 // len ('civicrm_api3_') == 13
317 $name = substr($name, 13, $last - 13);
320 $name = _civicrm_api_get_camel_name($name);
322 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
326 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
328 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
329 if ($name == 'MailingEventQueue') {
330 return 'CRM_Mailing_Event_DAO_Queue';
332 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
333 // but am not confident mailing_recipients is tested so have not tackled.
334 if ($name == 'MailingRecipients') {
335 return 'CRM_Mailing_DAO_Recipients';
337 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
338 if ($name == 'MailingComponent') {
339 return 'CRM_Mailing_DAO_Component';
341 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
342 if ($name == 'AclRole') {
343 return 'CRM_ACL_DAO_EntityRole';
345 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
346 // But this would impact SMS extensions so need to coordinate
347 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
348 if ($name == 'SmsProvider') {
349 return 'CRM_SMS_DAO_Provider';
351 // FIXME: DAO names should follow CamelCase convention
352 if ($name == 'Im' ||
$name == 'Acl') {
353 $name = strtoupper($name);
355 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
356 if ($dao ||
!$name) {
360 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
361 if (file_exists("api/v3/$name.php")) {
362 include_once "api/v3/$name.php";
365 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
366 if (function_exists($daoFn)) {
374 * Return the DAO of the function or Entity.
376 * @param string $name
377 * Is either a function of the api (civicrm_{entity}_create or the entity name.
378 * return the DAO name to manipulate this function
379 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
383 function _civicrm_api3_get_BAO($name) {
384 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
385 if ($name == 'PrintLabel') {
386 return 'CRM_Badge_BAO_Layout';
388 $dao = _civicrm_api3_get_DAO($name);
392 $bao = str_replace("DAO", "BAO", $dao);
393 $file = strtr($bao, '_', '/') . '.php';
394 // Check if this entity actually has a BAO. Fall back on the DAO if not.
395 return stream_resolve_include_path($file) ?
$bao : $dao;
399 * Recursive function to explode value-separated strings into arrays.
403 function _civicrm_api3_separate_values(&$values) {
404 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
405 foreach ($values as $key => & $value) {
406 if (is_array($value)) {
407 _civicrm_api3_separate_values($value);
409 elseif (is_string($value)) {
410 // This is to honor the way case API was originally written.
411 if ($key == 'case_type_id') {
412 $value = trim(str_replace($sp, ',', $value), ',');
414 elseif (strpos($value, $sp) !== FALSE) {
415 $value = explode($sp, trim($value, $sp));
422 * This is a legacy wrapper for api_store_values.
424 * It checks suitable fields using getfields rather than DAO->fields.
426 * Getfields has handling for how to deal with unique names which dao->fields doesn't
428 * Note this is used by BAO type create functions - eg. contribution
430 * @param string $entity
431 * @param array $params
432 * @param array $values
434 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
435 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
436 $fields = $fields['values'];
437 _civicrm_api3_store_values($fields, $params, $values);
442 * @param array $fields
443 * @param array $params
444 * @param array $values
448 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
451 $keys = array_intersect_key($params, $fields);
452 foreach ($keys as $name => $value) {
453 if ($name !== 'id') {
454 $values[$name] = $value;
462 * Get function for query object api.
464 * The API supports 2 types of get request. The more complex uses the BAO query object.
465 * This is a generic function for those functions that call it
467 * At the moment only called by contact we should extend to contribution &
468 * others that use the query object. Note that this function passes permission information in.
471 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
475 * @param array $params
476 * As passed into api get or getcount function.
477 * @param array $additional_options
478 * Array of options (so we can modify the filter).
479 * @param bool $getCount
480 * Are we just after the count.
484 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL) {
485 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
486 // Convert id to e.g. contact_id
487 if (empty($params[$lowercase_entity . '_id']) && isset($params['id'])) {
488 $params[$lowercase_entity . '_id'] = $params['id'];
490 unset($params['id']);
492 $options = _civicrm_api3_get_options_from_params($params, TRUE);
494 $inputParams = array_merge(
495 CRM_Utils_Array
::value('input_params', $options, array()),
496 CRM_Utils_Array
::value('input_params', $additional_options, array())
498 $returnProperties = array_merge(
499 CRM_Utils_Array
::value('return', $options, array()),
500 CRM_Utils_Array
::value('return', $additional_options, array())
502 if (empty($returnProperties)) {
503 $returnProperties = NULL;
505 if (!empty($params['check_permissions'])) {
506 // we will filter query object against getfields
507 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
508 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
509 $fields['values'][$lowercase_entity . '_id'] = array();
510 $varsToFilter = array('returnProperties', 'inputParams');
511 foreach ($varsToFilter as $varToFilter) {
512 if (!is_array($
$varToFilter)) {
515 //I was going to throw an exception rather than silently filter out - but
516 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
517 //so we are silently ignoring parts of their request
518 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
519 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
522 $options = array_merge($options, $additional_options);
523 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
524 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
525 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
526 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
530 $returnProperties = NULL;
533 if (substr($sort, 0, 2) == 'id') {
534 $sort = $lowercase_entity . "_" . $sort;
537 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
538 foreach ($newParams as &$newParam) {
539 if ($newParam[1] == '=' && is_array($newParam[2])) {
540 // we may be looking at an attempt to use the 'IN' style syntax
541 // @todo at time of writing only 'IN' & 'NOT IN' are supported for the array style syntax
542 $sqlFilter = CRM_Core_DAO
::createSqlFilter($newParam[0], $params[$newParam[0]], 'String', NULL, TRUE);
544 $newParam[1] = key($newParam[2]);
545 $newParam[2] = $sqlFilter;
550 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
552 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
564 // only return the count of contacts
572 * Get dao query object based on input params.
574 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
577 * @param array $params
578 * @param string $mode
579 * @param string $entity
582 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
584 function _civicrm_api3_get_query_object($params, $mode, $entity) {
585 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
586 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
587 $offset = CRM_Utils_Array
::value('offset', $options);
588 $rowCount = CRM_Utils_Array
::value('limit', $options);
589 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
590 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
591 if (empty($returnProperties)) {
592 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
595 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
596 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
598 empty($params['check_permissions'])
600 list($select, $from, $where, $having) = $query->query();
602 $sql = "$select $from $where $having";
605 $sql .= " ORDER BY $sort ";
607 if (!empty($rowCount)) {
608 $sql .= " LIMIT $offset, $rowCount ";
610 $dao = CRM_Core_DAO
::executeQuery($sql);
611 return array($dao, $query);
615 * Function transfers the filters being passed into the DAO onto the params object.
617 * @param CRM_Core_DAO $dao
618 * @param array $params
619 * @param bool $unique
621 * @throws API_Exception
624 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE) {
625 $entity = _civicrm_api_get_entity_name_from_dao($dao);
626 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
627 if (!empty($params[$lowercase_entity . "_id"]) && empty($params['id'])) {
628 //if entity_id is set then treat it as ID (will be overridden by id if set)
629 $params['id'] = $params[$lowercase_entity . "_id"];
631 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
632 $fields = array_intersect(array_keys($allfields), array_keys($params));
634 $options = _civicrm_api3_get_options_from_params($params);
635 //apply options like sort
636 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
638 //accept filters like filter.activity_date_time_high
639 // std is now 'filters' => ..
640 if (strstr(implode(',', array_keys($params)), 'filter')) {
641 if (isset($params['filters']) && is_array($params['filters'])) {
642 foreach ($params['filters'] as $paramkey => $paramvalue) {
643 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
647 foreach ($params as $paramkey => $paramvalue) {
648 if (strstr($paramkey, 'filter')) {
649 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
658 foreach ($fields as $field) {
659 if (is_array($params[$field])) {
660 //get the actual fieldname from db
661 $fieldName = $allfields[$field]['name'];
662 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
663 if (!empty($where)) {
664 $dao->whereAdd($where);
669 $daoFieldName = $allfields[$field]['name'];
670 if (empty($daoFieldName)) {
671 throw new API_Exception("Failed to determine field name for \"$field\"");
673 $dao->{$daoFieldName} = $params[$field];
676 $dao->$field = $params[$field];
680 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
682 // Ensure 'id' is included.
683 $options['return']['id'] = TRUE;
684 $allfields = _civicrm_api3_get_unique_name_array($dao);
685 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
686 foreach ($returnMatched as $returnValue) {
687 $dao->selectAdd($returnValue);
690 // Not already matched on the field names.
691 $unmatchedFields = array_diff(
692 array_keys($options['return']),
696 $returnUniqueMatched = array_intersect(
698 // But a match for the field keys.
699 array_flip($allfields)
701 foreach ($returnUniqueMatched as $uniqueVal) {
702 $dao->selectAdd($allfields[$uniqueVal]);
705 $dao->setApiFilter($params);
709 * Apply filters (e.g. high, low) to DAO object (prior to find).
711 * @param string $filterField
712 * Field name of filter.
713 * @param string $filterValue
714 * Field value of filter.
718 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
719 if (strstr($filterField, 'high')) {
720 $fieldName = substr($filterField, 0, -5);
721 $dao->whereAdd("($fieldName <= $filterValue )");
723 if (strstr($filterField, 'low')) {
724 $fieldName = substr($filterField, 0, -4);
725 $dao->whereAdd("($fieldName >= $filterValue )");
727 if ($filterField == 'is_current' && $filterValue == 1) {
728 $todayStart = date('Ymd000000', strtotime('now'));
729 $todayEnd = date('Ymd235959', strtotime('now'));
730 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
731 if (property_exists($dao, 'is_active')) {
732 $dao->whereAdd('is_active = 1');
738 * Get sort, limit etc options from the params - supporting old & new formats.
740 * Get returnProperties for legacy
742 * @param array $params
743 * Params array as passed into civicrm_api.
744 * @param bool $queryObject
745 * Is this supporting a queryObject api (e.g contact) - if so we support more options.
746 * for legacy report & return a unique fields array
748 * @param string $entity
749 * @param string $action
751 * @throws API_Exception
753 * options extracted from params
755 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
756 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
758 $sort = CRM_Utils_Array
::value('sort', $params, 0);
759 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
760 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
762 $offset = CRM_Utils_Array
::value('offset', $params, 0);
763 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
764 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
765 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
767 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
768 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
769 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
771 if (is_array(CRM_Utils_Array
::value('options', $params))) {
772 // is count is set by generic getcount not user
773 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
774 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
775 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
776 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
779 $returnProperties = array();
780 // handle the format return =sort_name,display_name...
781 if (array_key_exists('return', $params)) {
782 if (is_array($params['return'])) {
783 $returnProperties = array_fill_keys($params['return'], 1);
786 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
787 $returnProperties = array_fill_keys($returnProperties, 1);
790 if ($entity && $action == 'get') {
791 if (!empty($returnProperties['id'])) {
792 $returnProperties[$lowercase_entity . '_id'] = 1;
793 unset($returnProperties['id']);
795 switch (trim(strtolower($sort))) {
799 $sort = str_replace('id', $lowercase_entity . '_id', $sort);
804 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
805 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
806 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
807 'is_count' => $is_count,
808 'return' => !empty($returnProperties) ?
$returnProperties : array(),
811 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
812 throw new API_Exception('invalid string in sort options');
818 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
819 // if the queryobject is being used this should be used
820 $inputParams = array();
821 $legacyreturnProperties = array();
823 'sort', 'offset', 'rowCount', 'options', 'return',
824 'version', 'prettyprint', 'check_permissions', 'sequential',
826 foreach ($params as $n => $v) {
827 if (substr($n, 0, 7) == 'return.') {
828 $legacyreturnProperties[substr($n, 7)] = $v;
830 elseif ($n == 'id') {
831 $inputParams[$lowercase_entity . '_id'] = $v;
833 elseif (in_array($n, $otherVars)) {
836 $inputParams[$n] = $v;
837 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
838 throw new API_Exception('invalid string');
842 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
843 $options['input_params'] = $inputParams;
848 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
850 * @param array $params
851 * Params array as passed into civicrm_api.
856 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
858 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
859 if (!$options['is_count']) {
860 if (!empty($options['limit'])) {
861 $dao->limit((int) $options['offset'], (int) $options['limit']);
863 if (!empty($options['sort'])) {
864 $dao->orderBy($options['sort']);
870 * Build fields array.
872 * This is the array of fields as it relates to the given DAO
873 * returns unique fields as keys by default but if set but can return by DB fields
875 * @param CRM_Core_DAO $bao
876 * @param bool $unique
880 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
881 $fields = $bao->fields();
883 if (empty($fields['id'])) {
884 $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
885 $fields['id'] = $fields[$lowercase_entity . '_id'];
886 unset($fields[$lowercase_entity . '_id']);
891 foreach ($fields as $field) {
892 $dbFields[$field['name']] = $field;
898 * Build fields array.
900 * This is the array of fields as it relates to the given DAO
901 * returns unique fields as keys by default but if set but can return by DB fields
903 * @param CRM_Core_DAO $bao
907 function _civicrm_api3_get_unique_name_array(&$bao) {
908 $fields = $bao->fields();
909 foreach ($fields as $field => $values) {
910 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
912 return $uniqueFields;
916 * Converts an DAO object to an array.
918 * @param CRM_Core_DAO $dao
920 * @param array $params
921 * @param bool $uniqueFields
922 * @param string $entity
923 * @param bool $autoFind
927 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
929 if (isset($params['options']) && !empty($params['options']['is_count'])) {
930 return $dao->count();
935 if ($autoFind && !$dao->find()) {
939 if (isset($dao->count
)) {
943 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
945 while ($dao->fetch()) {
947 foreach ($fields as $key) {
948 if (array_key_exists($key, $dao)) {
949 // not sure on that one
950 if ($dao->$key !== NULL) {
951 $tmp[$key] = $dao->$key;
955 $result[$dao->id
] = $tmp;
957 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
958 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
966 * Determine if custom fields need to be retrieved.
968 * We currently retrieve all custom fields or none at this level so if we know the entity
969 * && 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
970 * @todo filter so only required fields are queried
972 * @param string $entity
973 * Entity name in CamelCase.
974 * @param array $params
978 function _civicrm_api3_custom_fields_are_required($entity, $params) {
979 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
982 $options = _civicrm_api3_get_options_from_params($params);
983 // We check for possibility of 'custom' => 1 as well as specific custom fields.
984 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
985 if (stristr($returnString, 'custom')) {
990 * Converts an object to an array.
993 * (reference) object to convert.
994 * @param array $values
996 * @param array|bool $uniqueFields
998 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
1000 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
1001 foreach ($fields as $key => $value) {
1002 if (array_key_exists($key, $dao)) {
1003 $values[$key] = $dao->$key;
1009 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1016 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1017 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1021 * Format custom parameters.
1023 * @param array $params
1024 * @param array $values
1025 * @param string $extends
1026 * Entity that this custom field extends (e.g. contribution, event, contact).
1027 * @param string $entityId
1028 * ID of entity per $extends.
1030 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1031 $values['custom'] = array();
1032 $checkCheckBoxField = FALSE;
1034 if (in_array($extends, array('Household', 'Individual', 'Organization'))) {
1035 $entity = 'Contact';
1038 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
1039 if (!$fields['is_error']) {
1040 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1041 $fields = $fields['values'];
1042 $checkCheckBoxField = TRUE;
1045 foreach ($params as $key => $value) {
1046 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
1047 if ($customFieldID && (!is_null($value))) {
1048 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1049 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1052 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1053 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1060 * Format parameters for create action.
1062 * @param array $params
1065 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1066 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1068 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery
::$extendsMap, array_fill_keys($nonGenericEntities, 1));
1069 if (!array_key_exists($entity, $customFieldEntities)) {
1073 _civicrm_api3_custom_format_params($params, $values, $entity);
1074 $params = array_merge($params, $values);
1078 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1080 * We should look at pushing to BAO function
1081 * 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
1082 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1084 * 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
1085 * don't touch - lots of very cautious code in here
1087 * The resulting array should look like
1093 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1095 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1096 * be fixed in future
1098 * @param mixed $checkboxFieldValue
1099 * @param string $customFieldLabel
1100 * @param string $entity
1102 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1104 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1105 // We can assume it's pre-formatted.
1108 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1109 if (!empty($options['is_error'])) {
1110 // The check is precautionary - can probably be removed later.
1114 $options = $options['values'];
1116 if (is_array($checkboxFieldValue)) {
1117 foreach ($checkboxFieldValue as $key => $value) {
1118 if (!array_key_exists($key, $options)) {
1119 $validValue = FALSE;
1123 // we have been passed an array that is already in the 'odd' custom field format
1128 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1129 // if the array only has one item we'll treat it like any other string
1130 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1131 $possibleValue = reset($checkboxFieldValue);
1133 if (is_string($checkboxFieldValue)) {
1134 $possibleValue = $checkboxFieldValue;
1136 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1137 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1140 elseif (is_array($checkboxFieldValue)) {
1141 // so this time around we are considering the values in the array
1142 $possibleValues = $checkboxFieldValue;
1143 $formatValue = TRUE;
1145 elseif (stristr($checkboxFieldValue, ',')) {
1146 $formatValue = TRUE;
1147 //lets see if we should separate it - we do this near the end so we
1148 // ensure we have already checked that the comma is not part of a legitimate match
1149 // and of course, we don't make any changes if we don't now have matches
1150 $possibleValues = explode(',', $checkboxFieldValue);
1153 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1157 foreach ($possibleValues as $index => $possibleValue) {
1158 if (array_key_exists($possibleValue, $options)) {
1159 // 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)
1161 elseif (array_key_exists(trim($possibleValue), $options)) {
1162 $possibleValues[$index] = trim($possibleValue);
1165 $formatValue = FALSE;
1169 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1174 * This function ensures that we have the right input parameters.
1178 * This function is only called when $dao is passed into verify_mandatory.
1179 * The practice of passing $dao into verify_mandatory turned out to be
1180 * unsatisfactory as the required fields @ the dao level is so different to the abstract
1181 * api level. Hence the intention is to remove this function
1182 * & the associated param from verify_mandatory
1184 * @param array $params
1185 * Associative array of property name/value.
1186 * pairs to insert in new history.
1187 * @param string $daoName
1188 * @param bool $return
1190 * @daoName string DAO to check params agains
1193 * Should the missing fields be returned as an array (core error created as default)
1194 * true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1196 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1197 //@deprecated - see notes
1198 if (isset($params['extends'])) {
1199 if (($params['extends'] == 'Activity' ||
1200 $params['extends'] == 'Phonecall' ||
1201 $params['extends'] == 'Meeting' ||
1202 $params['extends'] == 'Group' ||
1203 $params['extends'] == 'Contribution'
1205 ($params['style'] == 'Tab')
1207 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1211 $dao = new $daoName();
1212 $fields = $dao->fields();
1215 foreach ($fields as $k => $v) {
1216 if ($v['name'] == 'id') {
1220 if (!empty($v['required'])) {
1221 // 0 is a valid input for numbers, CRM-8122
1222 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1228 if (!empty($missing)) {
1229 if (!empty($return)) {
1233 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1241 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1243 * @param string $bao_name
1245 * @param array $params
1247 * @param bool $returnAsSuccess
1248 * Return in api success format.
1249 * @param string $entity
1253 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1254 $bao = new $bao_name();
1255 _civicrm_api3_dao_set_filter($bao, $params, TRUE);
1256 if ($returnAsSuccess) {
1257 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1260 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity, 'get');
1265 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1267 * @param string $bao_name
1268 * Name of BAO Class.
1269 * @param array $params
1270 * Parameters passed into the api call.
1271 * @param string $entity
1272 * Entity - pass in if entity is non-standard & required $ids array.
1274 * @throws API_Exception
1277 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1278 _civicrm_api3_format_params_for_create($params, $entity);
1279 $args = array(&$params);
1281 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1285 if (method_exists($bao_name, 'create')) {
1287 $fct_name = $bao_name . '::' . $fct;
1288 $bao = call_user_func_array(array($bao_name, $fct), $args);
1290 elseif (method_exists($bao_name, 'add')) {
1292 $fct_name = $bao_name . '::' . $fct;
1293 $bao = call_user_func_array(array($bao_name, $fct), $args);
1296 $fct_name = '_civicrm_api3_basic_create_fallback';
1297 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1300 if (is_null($bao)) {
1301 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1303 elseif (is_a($bao, 'CRM_Core_Error')) {
1304 //some wierd circular thing means the error takes itself as an argument
1305 $msg = $bao->getMessages($bao);
1306 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1307 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1308 // so we need to reset the error object here to avoid getting concatenated errors
1309 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1310 CRM_Core_Error
::singleton()->reset();
1311 throw new API_Exception($msg);
1315 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1316 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1321 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1323 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1324 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1326 * @param string $bao_name
1327 * @param array $params
1329 * @throws API_Exception
1331 * @return CRM_Core_DAO|NULL
1332 * An instance of the BAO
1334 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1335 $dao_name = get_parent_class($bao_name);
1336 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1337 $dao_name = $bao_name;
1339 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1340 if (empty($entityName)) {
1341 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1342 'class_name' => $bao_name,
1345 $hook = empty($params['id']) ?
'create' : 'edit';
1347 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1348 $instance = new $dao_name();
1349 $instance->copyValues($params);
1351 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1357 * Function to do a 'standard' api del.
1359 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1361 * @param string $bao_name
1362 * @param array $params
1366 * @throws API_Exception
1368 function _civicrm_api3_basic_delete($bao_name, &$params) {
1370 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1371 $args = array(&$params['id']);
1372 if (method_exists($bao_name, 'del')) {
1373 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1374 if ($bao !== FALSE) {
1375 return civicrm_api3_create_success(TRUE);
1377 throw new API_Exception('Could not delete entity id ' . $params['id']);
1379 elseif (method_exists($bao_name, 'delete')) {
1380 $dao = new $bao_name();
1381 $dao->id
= $params['id'];
1383 while ($dao->fetch()) {
1385 return civicrm_api3_create_success();
1389 throw new API_Exception('Could not delete entity id ' . $params['id']);
1393 throw new API_Exception('no delete method found');
1397 * Get custom data for the given entity & Add it to the returnArray.
1399 * This looks like 'custom_123' = 'custom string' AND
1400 * 'custom_123_1' = 'custom string'
1401 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1403 * @param array $returnArray
1404 * Array to append custom data too - generally $result[4] where 4 is the entity id.
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, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1416 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1417 CRM_Core_DAO
::$_nullObject,
1423 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1424 $customValues = array();
1425 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1426 $fieldInfo = array();
1427 foreach ($groupTree as $set) {
1428 $fieldInfo +
= $set['fields'];
1430 if (!empty($customValues)) {
1431 foreach ($customValues as $key => $val) {
1432 // per standard - return custom_fieldID
1433 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1434 $returnArray['custom_' . $id] = $val;
1436 //not standard - but some api did this so guess we should keep - cheap as chips
1437 $returnArray[$key] = $val;
1439 // Shim to restore legacy behavior of ContactReference custom fields
1440 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1441 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1442 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1449 * Validate fields being passed into API.
1451 * This function relies on the getFields function working accurately
1452 * for the given API. If error mode is set to TRUE then it will also check
1455 * As of writing only date was implemented.
1457 * @param string $entity
1458 * @param string $action
1459 * @param array $params
1461 * @param array $fields
1462 * Response from getfields all variables are the same as per civicrm_api.
1463 * @param bool $errorMode
1464 * ErrorMode do intensive post fail checks?.
1468 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = FALSE) {
1469 //CRM-15792 handle datetime for custom fields below code handles chain api call
1470 $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params)));
1471 if (!empty($chainApikeys) && is_array($chainApikeys)) {
1472 foreach ($chainApikeys as $key => $value) {
1473 if (is_array($params[$key])) {
1474 $chainApiParams = array_intersect_key($fields, $params[$key]);
1475 $customFields = array_fill_keys(array_keys($params[$key]), $key);
1479 $fields = array_intersect_key($fields, $params);
1480 if (!empty($chainApiParams)) {
1481 $fields = array_merge($fields, $chainApiParams);
1483 foreach ($fields as $fieldName => $fieldInfo) {
1484 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1485 case CRM_Utils_Type
::T_INT
:
1486 //field is of type integer
1487 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1490 case CRM_Utils_Type
::T_DATE
:
1491 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1492 case CRM_Utils_Type
::T_TIMESTAMP
:
1493 //field is of type date or datetime
1494 if (!empty($customFields) && array_key_exists($fieldName, $customFields)) {
1495 $dateParams = &$params[$customFields[$fieldName]];
1498 $dateParams = &$params;
1500 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
1505 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1508 case CRM_Utils_Type
::T_STRING
:
1509 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1512 case CRM_Utils_Type
::T_MONEY
:
1513 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1514 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1517 foreach ((array) $fieldValue as $fieldvalue) {
1518 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1519 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1525 // intensive checks - usually only called after DB level fail
1526 if (!empty($errorMode) && strtolower($action) == 'create') {
1527 if (!empty($fieldInfo['FKClassName'])) {
1528 if (!empty($fieldValue)) {
1529 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1531 elseif (!empty($fieldInfo['required'])) {
1532 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1535 if (!empty($fieldInfo['api.unique'])) {
1536 $params['entity'] = $entity;
1537 _civicrm_api3_validate_unique_key($params, $fieldName);
1544 * Validate date fields being passed into API.
1546 * It currently converts both unique fields and DB field names to a mysql date.
1547 * @todo - probably the unique field handling & the if exists handling is now done before this
1548 * function is reached in the wrapper - can reduce this code down to assume we
1549 * are only checking the passed in field
1551 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1552 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1554 * @param array $params
1555 * Params from civicrm_api.
1556 * @param string $fieldName
1557 * Uniquename of field being checked.
1558 * @param array $fieldInfo
1559 * Array of fields from getfields function.
1563 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1564 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1565 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1568 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1569 if (!empty($params[$fieldInfo['name']])) {
1570 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1572 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1573 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1577 $params[$fieldName][$op] = $fieldValue;
1580 $params[$fieldName] = $fieldValue;
1585 * Convert date into BAO friendly date.
1587 * We accept 'whatever strtotime accepts'
1589 * @param string $dateValue
1590 * @param string $fieldName
1596 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1597 if (is_array($dateValue)) {
1598 foreach ($dateValue as $key => $value) {
1599 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1603 if (strtotime($dateValue) === FALSE) {
1604 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1606 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1607 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1611 * Validate foreign constraint fields being passed into API.
1613 * @param mixed $fieldValue
1614 * @param string $fieldName
1615 * Uniquename of field being checked.
1616 * @param array $fieldInfo
1617 * Array of fields from getfields function.
1619 * @throws \API_Exception
1621 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1622 $daoName = $fieldInfo['FKClassName'];
1623 $dao = new $daoName();
1624 $dao->id
= $fieldValue;
1626 $dao->selectAdd('id');
1627 if (!$dao->find()) {
1628 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1633 * Validate foreign constraint fields being passed into API.
1635 * @param array $params
1636 * Params from civicrm_api.
1637 * @param string $fieldName
1638 * Uniquename of field being checked.
1642 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1643 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1644 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1647 $existing = civicrm_api($params['entity'], 'get', array(
1648 'version' => $params['version'],
1649 $fieldName => $fieldValue,
1651 // an entry already exists for this unique field
1652 if ($existing['count'] == 1) {
1653 // question - could this ever be a security issue?
1654 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1659 * Generic implementation of the "replace" action.
1661 * Replace the old set of entities (matching some given keys) with a new set of
1662 * entities (matching the same keys).
1664 * @note This will verify that 'values' is present, but it does not directly verify
1665 * any other parameters.
1667 * @param string $entity
1669 * @param array $params
1670 * Params from civicrm_api, including:.
1671 * - 'values': an array of records to save
1672 * - all other items: keys which identify new/pre-existing records.
1676 function _civicrm_api3_generic_replace($entity, $params) {
1678 $transaction = new CRM_Core_Transaction();
1680 if (!is_array($params['values'])) {
1681 throw new Exception("Mandatory key(s) missing from params array: values");
1684 // Extract the keys -- somewhat scary, don't think too hard about it
1685 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1687 // Lookup pre-existing records
1688 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1689 if (civicrm_error($preexisting)) {
1690 $transaction->rollback();
1691 return $preexisting;
1694 // Save the new/updated records
1696 foreach ($params['values'] as $replacement) {
1697 // Sugar: Don't force clients to duplicate the 'key' data
1698 $replacement = array_merge($baseParams, $replacement);
1699 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1700 $create = civicrm_api($entity, $action, $replacement);
1701 if (civicrm_error($create)) {
1702 $transaction->rollback();
1705 foreach ($create['values'] as $entity_id => $entity_value) {
1706 $creates[$entity_id] = $entity_value;
1710 // Remove stale records
1711 $staleIDs = array_diff(
1712 array_keys($preexisting['values']),
1713 array_keys($creates)
1715 foreach ($staleIDs as $staleID) {
1716 $delete = civicrm_api($entity, 'delete', array(
1717 'version' => $params['version'],
1720 if (civicrm_error($delete)) {
1721 $transaction->rollback();
1726 return civicrm_api3_create_success($creates, $params);
1728 catch(PEAR_Exception
$e) {
1729 $transaction->rollback();
1730 return civicrm_api3_create_error($e->getMessage());
1732 catch(Exception
$e) {
1733 $transaction->rollback();
1734 return civicrm_api3_create_error($e->getMessage());
1739 * Replace base parameters.
1741 * @param array $params
1745 function _civicrm_api3_generic_replace_base_params($params) {
1746 $baseParams = $params;
1747 unset($baseParams['values']);
1748 unset($baseParams['sequential']);
1749 unset($baseParams['options']);
1754 * Returns fields allowable by api.
1757 * String Entity to query.
1758 * @param bool $unique
1759 * Index by unique fields?.
1760 * @param array $params
1764 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1765 $unsetIfEmpty = array(
1772 $dao = _civicrm_api3_get_DAO($entity);
1777 $fields = $d->fields();
1778 // replace uniqueNames by the normal names as the key
1779 if (empty($unique)) {
1780 foreach ($fields as $name => &$field) {
1781 //getting rid of unused attributes
1782 foreach ($unsetIfEmpty as $attr) {
1783 if (empty($field[$attr])) {
1784 unset($field[$attr]);
1787 if ($name == $field['name']) {
1790 if (array_key_exists($field['name'], $fields)) {
1791 $field['error'] = 'name conflict';
1792 // it should never happen, but better safe than sorry
1795 $fields[$field['name']] = $field;
1796 $fields[$field['name']]['uniqueName'] = $name;
1797 unset($fields[$name]);
1800 // Translate FKClassName to the corresponding api
1801 foreach ($fields as $name => &$field) {
1802 if (!empty($field['FKClassName'])) {
1803 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1805 $field['FKApiName'] = $FKApi;
1809 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1814 * Return an array of fields for a given entity.
1816 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1819 * @param array $params
1823 function _civicrm_api_get_custom_fields($entity, &$params) {
1824 $entity = _civicrm_api_get_camel_name($entity);
1825 if ($entity == 'Contact') {
1826 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1827 $entity = CRM_Utils_Array
::value('contact_type', $params);
1829 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1832 // we could / should probably test for other subtypes here - e.g. activity_type_id
1833 CRM_Utils_Array
::value('contact_sub_type', $params),
1842 foreach ($customfields as $key => $value) {
1843 // Regular fields have a 'name' property
1844 $value['name'] = 'custom_' . $key;
1845 $value['title'] = $value['label'];
1846 $value['type'] = _getStandardTypeFromCustomDataType($value);
1847 $ret['custom_' . $key] = $value;
1853 * Translate the custom field data_type attribute into a std 'type'.
1855 * @param array $value
1859 function _getStandardTypeFromCustomDataType($value) {
1860 $dataType = $value['data_type'];
1861 //CRM-15792 - If date custom field contains timeformat change type to DateTime
1862 if ($value['data_type'] == 'Date' && isset($value['time_format']) && $value['time_format'] > 0) {
1863 $dataType = 'DateTime';
1866 'String' => CRM_Utils_Type
::T_STRING
,
1867 'Int' => CRM_Utils_Type
::T_INT
,
1868 'Money' => CRM_Utils_Type
::T_MONEY
,
1869 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1870 'Float' => CRM_Utils_Type
::T_FLOAT
,
1871 'Date' => CRM_Utils_Type
::T_DATE
,
1872 'DateTime' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
1873 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1874 'StateProvince' => CRM_Utils_Type
::T_INT
,
1875 'File' => CRM_Utils_Type
::T_STRING
,
1876 'Link' => CRM_Utils_Type
::T_STRING
,
1877 'ContactReference' => CRM_Utils_Type
::T_INT
,
1878 'Country' => CRM_Utils_Type
::T_INT
,
1880 return $mapping[$dataType];
1885 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
1887 * If multiple aliases the last takes precedence
1889 * Function also swaps unique fields for non-unique fields & vice versa.
1891 * @param $apiRequest
1894 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1895 foreach ($fields as $field => $values) {
1896 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1897 if (!empty($values['api.aliases'])) {
1898 // if aliased field is not set we try to use field alias
1899 if (!isset($apiRequest['params'][$field])) {
1900 foreach ($values['api.aliases'] as $alias) {
1901 if (isset($apiRequest['params'][$alias])) {
1902 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1904 //unset original field nb - need to be careful with this as it may bring inconsistencies
1905 // out of the woodwork but will be implementing only as _spec function extended
1906 unset($apiRequest['params'][$alias]);
1910 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
1911 && isset($apiRequest['params'][$values['name']])
1913 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1914 // note that it would make sense to unset the original field here but tests need to be in place first
1916 if (!isset($apiRequest['params'][$field])
1918 && $field != $uniqueName
1919 && array_key_exists($uniqueName, $apiRequest['params'])
1921 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1922 // note that it would make sense to unset the original field here but tests need to be in place first
1929 * Validate integer fields being passed into API.
1931 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
1933 * @param array $params
1934 * Params from civicrm_api.
1935 * @param string $fieldName
1936 * Uniquename of field being checked.
1937 * @param array $fieldInfo
1938 * Array of fields from getfields function.
1939 * @param string $entity
1941 * @throws API_Exception
1943 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1944 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1945 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1949 if (!empty($fieldValue)) {
1950 // if value = 'user_contact_id' (or similar), replace value with contact id
1951 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
1952 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
1953 if ('unknown-user' === $realContactId) {
1954 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName, "type" => "integer"));
1956 elseif (is_numeric($realContactId)) {
1957 $fieldValue = $realContactId;
1960 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1961 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
1964 // After swapping options, ensure we have an integer(s)
1965 foreach ((array) ($fieldValue) as $value) {
1966 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1967 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1971 // Check our field length
1972 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
1974 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1975 2100, array('field' => $fieldName, "max_length" => $fieldInfo['maxlength'])
1981 $params[$fieldName][$op] = $fieldValue;
1984 $params[$fieldName] = $fieldValue;
1989 * Determine a contact ID using a string expression.
1991 * @param string $contactIdExpr
1992 * E.g. "user_contact_id" or "@user:username".
1994 * @return int|NULL|'unknown-user'
1996 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1997 // If value = 'user_contact_id' replace value with logged in user id.
1998 if ($contactIdExpr == "user_contact_id") {
1999 return CRM_Core_Session
::getLoggedInContactID();
2001 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
2002 $config = CRM_Core_Config
::singleton();
2004 $ufID = $config->userSystem
->getUfId($matches[1]);
2006 return 'unknown-user';
2009 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
2011 return 'unknown-user';
2020 * Validate html (check for scripting attack).
2022 * @param array $params
2023 * @param string $fieldName
2024 * @param array $fieldInfo
2026 * @throws API_Exception
2028 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
2029 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2030 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
2034 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2035 throw new API_Exception('Input contains illegal SCRIPT tag.', array("field" => $fieldName, "error_code" => "xss"));
2041 * Validate string fields being passed into API.
2043 * @param array $params
2044 * Params from civicrm_api.
2045 * @param string $fieldName
2046 * Uniquename of field being checked.
2047 * @param array $fieldInfo
2048 * Array of fields from getfields function.
2049 * @param string $entity
2051 * @throws API_Exception
2054 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2055 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2056 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
2060 if (!is_array($fieldValue)) {
2061 $fieldValue = (string) $fieldValue;
2064 //@todo what do we do about passed in arrays. For many of these fields
2065 // the missing piece of functionality is separating them to a separated string
2066 // & many save incorrectly. But can we change them wholesale?
2069 foreach ((array) $fieldValue as $value) {
2070 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2071 throw new Exception('Input contains illegal SCRIPT tag.');
2073 if ($fieldName == 'currency') {
2074 //When using IN operator $fieldValue is a array of currency codes
2075 if (!CRM_Utils_Rule
::currencyCode($value)) {
2076 throw new Exception("Currency not a valid code: $currency");
2081 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2082 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
2084 // Check our field length
2085 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2086 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2087 2100, array('field' => $fieldName)
2092 $params[$fieldName][$op] = $fieldValue;
2095 $params[$fieldName] = $fieldValue;
2100 * Validate & swap out any pseudoconstants / options.
2102 * @param mixed $fieldValue
2103 * @param string $entity : api entity name
2104 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2105 * @param array $fieldInfo : getfields meta-data
2107 * @throws \API_Exception
2109 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo) {
2110 $options = CRM_Utils_Array
::value('options', $fieldInfo);
2113 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2114 // We need to get the options from the entity the field relates to.
2115 $entity = $fieldInfo['entity'];
2117 $options = civicrm_api($entity, 'getoptions', array(
2119 'field' => $fieldInfo['name'],
2120 'context' => 'validate',
2122 $options = CRM_Utils_Array
::value('values', $options, array());
2125 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2127 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2128 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
2131 // If passed multiple options, validate each.
2132 if (is_array($fieldValue)) {
2133 foreach ($fieldValue as &$value) {
2134 if (!is_array($value)) {
2135 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
2138 // TODO: unwrap the call to implodePadded from the conditional and do it always
2139 // need to verify that this is safe and doesn't break anything though.
2140 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2142 CRM_Utils_Array
::implodePadded($fieldValue);
2146 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName);
2151 * Validate & swap a single option value for a field.
2153 * @param string $value field value
2154 * @param array $options array of options for this field
2155 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2157 * @throws API_Exception
2159 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
2160 // If option is a key, no need to translate
2161 // or if no options are avaiable for pseudoconstant 'table' property
2162 if (array_key_exists($value, $options) ||
!$options) {
2166 // Translate value into key
2167 $newValue = array_search($value, $options);
2168 if ($newValue !== FALSE) {
2172 // Case-insensitive matching
2173 $newValue = strtolower($value);
2174 $options = array_map("strtolower", $options);
2175 $newValue = array_search($newValue, $options);
2176 if ($newValue === FALSE) {
2177 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
2183 * Returns the canonical name of a field.
2186 * api entity name (string should already be standardized - no camelCase).
2188 * any variation of a field's name (name, unique_name, api.alias).
2190 * @return bool|string
2191 * fieldName or FALSE if the field does not exist
2193 function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') {
2194 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2197 if ($fieldName == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
2200 $result = civicrm_api($entity, 'getfields', array(
2202 'action' => $action,
2204 $meta = $result['values'];
2205 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2206 $fieldName = $fieldName . '_id';
2208 if (isset($meta[$fieldName])) {
2209 return $meta[$fieldName]['name'];
2211 foreach ($meta as $info) {
2212 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2213 return $info['name'];
2215 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
2216 return $info['name'];
2219 // Create didn't work, try with get
2220 if ($action == 'create') {
2221 return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get');
2227 * Check if the function is deprecated.
2229 * @param string $entity
2230 * @param array $result
2232 * @return string|array|null
2234 function _civicrm_api3_deprecation_check($entity, $result = array()) {
2236 $apiFile = "api/v3/$entity.php";
2237 if (CRM_Utils_File
::isIncludable($apiFile)) {
2238 require_once $apiFile;
2240 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
2241 $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation";
2242 if (function_exists($fnName)) {
2243 return $fnName($result);
2249 * Get the actual field value.
2251 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2252 * So this function returns the actual field value
2254 * @param array $params
2255 * @param string $fieldName
2259 function _civicrm_api3_field_value_check(&$params, $fieldName) {
2260 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2263 if (!empty($fieldValue) && is_array($fieldValue) && array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators())) {
2264 $op = key($fieldValue);
2265 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2267 return array($fieldValue, $op);
2271 * Like _civicrm_api3_basic_get, but data is backed by a simple array
2272 * instead of a DAO/BAO. This is useful for small/mid-size data loaded
2273 * from JSON or XML documents.
2275 * @param array $params
2277 * @param array $records
2278 * List of all records.
2279 * @param string $idCol
2280 * The property which defines the ID of a record
2281 * @param array $fields
2282 * List of filterable fields.
2285 function _civicrm_api3_basic_array_get($entity, $params, $records, $idCol, $fields) {
2286 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
2287 // TODO // $sort = CRM_Utils_Array::value('sort', $options, NULL);
2288 $offset = CRM_Utils_Array
::value('offset', $options);
2289 $limit = CRM_Utils_Array
::value('limit', $options);
2294 foreach ($records as $record) {
2295 if ($idCol != 'id') {
2296 $record['id'] = $record[$idCol];
2299 foreach ($params as $k => $v) {
2300 if (in_array($k, $fields) && $record[$k] !== $v) {
2306 if ($currentOffset >= $offset) {
2307 $matches[$record[$idCol]] = $record;
2309 if ($limit && count($matches) >= $limit) {
2316 $return = CRM_Utils_Array
::value('return', $options, array());
2317 if (!empty($return)) {
2319 $matches = CRM_Utils_Array
::filterColumns($matches, array_keys($return));
2322 return civicrm_api3_create_success($matches, $params);