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 // Always report "update" action as deprecated.
267 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'update')) {
268 $deprecated = ((array) $deprecated) +
array('update' => 'The "update" action is deprecated. Use "create" with an id instead.');
271 // Metadata-level deprecations or wholesale entity deprecations.
272 if ($entity == 'Entity' ||
$action == 'getactions' ||
is_string($deprecated)) {
273 $result['deprecated'] = $deprecated;
275 // Action-specific deprecations
276 elseif (!empty($deprecated[$action])) {
277 $result['deprecated'] = $deprecated[$action];
280 return array_merge($result, $extraReturnValues);
284 * Load the DAO of the entity.
290 function _civicrm_api3_load_DAO($entity) {
291 $dao = _civicrm_api3_get_DAO($entity);
300 * Return the DAO of the function or Entity.
302 * @param string $name
303 * Either a function of the api (civicrm_{entity}_create or the entity name.
304 * return the DAO name to manipulate this function
305 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
307 * @return mixed|string
309 function _civicrm_api3_get_DAO($name) {
310 if (strpos($name, 'civicrm_api3') !== FALSE) {
311 $last = strrpos($name, '_');
312 // len ('civicrm_api3_') == 13
313 $name = substr($name, 13, $last - 13);
316 $name = _civicrm_api_get_camel_name($name);
318 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
322 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
324 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
325 if ($name == 'MailingEventQueue') {
326 return 'CRM_Mailing_Event_DAO_Queue';
328 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
329 // but am not confident mailing_recipients is tested so have not tackled.
330 if ($name == 'MailingRecipients') {
331 return 'CRM_Mailing_DAO_Recipients';
333 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
334 if ($name == 'MailingComponent') {
335 return 'CRM_Mailing_DAO_Component';
337 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
338 if ($name == 'AclRole') {
339 return 'CRM_ACL_DAO_EntityRole';
341 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
342 // But this would impact SMS extensions so need to coordinate
343 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
344 if ($name == 'SmsProvider') {
345 return 'CRM_SMS_DAO_Provider';
347 // FIXME: DAO names should follow CamelCase convention
348 if ($name == 'Im' ||
$name == 'Acl') {
349 $name = strtoupper($name);
351 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
352 if ($dao ||
!$name) {
356 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
357 if (file_exists("api/v3/$name.php")) {
358 include_once "api/v3/$name.php";
361 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
362 if (function_exists($daoFn)) {
370 * Return the DAO of the function or Entity.
372 * @param string $name
373 * Is either a function of the api (civicrm_{entity}_create or the entity name.
374 * return the DAO name to manipulate this function
375 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
379 function _civicrm_api3_get_BAO($name) {
380 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
381 if ($name == 'PrintLabel') {
382 return 'CRM_Badge_BAO_Layout';
384 $dao = _civicrm_api3_get_DAO($name);
388 $bao = str_replace("DAO", "BAO", $dao);
389 $file = strtr($bao, '_', '/') . '.php';
390 // Check if this entity actually has a BAO. Fall back on the DAO if not.
391 return stream_resolve_include_path($file) ?
$bao : $dao;
395 * Recursive function to explode value-separated strings into arrays.
399 function _civicrm_api3_separate_values(&$values) {
400 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
401 foreach ($values as $key => & $value) {
402 if (is_array($value)) {
403 _civicrm_api3_separate_values($value);
405 elseif (is_string($value)) {
406 // This is to honor the way case API was originally written.
407 if ($key == 'case_type_id') {
408 $value = trim(str_replace($sp, ',', $value), ',');
410 elseif (strpos($value, $sp) !== FALSE) {
411 $value = explode($sp, trim($value, $sp));
418 * This is a legacy wrapper for api_store_values.
420 * It checks suitable fields using getfields rather than DAO->fields.
422 * Getfields has handling for how to deal with unique names which dao->fields doesn't
424 * Note this is used by BAO type create functions - eg. contribution
426 * @param string $entity
427 * @param array $params
428 * @param array $values
430 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
431 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
432 $fields = $fields['values'];
433 _civicrm_api3_store_values($fields, $params, $values);
438 * @param array $fields
439 * @param array $params
440 * @param array $values
444 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
447 $keys = array_intersect_key($params, $fields);
448 foreach ($keys as $name => $value) {
449 if ($name !== 'id') {
450 $values[$name] = $value;
458 * Get function for query object api.
460 * The API supports 2 types of get request. The more complex uses the BAO query object.
461 * This is a generic function for those functions that call it
463 * At the moment only called by contact we should extend to contribution &
464 * others that use the query object. Note that this function passes permission information in.
467 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
471 * @param array $params
472 * As passed into api get or getcount function.
473 * @param array $additional_options
474 * Array of options (so we can modify the filter).
475 * @param bool $getCount
476 * Are we just after the count.
480 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL) {
481 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
482 // Convert id to e.g. contact_id
483 if (empty($params[$lowercase_entity . '_id']) && isset($params['id'])) {
484 $params[$lowercase_entity . '_id'] = $params['id'];
486 unset($params['id']);
488 $options = _civicrm_api3_get_options_from_params($params, TRUE);
490 $inputParams = array_merge(
491 CRM_Utils_Array
::value('input_params', $options, array()),
492 CRM_Utils_Array
::value('input_params', $additional_options, array())
494 $returnProperties = array_merge(
495 CRM_Utils_Array
::value('return', $options, array()),
496 CRM_Utils_Array
::value('return', $additional_options, array())
498 if (empty($returnProperties)) {
499 $returnProperties = NULL;
501 if (!empty($params['check_permissions'])) {
502 // we will filter query object against getfields
503 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
504 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
505 $fields['values'][$lowercase_entity . '_id'] = array();
506 $varsToFilter = array('returnProperties', 'inputParams');
507 foreach ($varsToFilter as $varToFilter) {
508 if (!is_array($
$varToFilter)) {
511 //I was going to throw an exception rather than silently filter out - but
512 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
513 //so we are silently ignoring parts of their request
514 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
515 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
518 $options = array_merge($options, $additional_options);
519 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
520 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
521 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
522 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
526 $returnProperties = NULL;
529 if (substr($sort, 0, 2) == 'id') {
530 $sort = $lowercase_entity . "_" . $sort;
533 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
534 foreach ($newParams as &$newParam) {
535 if ($newParam[1] == '=' && is_array($newParam[2])) {
536 // we may be looking at an attempt to use the 'IN' style syntax
537 // @todo at time of writing only 'IN' & 'NOT IN' are supported for the array style syntax
538 $sqlFilter = CRM_Core_DAO
::createSqlFilter($newParam[0], $params[$newParam[0]], 'String', NULL, TRUE);
540 $newParam[1] = key($newParam[2]);
541 $newParam[2] = $sqlFilter;
546 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
548 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
560 // only return the count of contacts
568 * Get dao query object based on input params.
570 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
573 * @param array $params
574 * @param string $mode
575 * @param string $entity
578 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
580 function _civicrm_api3_get_query_object($params, $mode, $entity) {
581 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
582 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
583 $offset = CRM_Utils_Array
::value('offset', $options);
584 $rowCount = CRM_Utils_Array
::value('limit', $options);
585 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
586 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
587 if (empty($returnProperties)) {
588 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
591 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
592 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
594 empty($params['check_permissions'])
596 list($select, $from, $where, $having) = $query->query();
598 $sql = "$select $from $where $having";
601 $sql .= " ORDER BY $sort ";
603 if (!empty($rowCount)) {
604 $sql .= " LIMIT $offset, $rowCount ";
606 $dao = CRM_Core_DAO
::executeQuery($sql);
607 return array($dao, $query);
611 * Function transfers the filters being passed into the DAO onto the params object.
613 * @param CRM_Core_DAO $dao
614 * @param array $params
615 * @param bool $unique
617 * @throws API_Exception
620 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE) {
621 $entity = _civicrm_api_get_entity_name_from_dao($dao);
622 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
623 if (!empty($params[$lowercase_entity . "_id"]) && empty($params['id'])) {
624 //if entity_id is set then treat it as ID (will be overridden by id if set)
625 $params['id'] = $params[$lowercase_entity . "_id"];
627 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
628 $fields = array_intersect(array_keys($allfields), array_keys($params));
630 $options = _civicrm_api3_get_options_from_params($params);
631 //apply options like sort
632 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
634 //accept filters like filter.activity_date_time_high
635 // std is now 'filters' => ..
636 if (strstr(implode(',', array_keys($params)), 'filter')) {
637 if (isset($params['filters']) && is_array($params['filters'])) {
638 foreach ($params['filters'] as $paramkey => $paramvalue) {
639 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
643 foreach ($params as $paramkey => $paramvalue) {
644 if (strstr($paramkey, 'filter')) {
645 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
654 foreach ($fields as $field) {
655 if (is_array($params[$field])) {
656 //get the actual fieldname from db
657 $fieldName = $allfields[$field]['name'];
658 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
659 if (!empty($where)) {
660 $dao->whereAdd($where);
665 $daoFieldName = $allfields[$field]['name'];
666 if (empty($daoFieldName)) {
667 throw new API_Exception("Failed to determine field name for \"$field\"");
669 $dao->{$daoFieldName} = $params[$field];
672 $dao->$field = $params[$field];
676 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
678 // Ensure 'id' is included.
679 $options['return']['id'] = TRUE;
680 $allfields = _civicrm_api3_get_unique_name_array($dao);
681 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
682 foreach ($returnMatched as $returnValue) {
683 $dao->selectAdd($returnValue);
686 // Not already matched on the field names.
687 $unmatchedFields = array_diff(
688 array_keys($options['return']),
692 $returnUniqueMatched = array_intersect(
694 // But a match for the field keys.
695 array_flip($allfields)
697 foreach ($returnUniqueMatched as $uniqueVal) {
698 $dao->selectAdd($allfields[$uniqueVal]);
701 $dao->setApiFilter($params);
705 * Apply filters (e.g. high, low) to DAO object (prior to find).
707 * @param string $filterField
708 * Field name of filter.
709 * @param string $filterValue
710 * Field value of filter.
714 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
715 if (strstr($filterField, 'high')) {
716 $fieldName = substr($filterField, 0, -5);
717 $dao->whereAdd("($fieldName <= $filterValue )");
719 if (strstr($filterField, 'low')) {
720 $fieldName = substr($filterField, 0, -4);
721 $dao->whereAdd("($fieldName >= $filterValue )");
723 if ($filterField == 'is_current' && $filterValue == 1) {
724 $todayStart = date('Ymd000000', strtotime('now'));
725 $todayEnd = date('Ymd235959', strtotime('now'));
726 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
727 if (property_exists($dao, 'is_active')) {
728 $dao->whereAdd('is_active = 1');
734 * Get sort, limit etc options from the params - supporting old & new formats.
736 * Get returnProperties for legacy
738 * @param array $params
739 * Params array as passed into civicrm_api.
740 * @param bool $queryObject
741 * Is this supporting a queryObject api (e.g contact) - if so we support more options.
742 * for legacy report & return a unique fields array
744 * @param string $entity
745 * @param string $action
747 * @throws API_Exception
749 * options extracted from params
751 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
752 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
754 $sort = CRM_Utils_Array
::value('sort', $params, 0);
755 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
756 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
758 $offset = CRM_Utils_Array
::value('offset', $params, 0);
759 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
760 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
761 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
763 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
764 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
765 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
767 if (is_array(CRM_Utils_Array
::value('options', $params))) {
768 // is count is set by generic getcount not user
769 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
770 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
771 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
772 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
775 $returnProperties = array();
776 // handle the format return =sort_name,display_name...
777 if (array_key_exists('return', $params)) {
778 if (is_array($params['return'])) {
779 $returnProperties = array_fill_keys($params['return'], 1);
782 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
783 $returnProperties = array_fill_keys($returnProperties, 1);
786 if ($entity && $action == 'get') {
787 if (!empty($returnProperties['id'])) {
788 $returnProperties[$lowercase_entity . '_id'] = 1;
789 unset($returnProperties['id']);
791 switch (trim(strtolower($sort))) {
795 $sort = str_replace('id', $lowercase_entity . '_id', $sort);
800 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
801 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
802 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
803 'is_count' => $is_count,
804 'return' => !empty($returnProperties) ?
$returnProperties : array(),
807 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
808 throw new API_Exception('invalid string in sort options');
814 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
815 // if the queryobject is being used this should be used
816 $inputParams = array();
817 $legacyreturnProperties = array();
819 'sort', 'offset', 'rowCount', 'options', 'return',
820 'version', 'prettyprint', 'check_permissions', 'sequential',
822 foreach ($params as $n => $v) {
823 if (substr($n, 0, 7) == 'return.') {
824 $legacyreturnProperties[substr($n, 7)] = $v;
826 elseif ($n == 'id') {
827 $inputParams[$lowercase_entity . '_id'] = $v;
829 elseif (in_array($n, $otherVars)) {
832 $inputParams[$n] = $v;
833 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
834 throw new API_Exception('invalid string');
838 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
839 $options['input_params'] = $inputParams;
844 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
846 * @param array $params
847 * Params array as passed into civicrm_api.
852 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
854 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
855 if (!$options['is_count']) {
856 if (!empty($options['limit'])) {
857 $dao->limit((int) $options['offset'], (int) $options['limit']);
859 if (!empty($options['sort'])) {
860 $dao->orderBy($options['sort']);
866 * Build fields array.
868 * This is the array of fields as it relates to the given DAO
869 * returns unique fields as keys by default but if set but can return by DB fields
871 * @param CRM_Core_DAO $bao
872 * @param bool $unique
876 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
877 $fields = $bao->fields();
879 if (empty($fields['id'])) {
880 $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
881 $fields['id'] = $fields[$lowercase_entity . '_id'];
882 unset($fields[$lowercase_entity . '_id']);
887 foreach ($fields as $field) {
888 $dbFields[$field['name']] = $field;
894 * Build fields array.
896 * This is the array of fields as it relates to the given DAO
897 * returns unique fields as keys by default but if set but can return by DB fields
899 * @param CRM_Core_DAO $bao
903 function _civicrm_api3_get_unique_name_array(&$bao) {
904 $fields = $bao->fields();
905 foreach ($fields as $field => $values) {
906 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
908 return $uniqueFields;
912 * Converts an DAO object to an array.
914 * @param CRM_Core_DAO $dao
916 * @param array $params
917 * @param bool $uniqueFields
918 * @param string $entity
919 * @param bool $autoFind
923 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
925 if (isset($params['options']) && !empty($params['options']['is_count'])) {
926 return $dao->count();
931 if ($autoFind && !$dao->find()) {
935 if (isset($dao->count
)) {
939 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
941 while ($dao->fetch()) {
943 foreach ($fields as $key) {
944 if (array_key_exists($key, $dao)) {
945 // not sure on that one
946 if ($dao->$key !== NULL) {
947 $tmp[$key] = $dao->$key;
951 $result[$dao->id
] = $tmp;
953 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
954 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
962 * Determine if custom fields need to be retrieved.
964 * We currently retrieve all custom fields or none at this level so if we know the entity
965 * && 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
966 * @todo filter so only required fields are queried
968 * @param string $entity
969 * Entity name in CamelCase.
970 * @param array $params
974 function _civicrm_api3_custom_fields_are_required($entity, $params) {
975 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
978 $options = _civicrm_api3_get_options_from_params($params);
979 // We check for possibility of 'custom' => 1 as well as specific custom fields.
980 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
981 if (stristr($returnString, 'custom')) {
986 * Converts an object to an array.
989 * (reference) object to convert.
990 * @param array $values
992 * @param array|bool $uniqueFields
994 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
996 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
997 foreach ($fields as $key => $value) {
998 if (array_key_exists($key, $dao)) {
999 $values[$key] = $dao->$key;
1005 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1012 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1013 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1017 * Format custom parameters.
1019 * @param array $params
1020 * @param array $values
1021 * @param string $extends
1022 * Entity that this custom field extends (e.g. contribution, event, contact).
1023 * @param string $entityId
1024 * ID of entity per $extends.
1026 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1027 $values['custom'] = array();
1028 $checkCheckBoxField = FALSE;
1030 if (in_array($extends, array('Household', 'Individual', 'Organization'))) {
1031 $entity = 'Contact';
1034 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
1035 if (!$fields['is_error']) {
1036 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1037 $fields = $fields['values'];
1038 $checkCheckBoxField = TRUE;
1041 foreach ($params as $key => $value) {
1042 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
1043 if ($customFieldID && (!is_null($value))) {
1044 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1045 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1048 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1049 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1056 * Format parameters for create action.
1058 * @param array $params
1061 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1062 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1064 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery
::$extendsMap, array_fill_keys($nonGenericEntities, 1));
1065 if (!array_key_exists($entity, $customFieldEntities)) {
1069 _civicrm_api3_custom_format_params($params, $values, $entity);
1070 $params = array_merge($params, $values);
1074 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1076 * We should look at pushing to BAO function
1077 * 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
1078 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1080 * 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
1081 * don't touch - lots of very cautious code in here
1083 * The resulting array should look like
1089 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1091 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1092 * be fixed in future
1094 * @param mixed $checkboxFieldValue
1095 * @param string $customFieldLabel
1096 * @param string $entity
1098 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1100 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1101 // We can assume it's pre-formatted.
1104 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1105 if (!empty($options['is_error'])) {
1106 // The check is precautionary - can probably be removed later.
1110 $options = $options['values'];
1112 if (is_array($checkboxFieldValue)) {
1113 foreach ($checkboxFieldValue as $key => $value) {
1114 if (!array_key_exists($key, $options)) {
1115 $validValue = FALSE;
1119 // we have been passed an array that is already in the 'odd' custom field format
1124 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1125 // if the array only has one item we'll treat it like any other string
1126 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1127 $possibleValue = reset($checkboxFieldValue);
1129 if (is_string($checkboxFieldValue)) {
1130 $possibleValue = $checkboxFieldValue;
1132 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1133 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1136 elseif (is_array($checkboxFieldValue)) {
1137 // so this time around we are considering the values in the array
1138 $possibleValues = $checkboxFieldValue;
1139 $formatValue = TRUE;
1141 elseif (stristr($checkboxFieldValue, ',')) {
1142 $formatValue = TRUE;
1143 //lets see if we should separate it - we do this near the end so we
1144 // ensure we have already checked that the comma is not part of a legitimate match
1145 // and of course, we don't make any changes if we don't now have matches
1146 $possibleValues = explode(',', $checkboxFieldValue);
1149 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1153 foreach ($possibleValues as $index => $possibleValue) {
1154 if (array_key_exists($possibleValue, $options)) {
1155 // 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)
1157 elseif (array_key_exists(trim($possibleValue), $options)) {
1158 $possibleValues[$index] = trim($possibleValue);
1161 $formatValue = FALSE;
1165 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1170 * This function ensures that we have the right input parameters.
1174 * This function is only called when $dao is passed into verify_mandatory.
1175 * The practice of passing $dao into verify_mandatory turned out to be
1176 * unsatisfactory as the required fields @ the dao level is so different to the abstract
1177 * api level. Hence the intention is to remove this function
1178 * & the associated param from verify_mandatory
1180 * @param array $params
1181 * Associative array of property name/value.
1182 * pairs to insert in new history.
1183 * @param string $daoName
1184 * @param bool $return
1186 * @daoName string DAO to check params against
1189 * Should the missing fields be returned as an array (core error created as default)
1190 * true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1192 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1193 //@deprecated - see notes
1194 if (isset($params['extends'])) {
1195 if (($params['extends'] == 'Activity' ||
1196 $params['extends'] == 'Phonecall' ||
1197 $params['extends'] == 'Meeting' ||
1198 $params['extends'] == 'Group' ||
1199 $params['extends'] == 'Contribution'
1201 ($params['style'] == 'Tab')
1203 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1207 $dao = new $daoName();
1208 $fields = $dao->fields();
1211 foreach ($fields as $k => $v) {
1212 if ($v['name'] == 'id') {
1216 if (!empty($v['required'])) {
1217 // 0 is a valid input for numbers, CRM-8122
1218 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1224 if (!empty($missing)) {
1225 if (!empty($return)) {
1229 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1237 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1239 * @param string $bao_name
1241 * @param array $params
1243 * @param bool $returnAsSuccess
1244 * Return in api success format.
1245 * @param string $entity
1249 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1250 $bao = new $bao_name();
1251 _civicrm_api3_dao_set_filter($bao, $params, TRUE);
1252 if ($returnAsSuccess) {
1253 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1256 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity, 'get');
1261 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1263 * @param string $bao_name
1264 * Name of BAO Class.
1265 * @param array $params
1266 * Parameters passed into the api call.
1267 * @param string $entity
1268 * Entity - pass in if entity is non-standard & required $ids array.
1270 * @throws API_Exception
1273 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1274 _civicrm_api3_format_params_for_create($params, $entity);
1275 $args = array(&$params);
1277 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1281 if (method_exists($bao_name, 'create')) {
1283 $fct_name = $bao_name . '::' . $fct;
1284 $bao = call_user_func_array(array($bao_name, $fct), $args);
1286 elseif (method_exists($bao_name, 'add')) {
1288 $fct_name = $bao_name . '::' . $fct;
1289 $bao = call_user_func_array(array($bao_name, $fct), $args);
1292 $fct_name = '_civicrm_api3_basic_create_fallback';
1293 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1296 if (is_null($bao)) {
1297 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1299 elseif (is_a($bao, 'CRM_Core_Error')) {
1300 //some weird circular thing means the error takes itself as an argument
1301 $msg = $bao->getMessages($bao);
1302 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1303 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1304 // so we need to reset the error object here to avoid getting concatenated errors
1305 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1306 CRM_Core_Error
::singleton()->reset();
1307 throw new API_Exception($msg);
1311 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1312 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1317 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1319 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1320 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1322 * @param string $bao_name
1323 * @param array $params
1325 * @throws API_Exception
1327 * @return CRM_Core_DAO|NULL
1328 * An instance of the BAO
1330 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1331 $dao_name = get_parent_class($bao_name);
1332 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1333 $dao_name = $bao_name;
1335 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1336 if (empty($entityName)) {
1337 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1338 'class_name' => $bao_name,
1341 $hook = empty($params['id']) ?
'create' : 'edit';
1343 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1344 $instance = new $dao_name();
1345 $instance->copyValues($params);
1347 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1353 * Function to do a 'standard' api del.
1355 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1357 * @param string $bao_name
1358 * @param array $params
1362 * @throws API_Exception
1364 function _civicrm_api3_basic_delete($bao_name, &$params) {
1366 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1367 $args = array(&$params['id']);
1368 if (method_exists($bao_name, 'del')) {
1369 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1370 if ($bao !== FALSE) {
1371 return civicrm_api3_create_success(TRUE);
1373 throw new API_Exception('Could not delete entity id ' . $params['id']);
1375 elseif (method_exists($bao_name, 'delete')) {
1376 $dao = new $bao_name();
1377 $dao->id
= $params['id'];
1379 while ($dao->fetch()) {
1381 return civicrm_api3_create_success();
1385 throw new API_Exception('Could not delete entity id ' . $params['id']);
1389 throw new API_Exception('no delete method found');
1393 * Get custom data for the given entity & Add it to the returnArray.
1395 * This looks like 'custom_123' = 'custom string' AND
1396 * 'custom_123_1' = 'custom string'
1397 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1399 * @param array $returnArray
1400 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1401 * @param string $entity
1402 * E.g membership, event.
1403 * @param int $entity_id
1404 * @param int $groupID
1405 * Per CRM_Core_BAO_CustomGroup::getTree.
1406 * @param int $subType
1407 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1408 * @param string $subName
1409 * Subtype of entity.
1411 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1412 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1413 CRM_Core_DAO
::$_nullObject,
1422 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1423 $customValues = array();
1424 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1425 $fieldInfo = array();
1426 foreach ($groupTree as $set) {
1427 $fieldInfo +
= $set['fields'];
1429 if (!empty($customValues)) {
1430 foreach ($customValues as $key => $val) {
1431 // per standard - return custom_fieldID
1432 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1433 $returnArray['custom_' . $id] = $val;
1435 //not standard - but some api did this so guess we should keep - cheap as chips
1436 $returnArray[$key] = $val;
1438 // Shim to restore legacy behavior of ContactReference custom fields
1439 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1440 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1441 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1448 * Validate fields being passed into API.
1450 * This function relies on the getFields function working accurately
1451 * for the given API. If error mode is set to TRUE then it will also check
1454 * As of writing only date was implemented.
1456 * @param string $entity
1457 * @param string $action
1458 * @param array $params
1460 * @param array $fields
1461 * Response from getfields all variables are the same as per civicrm_api.
1462 * @param bool $errorMode
1463 * ErrorMode do intensive post fail checks?.
1467 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = FALSE) {
1468 //CRM-15792 handle datetime for custom fields below code handles chain api call
1469 $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params)));
1470 if (!empty($chainApikeys) && is_array($chainApikeys)) {
1471 foreach ($chainApikeys as $key => $value) {
1472 if (is_array($params[$key])) {
1473 $chainApiParams = array_intersect_key($fields, $params[$key]);
1474 $customFields = array_fill_keys(array_keys($params[$key]), $key);
1478 $fields = array_intersect_key($fields, $params);
1479 if (!empty($chainApiParams)) {
1480 $fields = array_merge($fields, $chainApiParams);
1482 foreach ($fields as $fieldName => $fieldInfo) {
1483 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1484 case CRM_Utils_Type
::T_INT
:
1485 //field is of type integer
1486 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1489 case CRM_Utils_Type
::T_DATE
:
1490 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1491 case CRM_Utils_Type
::T_TIMESTAMP
:
1492 //field is of type date or datetime
1493 if (!empty($customFields) && array_key_exists($fieldName, $customFields)) {
1494 $dateParams = &$params[$customFields[$fieldName]];
1497 $dateParams = &$params;
1499 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
1504 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1507 case CRM_Utils_Type
::T_STRING
:
1508 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1511 case CRM_Utils_Type
::T_MONEY
:
1512 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1513 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1516 foreach ((array) $fieldValue as $fieldvalue) {
1517 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1518 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1524 // intensive checks - usually only called after DB level fail
1525 if (!empty($errorMode) && strtolower($action) == 'create') {
1526 if (!empty($fieldInfo['FKClassName'])) {
1527 if (!empty($fieldValue)) {
1528 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1530 elseif (!empty($fieldInfo['required'])) {
1531 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1534 if (!empty($fieldInfo['api.unique'])) {
1535 $params['entity'] = $entity;
1536 _civicrm_api3_validate_unique_key($params, $fieldName);
1543 * Validate date fields being passed into API.
1545 * It currently converts both unique fields and DB field names to a mysql date.
1546 * @todo - probably the unique field handling & the if exists handling is now done before this
1547 * function is reached in the wrapper - can reduce this code down to assume we
1548 * are only checking the passed in field
1550 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1551 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1553 * @param array $params
1554 * Params from civicrm_api.
1555 * @param string $fieldName
1556 * Uniquename of field being checked.
1557 * @param array $fieldInfo
1558 * Array of fields from getfields function.
1562 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1563 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1564 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1567 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1568 if (!empty($params[$fieldInfo['name']])) {
1569 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1571 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1572 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1576 $params[$fieldName][$op] = $fieldValue;
1579 $params[$fieldName] = $fieldValue;
1584 * Convert date into BAO friendly date.
1586 * We accept 'whatever strtotime accepts'
1588 * @param string $dateValue
1589 * @param string $fieldName
1595 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1596 if (is_array($dateValue)) {
1597 foreach ($dateValue as $key => $value) {
1598 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1602 if (strtotime($dateValue) === FALSE) {
1603 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1605 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1606 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1610 * Validate foreign constraint fields being passed into API.
1612 * @param mixed $fieldValue
1613 * @param string $fieldName
1614 * Uniquename of field being checked.
1615 * @param array $fieldInfo
1616 * Array of fields from getfields function.
1618 * @throws \API_Exception
1620 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1621 $daoName = $fieldInfo['FKClassName'];
1622 $dao = new $daoName();
1623 $dao->id
= $fieldValue;
1625 $dao->selectAdd('id');
1626 if (!$dao->find()) {
1627 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1632 * Validate foreign constraint fields being passed into API.
1634 * @param array $params
1635 * Params from civicrm_api.
1636 * @param string $fieldName
1637 * Uniquename of field being checked.
1641 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1642 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1643 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1646 $existing = civicrm_api($params['entity'], 'get', array(
1647 'version' => $params['version'],
1648 $fieldName => $fieldValue,
1650 // an entry already exists for this unique field
1651 if ($existing['count'] == 1) {
1652 // question - could this ever be a security issue?
1653 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1658 * Generic implementation of the "replace" action.
1660 * Replace the old set of entities (matching some given keys) with a new set of
1661 * entities (matching the same keys).
1663 * @note This will verify that 'values' is present, but it does not directly verify
1664 * any other parameters.
1666 * @param string $entity
1668 * @param array $params
1669 * Params from civicrm_api, including:.
1670 * - 'values': an array of records to save
1671 * - all other items: keys which identify new/pre-existing records.
1675 function _civicrm_api3_generic_replace($entity, $params) {
1677 $transaction = new CRM_Core_Transaction();
1679 if (!is_array($params['values'])) {
1680 throw new Exception("Mandatory key(s) missing from params array: values");
1683 // Extract the keys -- somewhat scary, don't think too hard about it
1684 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1686 // Lookup pre-existing records
1687 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1688 if (civicrm_error($preexisting)) {
1689 $transaction->rollback();
1690 return $preexisting;
1693 // Save the new/updated records
1695 foreach ($params['values'] as $replacement) {
1696 // Sugar: Don't force clients to duplicate the 'key' data
1697 $replacement = array_merge($baseParams, $replacement);
1698 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1699 $create = civicrm_api($entity, $action, $replacement);
1700 if (civicrm_error($create)) {
1701 $transaction->rollback();
1704 foreach ($create['values'] as $entity_id => $entity_value) {
1705 $creates[$entity_id] = $entity_value;
1709 // Remove stale records
1710 $staleIDs = array_diff(
1711 array_keys($preexisting['values']),
1712 array_keys($creates)
1714 foreach ($staleIDs as $staleID) {
1715 $delete = civicrm_api($entity, 'delete', array(
1716 'version' => $params['version'],
1719 if (civicrm_error($delete)) {
1720 $transaction->rollback();
1725 return civicrm_api3_create_success($creates, $params);
1727 catch(PEAR_Exception
$e) {
1728 $transaction->rollback();
1729 return civicrm_api3_create_error($e->getMessage());
1731 catch(Exception
$e) {
1732 $transaction->rollback();
1733 return civicrm_api3_create_error($e->getMessage());
1738 * Replace base parameters.
1740 * @param array $params
1744 function _civicrm_api3_generic_replace_base_params($params) {
1745 $baseParams = $params;
1746 unset($baseParams['values']);
1747 unset($baseParams['sequential']);
1748 unset($baseParams['options']);
1753 * Returns fields allowable by api.
1756 * String Entity to query.
1757 * @param bool $unique
1758 * Index by unique fields?.
1759 * @param array $params
1763 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1764 $unsetIfEmpty = array(
1771 $dao = _civicrm_api3_get_DAO($entity);
1776 $fields = $d->fields();
1778 // Set html attributes for text fields
1779 foreach ($fields as $name => &$field) {
1780 if (isset($field['html'])) {
1781 $field['html'] +
= (array) $d::makeAttribute($field);
1785 // replace uniqueNames by the normal names as the key
1786 if (empty($unique)) {
1787 foreach ($fields as $name => &$field) {
1788 //getting rid of unused attributes
1789 foreach ($unsetIfEmpty as $attr) {
1790 if (empty($field[$attr])) {
1791 unset($field[$attr]);
1794 if ($name == $field['name']) {
1797 if (array_key_exists($field['name'], $fields)) {
1798 $field['error'] = 'name conflict';
1799 // it should never happen, but better safe than sorry
1802 $fields[$field['name']] = $field;
1803 $fields[$field['name']]['uniqueName'] = $name;
1804 unset($fields[$name]);
1807 // Translate FKClassName to the corresponding api
1808 foreach ($fields as $name => &$field) {
1809 if (!empty($field['FKClassName'])) {
1810 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1812 $field['FKApiName'] = $FKApi;
1816 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1821 * Return an array of fields for a given entity.
1823 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1826 * @param array $params
1830 function _civicrm_api_get_custom_fields($entity, &$params) {
1831 $entity = _civicrm_api_get_camel_name($entity);
1832 if ($entity == 'Contact') {
1833 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1834 $entity = CRM_Utils_Array
::value('contact_type', $params);
1836 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1839 // we could / should probably test for other subtypes here - e.g. activity_type_id
1840 CRM_Utils_Array
::value('contact_sub_type', $params),
1849 foreach ($customfields as $key => $value) {
1850 // Regular fields have a 'name' property
1851 $value['name'] = 'custom_' . $key;
1852 $value['title'] = $value['label'];
1853 $value['type'] = _getStandardTypeFromCustomDataType($value);
1854 $ret['custom_' . $key] = $value;
1860 * Translate the custom field data_type attribute into a std 'type'.
1862 * @param array $value
1866 function _getStandardTypeFromCustomDataType($value) {
1867 $dataType = $value['data_type'];
1868 //CRM-15792 - If date custom field contains timeformat change type to DateTime
1869 if ($value['data_type'] == 'Date' && isset($value['time_format']) && $value['time_format'] > 0) {
1870 $dataType = 'DateTime';
1873 'String' => CRM_Utils_Type
::T_STRING
,
1874 'Int' => CRM_Utils_Type
::T_INT
,
1875 'Money' => CRM_Utils_Type
::T_MONEY
,
1876 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1877 'Float' => CRM_Utils_Type
::T_FLOAT
,
1878 'Date' => CRM_Utils_Type
::T_DATE
,
1879 'DateTime' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
1880 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1881 'StateProvince' => CRM_Utils_Type
::T_INT
,
1882 'File' => CRM_Utils_Type
::T_STRING
,
1883 'Link' => CRM_Utils_Type
::T_STRING
,
1884 'ContactReference' => CRM_Utils_Type
::T_INT
,
1885 'Country' => CRM_Utils_Type
::T_INT
,
1887 return $mapping[$dataType];
1892 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
1894 * If multiple aliases the last takes precedence
1896 * Function also swaps unique fields for non-unique fields & vice versa.
1898 * @param $apiRequest
1901 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1902 foreach ($fields as $field => $values) {
1903 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1904 if (!empty($values['api.aliases'])) {
1905 // if aliased field is not set we try to use field alias
1906 if (!isset($apiRequest['params'][$field])) {
1907 foreach ($values['api.aliases'] as $alias) {
1908 if (isset($apiRequest['params'][$alias])) {
1909 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1911 //unset original field nb - need to be careful with this as it may bring inconsistencies
1912 // out of the woodwork but will be implementing only as _spec function extended
1913 unset($apiRequest['params'][$alias]);
1917 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
1918 && isset($apiRequest['params'][$values['name']])
1920 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1921 // note that it would make sense to unset the original field here but tests need to be in place first
1923 if (!isset($apiRequest['params'][$field])
1925 && $field != $uniqueName
1926 && array_key_exists($uniqueName, $apiRequest['params'])
1928 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1929 // note that it would make sense to unset the original field here but tests need to be in place first
1936 * Validate integer fields being passed into API.
1938 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
1940 * @param array $params
1941 * Params from civicrm_api.
1942 * @param string $fieldName
1943 * Uniquename of field being checked.
1944 * @param array $fieldInfo
1945 * Array of fields from getfields function.
1946 * @param string $entity
1948 * @throws API_Exception
1950 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1951 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1952 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1956 if (!empty($fieldValue)) {
1957 // if value = 'user_contact_id' (or similar), replace value with contact id
1958 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
1959 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
1960 if ('unknown-user' === $realContactId) {
1961 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName, "type" => "integer"));
1963 elseif (is_numeric($realContactId)) {
1964 $fieldValue = $realContactId;
1967 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1968 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
1971 // After swapping options, ensure we have an integer(s)
1972 foreach ((array) ($fieldValue) as $value) {
1973 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1974 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1978 // Check our field length
1979 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
1981 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1982 2100, array('field' => $fieldName, "max_length" => $fieldInfo['maxlength'])
1988 $params[$fieldName][$op] = $fieldValue;
1991 $params[$fieldName] = $fieldValue;
1996 * Determine a contact ID using a string expression.
1998 * @param string $contactIdExpr
1999 * E.g. "user_contact_id" or "@user:username".
2001 * @return int|NULL|'unknown-user'
2003 function _civicrm_api3_resolve_contactID($contactIdExpr) {
2004 // If value = 'user_contact_id' replace value with logged in user id.
2005 if ($contactIdExpr == "user_contact_id") {
2006 return CRM_Core_Session
::getLoggedInContactID();
2008 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
2009 $config = CRM_Core_Config
::singleton();
2011 $ufID = $config->userSystem
->getUfId($matches[1]);
2013 return 'unknown-user';
2016 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
2018 return 'unknown-user';
2027 * Validate html (check for scripting attack).
2029 * @param array $params
2030 * @param string $fieldName
2031 * @param array $fieldInfo
2033 * @throws API_Exception
2035 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
2036 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2037 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
2041 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2042 throw new API_Exception('Input contains illegal SCRIPT tag.', array("field" => $fieldName, "error_code" => "xss"));
2048 * Validate string fields being passed into API.
2050 * @param array $params
2051 * Params from civicrm_api.
2052 * @param string $fieldName
2053 * Uniquename of field being checked.
2054 * @param array $fieldInfo
2055 * Array of fields from getfields function.
2056 * @param string $entity
2058 * @throws API_Exception
2061 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2062 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2063 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
2067 if (!is_array($fieldValue)) {
2068 $fieldValue = (string) $fieldValue;
2071 //@todo what do we do about passed in arrays. For many of these fields
2072 // the missing piece of functionality is separating them to a separated string
2073 // & many save incorrectly. But can we change them wholesale?
2076 foreach ((array) $fieldValue as $value) {
2077 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2078 throw new Exception('Input contains illegal SCRIPT tag.');
2080 if ($fieldName == 'currency') {
2081 //When using IN operator $fieldValue is a array of currency codes
2082 if (!CRM_Utils_Rule
::currencyCode($value)) {
2083 throw new Exception("Currency not a valid code: $currency");
2088 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2089 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
2091 // Check our field length
2092 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2093 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2094 2100, array('field' => $fieldName)
2099 $params[$fieldName][$op] = $fieldValue;
2102 $params[$fieldName] = $fieldValue;
2107 * Validate & swap out any pseudoconstants / options.
2109 * @param mixed $fieldValue
2110 * @param string $entity : api entity name
2111 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2112 * @param array $fieldInfo : getfields meta-data
2114 * @throws \API_Exception
2116 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo) {
2117 $options = CRM_Utils_Array
::value('options', $fieldInfo);
2120 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2121 // We need to get the options from the entity the field relates to.
2122 $entity = $fieldInfo['entity'];
2124 $options = civicrm_api($entity, 'getoptions', array(
2126 'field' => $fieldInfo['name'],
2127 'context' => 'validate',
2129 $options = CRM_Utils_Array
::value('values', $options, array());
2132 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2134 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2135 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
2138 // If passed multiple options, validate each.
2139 if (is_array($fieldValue)) {
2140 foreach ($fieldValue as &$value) {
2141 if (!is_array($value)) {
2142 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
2145 // TODO: unwrap the call to implodePadded from the conditional and do it always
2146 // need to verify that this is safe and doesn't break anything though.
2147 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2149 CRM_Utils_Array
::implodePadded($fieldValue);
2153 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName);
2158 * Validate & swap a single option value for a field.
2160 * @param string $value field value
2161 * @param array $options array of options for this field
2162 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2164 * @throws API_Exception
2166 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
2167 // If option is a key, no need to translate
2168 // or if no options are avaiable for pseudoconstant 'table' property
2169 if (array_key_exists($value, $options) ||
!$options) {
2173 // Translate value into key
2174 $newValue = array_search($value, $options);
2175 if ($newValue !== FALSE) {
2179 // Case-insensitive matching
2180 $newValue = strtolower($value);
2181 $options = array_map("strtolower", $options);
2182 $newValue = array_search($newValue, $options);
2183 if ($newValue === FALSE) {
2184 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
2190 * Returns the canonical name of a field.
2193 * api entity name (string should already be standardized - no camelCase).
2195 * any variation of a field's name (name, unique_name, api.alias).
2197 * @return bool|string
2198 * fieldName or FALSE if the field does not exist
2200 function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') {
2204 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2207 if ($fieldName == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
2210 $result = civicrm_api($entity, 'getfields', array(
2212 'action' => $action,
2214 $meta = $result['values'];
2215 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2216 $fieldName = $fieldName . '_id';
2218 if (isset($meta[$fieldName])) {
2219 return $meta[$fieldName]['name'];
2221 foreach ($meta as $info) {
2222 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2223 return $info['name'];
2225 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
2226 return $info['name'];
2229 // Create didn't work, try with get
2230 if ($action == 'create') {
2231 return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get');
2237 * Check if the function is deprecated.
2239 * @param string $entity
2240 * @param array $result
2242 * @return string|array|null
2244 function _civicrm_api3_deprecation_check($entity, $result = array()) {
2246 $apiFile = "api/v3/$entity.php";
2247 if (CRM_Utils_File
::isIncludable($apiFile)) {
2248 require_once $apiFile;
2250 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
2251 $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation";
2252 if (function_exists($fnName)) {
2253 return $fnName($result);
2259 * Get the actual field value.
2261 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2262 * So this function returns the actual field value
2264 * @param array $params
2265 * @param string $fieldName
2269 function _civicrm_api3_field_value_check(&$params, $fieldName) {
2270 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2273 if (!empty($fieldValue) && is_array($fieldValue) && array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators())) {
2274 $op = key($fieldValue);
2275 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2277 return array($fieldValue, $op);