3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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',
821 foreach ($params as $n => $v) {
822 if (substr($n, 0, 7) == 'return.') {
823 $legacyreturnProperties[substr($n, 7)] = $v;
825 elseif ($n == 'id') {
826 $inputParams[$lowercase_entity . '_id'] = $v;
828 elseif (in_array($n, $otherVars)) {
831 $inputParams[$n] = $v;
832 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
833 throw new API_Exception('invalid string');
837 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
838 $options['input_params'] = $inputParams;
843 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
845 * @param array $params
846 * Params array as passed into civicrm_api.
851 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
853 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
854 if (!$options['is_count']) {
855 if (!empty($options['limit'])) {
856 $dao->limit((int) $options['offset'], (int) $options['limit']);
858 if (!empty($options['sort'])) {
859 $dao->orderBy($options['sort']);
865 * Build fields array.
867 * This is the array of fields as it relates to the given DAO
868 * returns unique fields as keys by default but if set but can return by DB fields
870 * @param CRM_Core_DAO $bao
871 * @param bool $unique
875 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
876 $fields = $bao->fields();
878 if (empty($fields['id'])) {
879 $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
880 $fields['id'] = $fields[$lowercase_entity . '_id'];
881 unset($fields[$lowercase_entity . '_id']);
886 foreach ($fields as $field) {
887 $dbFields[$field['name']] = $field;
893 * Build fields array.
895 * This is the array of fields as it relates to the given DAO
896 * returns unique fields as keys by default but if set but can return by DB fields
898 * @param CRM_Core_DAO $bao
902 function _civicrm_api3_get_unique_name_array(&$bao) {
903 $fields = $bao->fields();
904 foreach ($fields as $field => $values) {
905 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
907 return $uniqueFields;
911 * Converts an DAO object to an array.
913 * @param CRM_Core_DAO $dao
915 * @param array $params
916 * @param bool $uniqueFields
917 * @param string $entity
918 * @param bool $autoFind
922 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
924 if (isset($params['options']) && !empty($params['options']['is_count'])) {
925 return $dao->count();
930 if ($autoFind && !$dao->find()) {
934 if (isset($dao->count
)) {
938 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
940 while ($dao->fetch()) {
942 foreach ($fields as $key) {
943 if (array_key_exists($key, $dao)) {
944 // not sure on that one
945 if ($dao->$key !== NULL) {
946 $tmp[$key] = $dao->$key;
950 $result[$dao->id
] = $tmp;
952 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
953 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
961 * Determine if custom fields need to be retrieved.
963 * We currently retrieve all custom fields or none at this level so if we know the entity
964 * && 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
965 * @todo filter so only required fields are queried
967 * @param string $entity
968 * Entity name in CamelCase.
969 * @param array $params
973 function _civicrm_api3_custom_fields_are_required($entity, $params) {
974 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
977 $options = _civicrm_api3_get_options_from_params($params);
978 // We check for possibility of 'custom' => 1 as well as specific custom fields.
979 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
980 if (stristr($returnString, 'custom')) {
985 * Converts an object to an array.
988 * (reference) object to convert.
989 * @param array $values
991 * @param array|bool $uniqueFields
993 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
995 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
996 foreach ($fields as $key => $value) {
997 if (array_key_exists($key, $dao)) {
998 $values[$key] = $dao->$key;
1004 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1011 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1012 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1016 * Format custom parameters.
1018 * @param array $params
1019 * @param array $values
1020 * @param string $extends
1021 * Entity that this custom field extends (e.g. contribution, event, contact).
1022 * @param string $entityId
1023 * ID of entity per $extends.
1025 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1026 $values['custom'] = array();
1027 $checkCheckBoxField = FALSE;
1029 if (in_array($extends, array('Household', 'Individual', 'Organization'))) {
1030 $entity = 'Contact';
1033 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
1034 if (!$fields['is_error']) {
1035 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1036 $fields = $fields['values'];
1037 $checkCheckBoxField = TRUE;
1040 foreach ($params as $key => $value) {
1041 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
1042 if ($customFieldID && (!is_null($value))) {
1043 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1044 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1047 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1048 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1055 * Format parameters for create action.
1057 * @param array $params
1060 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1061 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1063 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery
::$extendsMap, array_fill_keys($nonGenericEntities, 1));
1064 if (!array_key_exists($entity, $customFieldEntities)) {
1068 _civicrm_api3_custom_format_params($params, $values, $entity);
1069 $params = array_merge($params, $values);
1073 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1075 * We should look at pushing to BAO function
1076 * 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
1077 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1079 * 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
1080 * don't touch - lots of very cautious code in here
1082 * The resulting array should look like
1088 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1090 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1091 * be fixed in future
1093 * @param mixed $checkboxFieldValue
1094 * @param string $customFieldLabel
1095 * @param string $entity
1097 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1099 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1100 // We can assume it's pre-formatted.
1103 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1104 if (!empty($options['is_error'])) {
1105 // The check is precautionary - can probably be removed later.
1109 $options = $options['values'];
1111 if (is_array($checkboxFieldValue)) {
1112 foreach ($checkboxFieldValue as $key => $value) {
1113 if (!array_key_exists($key, $options)) {
1114 $validValue = FALSE;
1118 // we have been passed an array that is already in the 'odd' custom field format
1123 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1124 // if the array only has one item we'll treat it like any other string
1125 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1126 $possibleValue = reset($checkboxFieldValue);
1128 if (is_string($checkboxFieldValue)) {
1129 $possibleValue = $checkboxFieldValue;
1131 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1132 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1135 elseif (is_array($checkboxFieldValue)) {
1136 // so this time around we are considering the values in the array
1137 $possibleValues = $checkboxFieldValue;
1138 $formatValue = TRUE;
1140 elseif (stristr($checkboxFieldValue, ',')) {
1141 $formatValue = TRUE;
1142 //lets see if we should separate it - we do this near the end so we
1143 // ensure we have already checked that the comma is not part of a legitimate match
1144 // and of course, we don't make any changes if we don't now have matches
1145 $possibleValues = explode(',', $checkboxFieldValue);
1148 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1152 foreach ($possibleValues as $index => $possibleValue) {
1153 if (array_key_exists($possibleValue, $options)) {
1154 // 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)
1156 elseif (array_key_exists(trim($possibleValue), $options)) {
1157 $possibleValues[$index] = trim($possibleValue);
1160 $formatValue = FALSE;
1164 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1169 * This function ensures that we have the right input parameters.
1173 * This function is only called when $dao is passed into verify_mandatory.
1174 * The practice of passing $dao into verify_mandatory turned out to be
1175 * unsatisfactory as the required fields @ the dao level is so different to the abstract
1176 * api level. Hence the intention is to remove this function
1177 * & the associated param from verify_mandatory
1179 * @param array $params
1180 * Associative array of property name/value.
1181 * pairs to insert in new history.
1182 * @param string $daoName
1183 * @param bool $return
1185 * @daoName string DAO to check params agains
1188 * Should the missing fields be returned as an array (core error created as default)
1189 * true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1191 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1192 //@deprecated - see notes
1193 if (isset($params['extends'])) {
1194 if (($params['extends'] == 'Activity' ||
1195 $params['extends'] == 'Phonecall' ||
1196 $params['extends'] == 'Meeting' ||
1197 $params['extends'] == 'Group' ||
1198 $params['extends'] == 'Contribution'
1200 ($params['style'] == 'Tab')
1202 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1206 $dao = new $daoName();
1207 $fields = $dao->fields();
1210 foreach ($fields as $k => $v) {
1211 if ($v['name'] == 'id') {
1215 if (!empty($v['required'])) {
1216 // 0 is a valid input for numbers, CRM-8122
1217 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1223 if (!empty($missing)) {
1224 if (!empty($return)) {
1228 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1236 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1238 * @param string $bao_name
1240 * @param array $params
1242 * @param bool $returnAsSuccess
1243 * Return in api success format.
1244 * @param string $entity
1248 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1249 $bao = new $bao_name();
1250 _civicrm_api3_dao_set_filter($bao, $params, TRUE);
1251 if ($returnAsSuccess) {
1252 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1255 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity, 'get');
1260 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1262 * @param string $bao_name
1263 * Name of BAO Class.
1264 * @param array $params
1265 * Parameters passed into the api call.
1266 * @param string $entity
1267 * Entity - pass in if entity is non-standard & required $ids array.
1269 * @throws API_Exception
1272 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1273 _civicrm_api3_format_params_for_create($params, $entity);
1274 $args = array(&$params);
1276 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1280 if (method_exists($bao_name, 'create')) {
1282 $fct_name = $bao_name . '::' . $fct;
1283 $bao = call_user_func_array(array($bao_name, $fct), $args);
1285 elseif (method_exists($bao_name, 'add')) {
1287 $fct_name = $bao_name . '::' . $fct;
1288 $bao = call_user_func_array(array($bao_name, $fct), $args);
1291 $fct_name = '_civicrm_api3_basic_create_fallback';
1292 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1295 if (is_null($bao)) {
1296 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1298 elseif (is_a($bao, 'CRM_Core_Error')) {
1299 //some wierd circular thing means the error takes itself as an argument
1300 $msg = $bao->getMessages($bao);
1301 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1302 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1303 // so we need to reset the error object here to avoid getting concatenated errors
1304 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1305 CRM_Core_Error
::singleton()->reset();
1306 throw new API_Exception($msg);
1310 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1311 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1316 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1318 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1319 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1321 * @param string $bao_name
1322 * @param array $params
1324 * @throws API_Exception
1326 * @return CRM_Core_DAO|NULL
1327 * An instance of the BAO
1329 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1330 $dao_name = get_parent_class($bao_name);
1331 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1332 $dao_name = $bao_name;
1334 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1335 if (empty($entityName)) {
1336 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1337 'class_name' => $bao_name,
1340 $hook = empty($params['id']) ?
'create' : 'edit';
1342 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1343 $instance = new $dao_name();
1344 $instance->copyValues($params);
1346 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1352 * Function to do a 'standard' api del.
1354 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1356 * @param string $bao_name
1357 * @param array $params
1361 * @throws API_Exception
1363 function _civicrm_api3_basic_delete($bao_name, &$params) {
1365 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1366 $args = array(&$params['id']);
1367 if (method_exists($bao_name, 'del')) {
1368 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1369 if ($bao !== FALSE) {
1370 return civicrm_api3_create_success(TRUE);
1372 throw new API_Exception('Could not delete entity id ' . $params['id']);
1374 elseif (method_exists($bao_name, 'delete')) {
1375 $dao = new $bao_name();
1376 $dao->id
= $params['id'];
1378 while ($dao->fetch()) {
1380 return civicrm_api3_create_success();
1384 throw new API_Exception('Could not delete entity id ' . $params['id']);
1388 throw new API_Exception('no delete method found');
1392 * Get custom data for the given entity & Add it to the returnArray.
1394 * This looks like 'custom_123' = 'custom string' AND
1395 * 'custom_123_1' = 'custom string'
1396 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1398 * @param array $returnArray
1399 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1400 * @param string $entity
1401 * E.g membership, event.
1402 * @param int $entity_id
1403 * @param int $groupID
1404 * Per CRM_Core_BAO_CustomGroup::getTree.
1405 * @param int $subType
1406 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1407 * @param string $subName
1408 * Subtype of entity.
1410 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1411 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1412 CRM_Core_DAO
::$_nullObject,
1418 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1419 $customValues = array();
1420 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1421 $fieldInfo = array();
1422 foreach ($groupTree as $set) {
1423 $fieldInfo +
= $set['fields'];
1425 if (!empty($customValues)) {
1426 foreach ($customValues as $key => $val) {
1427 // per standard - return custom_fieldID
1428 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1429 $returnArray['custom_' . $id] = $val;
1431 //not standard - but some api did this so guess we should keep - cheap as chips
1432 $returnArray[$key] = $val;
1434 // Shim to restore legacy behavior of ContactReference custom fields
1435 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1436 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1437 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1444 * Validate fields being passed into API.
1446 * This function relies on the getFields function working accurately
1447 * for the given API. If error mode is set to TRUE then it will also check
1450 * As of writing only date was implemented.
1452 * @param string $entity
1453 * @param string $action
1454 * @param array $params
1456 * @param array $fields
1457 * Response from getfields all variables are the same as per civicrm_api.
1458 * @param bool $errorMode
1459 * ErrorMode do intensive post fail checks?.
1463 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = FALSE) {
1464 //CRM-15792 handle datetime for custom fields below code handles chain api call
1465 $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params)));
1466 if (!empty($chainApikeys) && is_array($chainApikeys)) {
1467 foreach ($chainApikeys as $key => $value) {
1468 if (is_array($params[$key])) {
1469 $chainApiParams = array_intersect_key($fields, $params[$key]);
1470 $customFields = array_fill_keys(array_keys($params[$key]), $key);
1474 $fields = array_intersect_key($fields, $params);
1475 if (!empty($chainApiParams)) {
1476 $fields = array_merge($fields, $chainApiParams);
1478 foreach ($fields as $fieldName => $fieldInfo) {
1479 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1480 case CRM_Utils_Type
::T_INT
:
1481 //field is of type integer
1482 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1485 case CRM_Utils_Type
::T_DATE
:
1486 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1487 case CRM_Utils_Type
::T_TIMESTAMP
:
1488 //field is of type date or datetime
1489 if (!empty($customFields) && array_key_exists($fieldName, $customFields)) {
1490 $dateParams = &$params[$customFields[$fieldName]];
1493 $dateParams = &$params;
1495 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
1500 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1503 case CRM_Utils_Type
::T_STRING
:
1504 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1507 case CRM_Utils_Type
::T_MONEY
:
1508 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1509 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1512 foreach ((array) $fieldValue as $fieldvalue) {
1513 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1514 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1520 // intensive checks - usually only called after DB level fail
1521 if (!empty($errorMode) && strtolower($action) == 'create') {
1522 if (!empty($fieldInfo['FKClassName'])) {
1523 if (!empty($fieldValue)) {
1524 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1526 elseif (!empty($fieldInfo['required'])) {
1527 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1530 if (!empty($fieldInfo['api.unique'])) {
1531 $params['entity'] = $entity;
1532 _civicrm_api3_validate_unique_key($params, $fieldName);
1539 * Validate date fields being passed into API.
1541 * It currently converts both unique fields and DB field names to a mysql date.
1542 * @todo - probably the unique field handling & the if exists handling is now done before this
1543 * function is reached in the wrapper - can reduce this code down to assume we
1544 * are only checking the passed in field
1546 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1547 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1549 * @param array $params
1550 * Params from civicrm_api.
1551 * @param string $fieldName
1552 * Uniquename of field being checked.
1553 * @param array $fieldInfo
1554 * Array of fields from getfields function.
1558 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1559 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1560 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1563 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1564 if (!empty($params[$fieldInfo['name']])) {
1565 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1567 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1568 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1572 $params[$fieldName][$op] = $fieldValue;
1575 $params[$fieldName] = $fieldValue;
1580 * Convert date into BAO friendly date.
1582 * We accept 'whatever strtotime accepts'
1584 * @param string $dateValue
1585 * @param string $fieldName
1591 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1592 if (is_array($dateValue)) {
1593 foreach ($dateValue as $key => $value) {
1594 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1598 if (strtotime($dateValue) === FALSE) {
1599 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1601 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1602 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1606 * Validate foreign constraint fields being passed into API.
1608 * @param mixed $fieldValue
1609 * @param string $fieldName
1610 * Uniquename of field being checked.
1611 * @param array $fieldInfo
1612 * Array of fields from getfields function.
1614 * @throws \API_Exception
1616 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1617 $daoName = $fieldInfo['FKClassName'];
1618 $dao = new $daoName();
1619 $dao->id
= $fieldValue;
1621 $dao->selectAdd('id');
1622 if (!$dao->find()) {
1623 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1628 * Validate foreign constraint fields being passed into API.
1630 * @param array $params
1631 * Params from civicrm_api.
1632 * @param string $fieldName
1633 * Uniquename of field being checked.
1637 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1638 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1639 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1642 $existing = civicrm_api($params['entity'], 'get', array(
1643 'version' => $params['version'],
1644 $fieldName => $fieldValue,
1646 // an entry already exists for this unique field
1647 if ($existing['count'] == 1) {
1648 // question - could this ever be a security issue?
1649 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1654 * Generic implementation of the "replace" action.
1656 * Replace the old set of entities (matching some given keys) with a new set of
1657 * entities (matching the same keys).
1659 * @note This will verify that 'values' is present, but it does not directly verify
1660 * any other parameters.
1662 * @param string $entity
1664 * @param array $params
1665 * Params from civicrm_api, including:.
1666 * - 'values': an array of records to save
1667 * - all other items: keys which identify new/pre-existing records.
1671 function _civicrm_api3_generic_replace($entity, $params) {
1673 $transaction = new CRM_Core_Transaction();
1675 if (!is_array($params['values'])) {
1676 throw new Exception("Mandatory key(s) missing from params array: values");
1679 // Extract the keys -- somewhat scary, don't think too hard about it
1680 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1682 // Lookup pre-existing records
1683 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1684 if (civicrm_error($preexisting)) {
1685 $transaction->rollback();
1686 return $preexisting;
1689 // Save the new/updated records
1691 foreach ($params['values'] as $replacement) {
1692 // Sugar: Don't force clients to duplicate the 'key' data
1693 $replacement = array_merge($baseParams, $replacement);
1694 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1695 $create = civicrm_api($entity, $action, $replacement);
1696 if (civicrm_error($create)) {
1697 $transaction->rollback();
1700 foreach ($create['values'] as $entity_id => $entity_value) {
1701 $creates[$entity_id] = $entity_value;
1705 // Remove stale records
1706 $staleIDs = array_diff(
1707 array_keys($preexisting['values']),
1708 array_keys($creates)
1710 foreach ($staleIDs as $staleID) {
1711 $delete = civicrm_api($entity, 'delete', array(
1712 'version' => $params['version'],
1715 if (civicrm_error($delete)) {
1716 $transaction->rollback();
1721 return civicrm_api3_create_success($creates, $params);
1723 catch(PEAR_Exception
$e) {
1724 $transaction->rollback();
1725 return civicrm_api3_create_error($e->getMessage());
1727 catch(Exception
$e) {
1728 $transaction->rollback();
1729 return civicrm_api3_create_error($e->getMessage());
1734 * Replace base parameters.
1736 * @param array $params
1740 function _civicrm_api3_generic_replace_base_params($params) {
1741 $baseParams = $params;
1742 unset($baseParams['values']);
1743 unset($baseParams['sequential']);
1744 unset($baseParams['options']);
1749 * Returns fields allowable by api.
1752 * String Entity to query.
1753 * @param bool $unique
1754 * Index by unique fields?.
1755 * @param array $params
1759 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1760 $unsetIfEmpty = array(
1767 $dao = _civicrm_api3_get_DAO($entity);
1772 $fields = $d->fields();
1773 // replace uniqueNames by the normal names as the key
1774 if (empty($unique)) {
1775 foreach ($fields as $name => &$field) {
1776 //getting rid of unused attributes
1777 foreach ($unsetIfEmpty as $attr) {
1778 if (empty($field[$attr])) {
1779 unset($field[$attr]);
1782 if ($name == $field['name']) {
1785 if (array_key_exists($field['name'], $fields)) {
1786 $field['error'] = 'name conflict';
1787 // it should never happen, but better safe than sorry
1790 $fields[$field['name']] = $field;
1791 $fields[$field['name']]['uniqueName'] = $name;
1792 unset($fields[$name]);
1795 // Translate FKClassName to the corresponding api
1796 foreach ($fields as $name => &$field) {
1797 if (!empty($field['FKClassName'])) {
1798 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1800 $field['FKApiName'] = $FKApi;
1804 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1809 * Return an array of fields for a given entity.
1811 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1814 * @param array $params
1818 function _civicrm_api_get_custom_fields($entity, &$params) {
1819 $entity = _civicrm_api_get_camel_name($entity);
1820 if ($entity == 'Contact') {
1821 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1822 $entity = CRM_Utils_Array
::value('contact_type', $params);
1824 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1827 // we could / should probably test for other subtypes here - e.g. activity_type_id
1828 CRM_Utils_Array
::value('contact_sub_type', $params),
1837 foreach ($customfields as $key => $value) {
1838 // Regular fields have a 'name' property
1839 $value['name'] = 'custom_' . $key;
1840 $value['title'] = $value['label'];
1841 $value['type'] = _getStandardTypeFromCustomDataType($value);
1842 $ret['custom_' . $key] = $value;
1848 * Translate the custom field data_type attribute into a std 'type'.
1850 * @param array $value
1854 function _getStandardTypeFromCustomDataType($value) {
1855 $dataType = $value['data_type'];
1856 //CRM-15792 - If date custom field contains timeformat change type to DateTime
1857 if ($value['data_type'] == 'Date' && isset($value['time_format']) && $value['time_format'] > 0) {
1858 $dataType = 'DateTime';
1861 'String' => CRM_Utils_Type
::T_STRING
,
1862 'Int' => CRM_Utils_Type
::T_INT
,
1863 'Money' => CRM_Utils_Type
::T_MONEY
,
1864 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1865 'Float' => CRM_Utils_Type
::T_FLOAT
,
1866 'Date' => CRM_Utils_Type
::T_DATE
,
1867 'DateTime' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
1868 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1869 'StateProvince' => CRM_Utils_Type
::T_INT
,
1870 'File' => CRM_Utils_Type
::T_STRING
,
1871 'Link' => CRM_Utils_Type
::T_STRING
,
1872 'ContactReference' => CRM_Utils_Type
::T_INT
,
1873 'Country' => CRM_Utils_Type
::T_INT
,
1875 return $mapping[$dataType];
1880 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
1882 * If multiple aliases the last takes precedence
1884 * Function also swaps unique fields for non-unique fields & vice versa.
1886 * @param $apiRequest
1889 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1890 foreach ($fields as $field => $values) {
1891 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1892 if (!empty($values['api.aliases'])) {
1893 // if aliased field is not set we try to use field alias
1894 if (!isset($apiRequest['params'][$field])) {
1895 foreach ($values['api.aliases'] as $alias) {
1896 if (isset($apiRequest['params'][$alias])) {
1897 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1899 //unset original field nb - need to be careful with this as it may bring inconsistencies
1900 // out of the woodwork but will be implementing only as _spec function extended
1901 unset($apiRequest['params'][$alias]);
1905 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
1906 && isset($apiRequest['params'][$values['name']])
1908 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1909 // note that it would make sense to unset the original field here but tests need to be in place first
1911 if (!isset($apiRequest['params'][$field])
1913 && $field != $uniqueName
1914 && array_key_exists($uniqueName, $apiRequest['params'])
1916 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1917 // note that it would make sense to unset the original field here but tests need to be in place first
1924 * Validate integer fields being passed into API.
1926 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
1928 * @param array $params
1929 * Params from civicrm_api.
1930 * @param string $fieldName
1931 * Uniquename of field being checked.
1932 * @param array $fieldInfo
1933 * Array of fields from getfields function.
1934 * @param string $entity
1936 * @throws API_Exception
1938 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1939 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1940 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1944 if (!empty($fieldValue)) {
1945 // if value = 'user_contact_id' (or similar), replace value with contact id
1946 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
1947 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
1948 if ('unknown-user' === $realContactId) {
1949 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName, "type" => "integer"));
1951 elseif (is_numeric($realContactId)) {
1952 $fieldValue = $realContactId;
1955 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1956 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
1959 // After swapping options, ensure we have an integer(s)
1960 foreach ((array) ($fieldValue) as $value) {
1961 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1962 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1966 // Check our field length
1967 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
1969 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1970 2100, array('field' => $fieldName, "max_length" => $fieldInfo['maxlength'])
1976 $params[$fieldName][$op] = $fieldValue;
1979 $params[$fieldName] = $fieldValue;
1984 * Determine a contact ID using a string expression.
1986 * @param string $contactIdExpr
1987 * E.g. "user_contact_id" or "@user:username".
1989 * @return int|NULL|'unknown-user'
1991 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1992 // If value = 'user_contact_id' replace value with logged in user id.
1993 if ($contactIdExpr == "user_contact_id") {
1994 return CRM_Core_Session
::getLoggedInContactID();
1996 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1997 $config = CRM_Core_Config
::singleton();
1999 $ufID = $config->userSystem
->getUfId($matches[1]);
2001 return 'unknown-user';
2004 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
2006 return 'unknown-user';
2015 * Validate html (check for scripting attack).
2017 * @param array $params
2018 * @param string $fieldName
2019 * @param array $fieldInfo
2021 * @throws API_Exception
2023 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
2024 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2025 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
2029 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2030 throw new API_Exception('Illegal characters in input (potential scripting attack)', array("field" => $fieldName, "error_code" => "xss"));
2036 * Validate string fields being passed into API.
2038 * @param array $params
2039 * Params from civicrm_api.
2040 * @param string $fieldName
2041 * Uniquename of field being checked.
2042 * @param array $fieldInfo
2043 * Array of fields from getfields function.
2044 * @param string $entity
2046 * @throws API_Exception
2049 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2050 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2051 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
2055 if (!is_array($fieldValue)) {
2056 $fieldValue = (string) $fieldValue;
2059 //@todo what do we do about passed in arrays. For many of these fields
2060 // the missing piece of functionality is separating them to a separated string
2061 // & many save incorrectly. But can we change them wholesale?
2064 foreach ((array) $fieldValue as $value) {
2065 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2066 throw new Exception('Illegal characters in input (potential scripting attack)');
2068 if ($fieldName == 'currency') {
2069 //When using IN operator $fieldValue is a array of currency codes
2070 if (!CRM_Utils_Rule
::currencyCode($value)) {
2071 throw new Exception("Currency not a valid code: $currency");
2076 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2077 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
2079 // Check our field length
2080 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2081 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2082 2100, array('field' => $fieldName)
2087 $params[$fieldName][$op] = $fieldValue;
2090 $params[$fieldName] = $fieldValue;
2095 * Validate & swap out any pseudoconstants / options.
2097 * @param mixed $fieldValue
2098 * @param string $entity : api entity name
2099 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2100 * @param array $fieldInfo : getfields meta-data
2102 * @throws \API_Exception
2104 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo) {
2105 $options = CRM_Utils_Array
::value('options', $fieldInfo);
2108 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2109 // We need to get the options from the entity the field relates to.
2110 $entity = $fieldInfo['entity'];
2112 $options = civicrm_api($entity, 'getoptions', array(
2114 'field' => $fieldInfo['name'],
2115 'context' => 'validate',
2117 $options = CRM_Utils_Array
::value('values', $options, array());
2120 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2122 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2123 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
2126 // If passed multiple options, validate each.
2127 if (is_array($fieldValue)) {
2128 foreach ($fieldValue as &$value) {
2129 if (!is_array($value)) {
2130 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
2133 // TODO: unwrap the call to implodePadded from the conditional and do it always
2134 // need to verify that this is safe and doesn't break anything though.
2135 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2137 CRM_Utils_Array
::implodePadded($fieldValue);
2141 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName);
2146 * Validate & swap a single option value for a field.
2148 * @param string $value field value
2149 * @param array $options array of options for this field
2150 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2152 * @throws API_Exception
2154 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
2155 // If option is a key, no need to translate
2156 // or if no options are avaiable for pseudoconstant 'table' property
2157 if (array_key_exists($value, $options) ||
!$options) {
2161 // Translate value into key
2162 $newValue = array_search($value, $options);
2163 if ($newValue !== FALSE) {
2167 // Case-insensitive matching
2168 $newValue = strtolower($value);
2169 $options = array_map("strtolower", $options);
2170 $newValue = array_search($newValue, $options);
2171 if ($newValue === FALSE) {
2172 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
2178 * Returns the canonical name of a field.
2181 * api entity name (string should already be standardized - no camelCase).
2183 * any variation of a field's name (name, unique_name, api.alias).
2185 * @return bool|string
2186 * fieldName or FALSE if the field does not exist
2188 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
2189 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2192 if ($fieldName == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
2195 $result = civicrm_api($entity, 'getfields', array(
2197 'action' => 'create',
2199 $meta = $result['values'];
2200 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2201 $fieldName = $fieldName . '_id';
2203 if (isset($meta[$fieldName])) {
2204 return $meta[$fieldName]['name'];
2206 foreach ($meta as $info) {
2207 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2208 return $info['name'];
2210 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
2211 return $info['name'];
2218 * Check if the function is deprecated.
2220 * @param string $entity
2221 * @param array $result
2223 * @return string|array|null
2225 function _civicrm_api3_deprecation_check($entity, $result = array()) {
2227 $apiFile = "api/v3/$entity.php";
2228 if (CRM_Utils_File
::isIncludable($apiFile)) {
2229 require_once $apiFile;
2231 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
2232 $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation";
2233 if (function_exists($fnName)) {
2234 return $fnName($result);
2240 * Get the actual field value.
2242 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2243 * So this function returns the actual field value
2245 * @param array $params
2246 * @param string $fieldName
2250 function _civicrm_api3_field_value_check(&$params, $fieldName) {
2251 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2254 if (!empty($fieldValue) && is_array($fieldValue) && array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators())) {
2255 $op = key($fieldValue);
2256 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2258 return array($fieldValue, $op);