3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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 * File for CiviCRM APIv3 utilitity functions
31 * @package CiviCRM_APIv3
32 * @subpackage API_utils
34 * @copyright CiviCRM LLC (c) 2004-2013
35 * @version $Id: utils.php 30879 2010-11-22 15:45:55Z shot $
40 * Initialize CiviCRM - should be run at the start of each API function
42 function _civicrm_api3_initialize() {
43 require_once 'CRM/Core/ClassLoader.php';
44 CRM_Core_ClassLoader
::singleton()->register();
45 CRM_Core_Config
::singleton();
49 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking
51 * @param array $params array of fields to checkl
52 * @param array $daoName string DAO to check for required fields (create functions only)
53 * @param array $keyoptions
55 * @internal param array $keys list of required fields options. One of the options is required
56 * @return null or throws error if there the required fields not present
59 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = array(
61 $keys = array(array());
62 foreach ($keyoptions as $key) {
65 civicrm_api3_verify_mandatory($params, $daoName, $keys);
69 * Function to check mandatory fields are included
71 * @param array $params array of fields to check
72 * @param array $daoName string DAO to check for required fields (create functions only)
73 * @param array $keys list of required fields. A value can be an array denoting that either this or that is required.
74 * @param bool $verifyDAO
76 * @throws API_Exception
77 * @return null or throws error if there the required fields not present
79 * @todo see notes on _civicrm_api3_check_required_fields regarding removing $daoName param
81 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = array(), $verifyDAO = TRUE) {
84 if ($daoName != NULL && $verifyDAO && empty($params['id'])) {
85 $unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
86 if (!is_array($unmatched)) {
91 if (!empty($params['id'])) {
92 $keys = array('version');
95 if (!in_array('version', $keys)) {
96 // required from v3 onwards
100 foreach ($keys as $key) {
101 if (is_array($key)) {
103 $optionset = array();
104 foreach ($key as $subkey) {
105 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
106 $optionset[] = $subkey;
109 // as long as there is one match then we don't need to rtn anything
113 if (empty($match) && !empty($optionset)) {
114 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
118 // Disallow empty values except for the number zero.
119 // TODO: create a utility for this since it's needed in many places
120 if (!array_key_exists($key, $params) ||
(empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
125 if (!empty($unmatched)) {
126 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched),"mandatory_missing",array("fields"=>$unmatched));
132 * @param <type> $data
134 * @param array $dao (misnomer) apiRequest which led to this error (with keys "entity", "action", etc)
136 * @throws API_Exception
137 * @return array <type>
139 function civicrm_api3_create_error($msg, $data = array(), &$dao = NULL) {
140 if (is_array($dao)) {
141 if ($msg == 'DB Error: constraint violation' ||
substr($msg, 0,9) == 'DB Error:' ||
$msg == 'DB Error: already exists') {
143 $fields = _civicrm_api3_api_getfields($dao);
144 _civicrm_api3_validate_fields($dao['entity'], $dao['action'], $dao['params'], $fields, TRUE);
146 catch(Exception
$e) {
147 $msg = $e->getMessage();
151 $data['is_error'] = 1;
152 $data['error_message'] = $msg;
153 // we will show sql to privelledged user only (not sure of a specific
154 // security hole here but seems sensible - perhaps should apply to the trace as well?
155 if(isset($data['sql']) && CRM_Core_Permission
::check('Administer CiviCRM')) {
156 $data['debug_information'] = $data['sql']; // Isn't this redundant?
160 if (is_array($dao) && isset($dao['params']) && is_array($dao['params']) && !empty($dao['params']['api.has_parent'])) {
161 $errorCode = empty($data['error_code']) ?
'chained_api_failed' : $data['error_code'];
162 throw new API_Exception('Error in call to ' . $dao['entity'] . '_' . $dao['action'] . ' : ' . $msg, $errorCode, $data);
168 * Format array in result output styple
170 * @param array $values values generated by API operation (the result)
171 * @param array $params parameters passed into API call
172 * @param string $entity the entity being acted on
173 * @param string $action the action passed to the API
174 * @param object $dao DAO object to be freed here
175 * @param array $extraReturnValues additional values to be added to top level of result array(
176 * - this param is currently used for legacy behaviour support
178 * @return array $result
180 function civicrm_api3_create_success($values = 1, $params = array(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
182 $result['is_error'] = 0;
183 //lets set the ['id'] field if it's not set & we know what the entity is
184 if (is_array($values) && !empty($entity)) {
185 foreach ($values as $key => $item) {
186 if (empty($item['id']) && !empty($item[$entity . "_id"])) {
187 $values[$key]['id'] = $item[$entity . "_id"];
189 if(!empty($item['financial_type_id'])){
190 //4.3 legacy handling
191 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
193 if(!empty($item['next_sched_contribution_date'])){
194 // 4.4 legacy handling
195 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
200 if (is_array($params) && !empty($params['debug'])) {
201 if (is_string($action) && $action != 'getfields') {
202 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) +
$params);
204 elseif ($action != 'getfields') {
205 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
211 $allFields = array();
212 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
213 $allFields = array_keys($apiFields['values']);
215 $paramFields = array_keys($params);
216 $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), array('action', 'entity', 'debug', 'version', 'check_permissions', 'IDS_request_uri', 'IDS_user_agent', 'return', 'sequential', 'rowCount', 'option_offset', 'option_limit', 'custom', 'option_sort', 'options'));
218 $result['undefined_fields'] = array_merge($undefined);
221 if (is_object($dao)) {
225 $result['version'] = 3;
226 if (is_array($values)) {
227 $result['count'] = (int) count($values);
229 // Convert value-separated strings to array
230 _civicrm_api3_separate_values($values);
232 if ($result['count'] == 1) {
233 list($result['id']) = array_keys($values);
235 elseif (!empty($values['id']) && is_int($values['id'])) {
236 $result['id'] = $values['id'];
240 $result['count'] = !empty($values) ?
1 : 0;
243 if (is_array($values) && isset($params['sequential']) &&
244 $params['sequential'] == 1
246 $result['values'] = array_values($values);
249 $result['values'] = $values;
251 if(!empty($params['options']['metadata'])) {
252 // we've made metadata an array but only supporting 'fields' atm
253 if(in_array('fields', $params['options']['metadata'])) {
254 $fields = civicrm_api3($entity, 'getfields', array('action' => substr($action, 0, 3) == 'get' ?
'get' : 'create'));
255 $result['metadata']['fields'] = $fields['values'];
258 return array_merge($result, $extraReturnValues);
262 * Load the DAO of the entity
264 function _civicrm_api3_load_DAO($entity) {
265 $dao = _civicrm_api3_get_DAO($entity);
274 * Function to return the DAO of the function or Entity
275 * @param String $name either a function of the api (civicrm_{entity}_create or the entity name
276 * return the DAO name to manipulate this function
277 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
278 * @return mixed|string
280 function _civicrm_api3_get_DAO($name) {
281 if (strpos($name, 'civicrm_api3') !== FALSE) {
282 $last = strrpos($name, '_');
283 // len ('civicrm_api3_') == 13
284 $name = substr($name, 13, $last - 13);
287 $name = _civicrm_api_get_camel_name($name, 3);
289 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
293 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
295 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
296 // but am not confident mailing_recipients is tested so have not tackled.
297 if ($name == 'MailingRecipients') {
298 return 'CRM_Mailing_DAO_Recipients';
300 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
301 if ($name == 'MailingComponent') {
302 return 'CRM_Mailing_DAO_Component';
304 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
305 if ($name == 'AclRole') {
306 return 'CRM_ACL_DAO_EntityRole';
308 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
309 // But this would impact SMS extensions so need to coordinate
310 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
311 if ($name == 'SmsProvider') {
312 return 'CRM_SMS_DAO_Provider';
314 // FIXME: DAO names should follow CamelCase convention
315 if ($name == 'Im' ||
$name == 'Acl') {
316 $name = strtoupper($name);
318 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
319 if ($dao ||
!$name) {
323 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
324 include_once "api/v3/$name.php";
325 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
326 if (function_exists($daoFn)) {
334 * Function to return the DAO of the function or Entity
335 * @param String $name is either a function of the api (civicrm_{entity}_create or the entity name
336 * return the DAO name to manipulate this function
337 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
340 function _civicrm_api3_get_BAO($name) {
341 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
342 if ($name == 'PrintLabel') {
343 return 'CRM_Badge_BAO_Layout';
345 $dao = _civicrm_api3_get_DAO($name);
349 $bao = str_replace("DAO", "BAO", $dao);
350 $file = strtr($bao, '_', '/') . '.php';
351 // Check if this entity actually has a BAO. Fall back on the DAO if not.
352 return stream_resolve_include_path($file) ?
$bao : $dao;
356 * Recursive function to explode value-separated strings into arrays
359 function _civicrm_api3_separate_values(&$values) {
360 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
361 foreach ($values as $key => & $value) {
362 if (is_array($value)) {
363 _civicrm_api3_separate_values($value);
365 elseif (is_string($value)) {
366 if($key == 'case_type_id'){// this is to honor the way case API was originally written
367 $value = trim(str_replace($sp, ',', $value), ',');
369 elseif (strpos($value, $sp) !== FALSE) {
370 $value = explode($sp, trim($value, $sp));
377 * This is a legacy wrapper for api_store_values which will check the suitable fields using getfields
378 * rather than DAO->fields
380 * Getfields has handling for how to deal with uniquenames which dao->fields doesn't
382 * Note this is used by BAO type create functions - eg. contribution
383 * @param string $entity
384 * @param array $params
385 * @param array $values
387 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values){
388 $fields = civicrm_api($entity,'getfields', array('version' => 3,'action' => 'create'));
389 $fields = $fields['values'];
390 _civicrm_api3_store_values($fields, $params, $values);
394 * @param array $fields
395 * @param array $params
396 * @param array $values
398 * @return Bool $valueFound
400 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
403 $keys = array_intersect_key($params, $fields);
404 foreach ($keys as $name => $value) {
405 if ($name !== 'id') {
406 $values[$name] = $value;
414 * The API supports 2 types of get requestion. The more complex uses the BAO query object.
415 * This is a generic function for those functions that call it
417 * At the moment only called by contact we should extend to contribution &
418 * others that use the query object. Note that this function passes permission information in.
421 * * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
424 * @param array $params as passed into api get or getcount function
425 * @param array $additional_options
426 * @param bool $getCount are we just after the count
429 * @internal param array $options array of options (so we can modify the filter)
431 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL){
433 // Convert id to e.g. contact_id
434 if (empty($params[$entity . '_id']) && isset($params['id'])) {
435 $params[$entity . '_id'] = $params['id'];
437 unset($params['id']);
439 $options = _civicrm_api3_get_options_from_params($params, TRUE);
441 $inputParams = array_merge(
442 CRM_Utils_Array
::value('input_params', $options, array()),
443 CRM_Utils_Array
::value('input_params', $additional_options, array())
445 $returnProperties = array_merge(
446 CRM_Utils_Array
::value('return', $options, array()),
447 CRM_Utils_Array
::value('return', $additional_options, array())
449 if(empty($returnProperties)){
450 $returnProperties = NULL;
452 if(!empty($params['check_permissions'])){
453 // we will filter query object against getfields
454 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
455 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
456 $fields['values'][$entity . '_id'] = array();
457 $varsToFilter = array('returnProperties', 'inputParams');
458 foreach ($varsToFilter as $varToFilter){
459 if(!is_array($
$varToFilter)){
462 //I was going to throw an exception rather than silently filter out - but
463 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
464 //so we are silently ignoring parts of their request
465 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
466 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
469 $options = array_merge($options,$additional_options);
470 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
471 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
472 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
473 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
477 $returnProperties = NULL;
480 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
481 foreach ($newParams as &$newParam) {
482 if($newParam[1] == '=' && is_array($newParam[2])) {
483 // we may be looking at an attempt to use the 'IN' style syntax
484 // @todo at time of writing only 'IN' & 'NOT IN' are supported for the array style syntax
485 $sqlFilter = CRM_Core_DAO
::createSqlFilter($newParam[0], $params[$newParam[0]], 'String', NULL, TRUE);
487 $newParam[1] = key($newParam[2]);
488 $newParam[2] = $sqlFilter;
493 $skipPermissions = !empty($params['check_permissions']) ?
0 :1;
495 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
506 if ($getCount) { // only return the count of contacts
514 * get dao query object based on input params
515 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
518 * @param array $params
519 * @param string $mode
520 * @param string $entity
521 * @return CRM_Core_DAO query object
523 function _civicrm_api3_get_query_object($params, $mode, $entity) {
524 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
525 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
526 $offset = CRM_Utils_Array
::value('offset', $options);
527 $rowCount = CRM_Utils_Array
::value('limit', $options);
528 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
529 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
530 if (empty($returnProperties)) {
531 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
534 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
535 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
538 list($select, $from, $where, $having) = $query->query();
540 $sql = "$select $from $where $having";
543 $sql .= " ORDER BY $sort ";
545 if(!empty($rowCount)) {
546 $sql .= " LIMIT $offset, $rowCount ";
548 $dao = CRM_Core_DAO
::executeQuery($sql);
549 return array($dao, $query);
553 * Function transfers the filters being passed into the DAO onto the params object
555 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $entity) {
556 $entity = substr($dao->__table
, 8);
558 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
560 $fields = array_intersect(array_keys($allfields), array_keys($params));
561 if (isset($params[$entity . "_id"])) {
562 //if entity_id is set then treat it as ID (will be overridden by id if set)
563 $dao->id
= $params[$entity . "_id"];
566 $options = _civicrm_api3_get_options_from_params($params);
567 //apply options like sort
568 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
570 //accept filters like filter.activity_date_time_high
571 // std is now 'filters' => ..
572 if (strstr(implode(',', array_keys($params)), 'filter')) {
573 if (isset($params['filters']) && is_array($params['filters'])) {
574 foreach ($params['filters'] as $paramkey => $paramvalue) {
575 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
579 foreach ($params as $paramkey => $paramvalue) {
580 if (strstr($paramkey, 'filter')) {
581 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
586 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
587 // support for other syntaxes is discussed in ticket but being put off for now
588 $acceptedSQLOperators = array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN');
593 foreach ($fields as $field) {
594 if (is_array($params[$field])) {
595 //get the actual fieldname from db
596 $fieldName = $allfields[$field]['name'];
597 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
599 $dao->whereAdd($where);
604 $daoFieldName = $allfields[$field]['name'];
605 if (empty($daoFieldName)) {
606 throw new API_Exception("Failed to determine field name for \"$field\"");
608 $dao->{$daoFieldName} = $params[$field];
611 $dao->$field = $params[$field];
615 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
617 $options['return']['id'] = TRUE;// ensure 'id' is included
618 $allfields = _civicrm_api3_get_unique_name_array($dao);
619 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
620 foreach ($returnMatched as $returnValue) {
621 $dao->selectAdd($returnValue);
624 $unmatchedFields = array_diff(// not already matched on the field names
625 array_keys($options['return']),
629 $returnUniqueMatched = array_intersect(
631 array_flip($allfields)// but a match for the field keys
633 foreach ($returnUniqueMatched as $uniqueVal){
634 $dao->selectAdd($allfields[$uniqueVal]);
637 $dao->setApiFilter($params);
641 * Apply filters (e.g. high, low) to DAO object (prior to find)
642 * @param string $filterField field name of filter
643 * @param string $filterValue field value of filter
644 * @param object $dao DAO object
646 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
647 if (strstr($filterField, 'high')) {
648 $fieldName = substr($filterField, 0, -5);
649 $dao->whereAdd("($fieldName <= $filterValue )");
651 if (strstr($filterField, 'low')) {
652 $fieldName = substr($filterField, 0, -4);
653 $dao->whereAdd("($fieldName >= $filterValue )");
655 if($filterField == 'is_current' && $filterValue == 1){
656 $todayStart = date('Ymd000000', strtotime('now'));
657 $todayEnd = date('Ymd235959', strtotime('now'));
658 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
659 if(property_exists($dao, 'is_active')){
660 $dao->whereAdd('is_active = 1');
666 * Get sort, limit etc options from the params - supporting old & new formats.
667 * get returnproperties for legacy
669 * @param array $params params array as passed into civicrm_api
670 * @param bool $queryObject - is this supporting a queryobject api (e.g contact) - if so we support more options
671 * for legacy report & return a unique fields array
673 * @param string $entity
674 * @param string $action
676 * @return array $options options extracted from params
678 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
680 $sort = CRM_Utils_Array
::value('sort', $params, 0);
681 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
682 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
684 $offset = CRM_Utils_Array
::value('offset', $params, 0);
685 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
686 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
687 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
689 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
690 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
691 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
693 if (is_array(CRM_Utils_Array
::value('options', $params))) {
694 // is count is set by generic getcount not user
695 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
696 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
697 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
698 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
701 $returnProperties = array();
702 // handle the format return =sort_name,display_name...
703 if (array_key_exists('return', $params)) {
704 if (is_array($params['return'])) {
705 $returnProperties = array_fill_keys($params['return'], 1);
708 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
709 $returnProperties = array_fill_keys($returnProperties, 1);
712 if ($entity && $action =='get') {
713 if (!empty($returnProperties['id'])) {
714 $returnProperties[$entity . '_id'] = 1;
715 unset($returnProperties['id']);
717 switch (trim(strtolower($sort))){
721 $sort = str_replace('id', $entity . '_id',$sort);
726 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
727 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
728 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
729 'is_count' => $is_count,
730 'return' => !empty($returnProperties) ?
$returnProperties : NULL,
733 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
734 throw new API_Exception('invalid string in sort options');
740 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
741 // if the queryobject is being used this should be used
742 $inputParams = array();
743 $legacyreturnProperties = array();
745 'sort', 'offset', 'rowCount', 'options','return',
747 foreach ($params as $n => $v) {
748 if (substr($n, 0, 7) == 'return.') {
749 $legacyreturnProperties[substr($n, 7)] = $v;
751 elseif ($n == 'id') {
752 $inputParams[$entity. '_id'] = $v;
754 elseif (in_array($n, $otherVars)) {}
756 $inputParams[$n] = $v;
757 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
758 throw new API_Exception('invalid string');
762 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
763 $options['input_params'] = $inputParams;
768 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find)
770 * @param array $params params array as passed into civicrm_api
771 * @param object $dao DAO object
774 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
776 $options = _civicrm_api3_get_options_from_params($params,FALSE,$entity);
777 if(!$options['is_count']) {
778 if(!empty($options['limit'])) {
779 $dao->limit((int)$options['offset'], (int)$options['limit']);
781 if (!empty($options['sort'])) {
782 $dao->orderBy($options['sort']);
788 * build fields array. This is the array of fields as it relates to the given DAO
789 * returns unique fields as keys by default but if set but can return by DB fields
791 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
792 $fields = $bao->fields();
794 if (empty($fields['id'])){
795 $entity = _civicrm_api_get_entity_name_from_dao($bao);
796 $fields['id'] = $fields[$entity . '_id'];
797 unset($fields[$entity . '_id']);
802 foreach ($fields as $field) {
803 $dbFields[$field['name']] = $field;
809 * build fields array. This is the array of fields as it relates to the given DAO
810 * returns unique fields as keys by default but if set but can return by DB fields
812 function _civicrm_api3_get_unique_name_array(&$bao) {
813 $fields = $bao->fields();
814 foreach ($fields as $field => $values) {
815 $uniqueFields[$field] = CRM_Utils_Array
::value('name',$values, $field);
817 return $uniqueFields;
821 * Converts an DAO object to an array
823 * @param object $dao (reference )object to convert
824 * @param null $params
825 * @param bool $uniqueFields
826 * @param string $entity
830 * @params array of arrays (key = id) of array of fields
835 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
837 if(isset($params['options']) && !empty($params['options']['is_count'])) {
838 return $dao->count();
843 if ($autoFind && !$dao->find()) {
847 if(isset($dao->count
)) {
850 //if custom fields are required we will endeavour to set them . NB passing $entity in might be a bit clunky / unrequired
851 if (!empty($entity) && !empty($params['return']) && is_array($params['return'])) {
852 foreach ($params['return'] as $return) {
853 if (substr($return, 0, 6) == 'custom') {
860 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
862 while ($dao->fetch()) {
864 foreach ($fields as $key) {
865 if (array_key_exists($key, $dao)) {
866 // not sure on that one
867 if ($dao->$key !== NULL) {
868 $tmp[$key] = $dao->$key;
872 $result[$dao->id
] = $tmp;
873 if (!empty($custom)) {
874 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
883 * Converts an object to an array
885 * @param object $dao (reference) object to convert
886 * @param array $values (reference) array
887 * @param array|bool $uniqueFields
893 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
895 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
896 foreach ($fields as $key => $value) {
897 if (array_key_exists($key, $dao)) {
898 $values[$key] = $dao->$key;
904 * Wrapper for _civicrm_object_to_array when api supports unique fields
906 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
907 return _civicrm_api3_object_to_array($dao, $values, TRUE);
912 * @param array $params
913 * @param array $values
914 * @param string $extends entity that this custom field extends (e.g. contribution, event, contact)
915 * @param string $entityId ID of entity per $extends
917 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
918 $values['custom'] = array();
919 foreach ($params as $key => $value) {
920 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
921 if ($customFieldID && (!IS_NULL($value))) {
922 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
923 $value, $extends, $customValueID, $entityId, FALSE, FALSE
931 * This function ensures that we have the right input parameters
933 * This function is only called when $dao is passed into verify_mandatory.
934 * The practice of passing $dao into verify_mandatory turned out to be
935 * unsatisfactory as the required fields @ the dao level is so diffent to the abstract
936 * api level. Hence the intention is to remove this function
937 * & the associated param from viery_mandatory
939 * @param array $params Associative array of property name/value
940 * pairs to insert in new history.
942 * @param bool $return
944 * @daoName string DAO to check params agains
946 * @return bool should the missing fields be returned as an array (core error created as default)
948 * @return bool true if all fields present, depending on $result a core error is created of an array of missing fields is returned
951 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
952 //@deprecated - see notes
953 if (isset($params['extends'])) {
954 if (($params['extends'] == 'Activity' ||
955 $params['extends'] == 'Phonecall' ||
956 $params['extends'] == 'Meeting' ||
957 $params['extends'] == 'Group' ||
958 $params['extends'] == 'Contribution'
960 ($params['style'] == 'Tab')
962 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
966 $dao = new $daoName();
967 $fields = $dao->fields();
970 foreach ($fields as $k => $v) {
971 if ($v['name'] == 'id') {
975 if (!empty($v['required'])) {
976 // 0 is a valid input for numbers, CRM-8122
977 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
983 if (!empty($missing)) {
984 if (!empty($return)) {
988 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
996 * Check permissions for a given API call.
998 * @param $entity string API entity being accessed
999 * @param $action string API action being performed
1000 * @param $params array params of the API call
1001 * @param $throw deprecated bool whether to throw exception instead of returning false
1004 * @return bool whether the current API user has the permission to make the call
1006 function _civicrm_api3_api_check_permission($entity, $action, &$params, $throw = TRUE) {
1007 // return early unless we’re told explicitly to do the permission check
1008 if (empty($params['check_permissions']) or $params['check_permissions'] == FALSE) {
1012 require_once 'CRM/Core/DAO/permissions.php';
1013 $permissions = _civicrm_api3_permissions($entity, $action, $params);
1015 // $params might’ve been reset by the alterAPIPermissions() hook
1016 if (isset($params['check_permissions']) and $params['check_permissions'] == FALSE) {
1020 if (!CRM_Core_Permission
::check($permissions)) {
1022 if(is_array($permissions)) {
1023 $permissions = implode(' and ', $permissions);
1025 throw new Exception("API permission check failed for $entity/$action call; insufficient permission: require $permissions");
1028 //@todo remove this - this is an internal api function called with $throw set to TRUE. It is only called with false
1029 // in tests & that should be tidied up
1038 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this
1040 * @param string $bao_name name of BAO
1041 * @param array $params params from api
1042 * @param bool $returnAsSuccess return in api success format
1043 * @param string $entity
1047 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1048 $bao = new $bao_name();
1049 _civicrm_api3_dao_set_filter($bao, $params, TRUE, $entity);
1050 if ($returnAsSuccess) {
1051 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1054 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity);
1059 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this
1060 * @param string $bao_name Name of BAO Class
1061 * @param array $params parameters passed into the api call
1062 * @param string $entity Entity - pass in if entity is non-standard & required $ids array
1065 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1067 $args = array(&$params);
1068 if (!empty($entity)) {
1069 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1073 if (method_exists($bao_name, 'create')) {
1075 $fct_name = $bao_name . '::' . $fct;
1076 $bao = call_user_func_array(array($bao_name, $fct), $args);
1078 elseif (method_exists($bao_name, 'add')) {
1080 $fct_name = $bao_name . '::' . $fct;
1081 $bao = call_user_func_array(array($bao_name, $fct), $args);
1084 $fct_name = '_civicrm_api3_basic_create_fallback';
1085 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1088 if (is_null($bao)) {
1089 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1091 elseif (is_a($bao, 'CRM_Core_Error')) {
1092 //some wierd circular thing means the error takes itself as an argument
1093 $msg = $bao->getMessages($bao);
1094 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1095 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1096 // so we need to reset the error object here to avoid getting concatenated errors
1097 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1098 CRM_Core_Error
::singleton()->reset();
1099 throw new API_Exception($msg);
1103 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1104 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1109 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1111 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1112 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1114 * @param string $bao_name
1115 * @param array $params
1117 * @throws API_Exception
1118 * @return CRM_Core_DAO|NULL an instance of the BAO
1120 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1121 $dao_name = get_parent_class($bao_name);
1122 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1123 $dao_name = $bao_name;
1125 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1126 if (empty($entityName)) {
1127 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1128 'class_name' => $bao_name,
1131 $hook = empty($params['id']) ?
'create' : 'edit';
1133 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1134 $instance = new $dao_name();
1135 $instance->copyValues($params);
1137 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1143 * Function to do a 'standard' api del - when the api is only doing a $bao::del then use this
1144 * if api::del doesn't exist it will try DAO delete method
1146 function _civicrm_api3_basic_delete($bao_name, &$params) {
1148 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1149 $args = array(&$params['id']);
1150 if (method_exists($bao_name, 'del')) {
1151 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1152 if ($bao !== FALSE) {
1153 return civicrm_api3_create_success(TRUE);
1155 throw new API_Exception('Could not delete entity id ' . $params['id']);
1157 elseif (method_exists($bao_name, 'delete')) {
1158 $dao = new $bao_name();
1159 $dao->id
= $params['id'];
1161 while ($dao->fetch()) {
1163 return civicrm_api3_create_success();
1167 throw new API_Exception('Could not delete entity id ' . $params['id']);
1171 throw new API_Exception('no delete method found');
1175 * Get custom data for the given entity & Add it to the returnArray as 'custom_123' = 'custom string' AND 'custom_123_1' = 'custom string'
1176 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1178 * @param array $returnArray - array to append custom data too - generally $result[4] where 4 is the entity id.
1179 * @param string $entity e.g membership, event
1181 * @param int $groupID - per CRM_Core_BAO_CustomGroup::getTree
1182 * @param int $subType e.g. membership_type_id where custom data doesn't apply to all membership types
1183 * @param string $subName - Subtype of entity
1185 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1186 $groupTree = &CRM_Core_BAO_CustomGroup
::getTree($entity,
1187 CRM_Core_DAO
::$_nullObject,
1193 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1194 $customValues = array();
1195 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1196 if (!empty($customValues)) {
1197 foreach ($customValues as $key => $val) {
1198 if (strstr($key, '_id')) {
1199 $idkey = substr($key, 0, -3);
1200 $returnArray['custom_' . (CRM_Core_BAO_CustomField
::getKeyID($idkey) . "_id")] = $val;
1201 $returnArray[$key] = $val;
1204 // per standard - return custom_fieldID
1205 $returnArray['custom_' . (CRM_Core_BAO_CustomField
::getKeyID($key))] = $val;
1207 //not standard - but some api did this so guess we should keep - cheap as chips
1208 $returnArray[$key] = $val;
1215 * Validate fields being passed into API. This function relies on the getFields function working accurately
1216 * for the given API. If error mode is set to TRUE then it will also check
1219 * As of writing only date was implemented.
1220 * @param string $entity
1221 * @param string $action
1222 * @param array $params -
1223 * @param array $fields response from getfields all variables are the same as per civicrm_api
1224 * @param bool $errorMode errorMode do intensive post fail checks?
1227 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = False) {
1228 $fields = array_intersect_key($fields, $params);
1229 foreach ($fields as $fieldName => $fieldInfo) {
1230 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1231 case CRM_Utils_Type
::T_INT
:
1232 //field is of type integer
1233 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1238 //field is of type date or datetime
1239 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1243 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1246 case CRM_Utils_Type
::T_STRING
:
1247 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1250 case CRM_Utils_Type
::T_MONEY
:
1251 if (!CRM_Utils_Rule
::money($params[$fieldName]) && !empty($params[$fieldName])) {
1252 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1256 // intensive checks - usually only called after DB level fail
1257 if (!empty($errorMode) && strtolower($action) == 'create') {
1258 if (!empty($fieldInfo['FKClassName'])) {
1259 if (!empty($params[$fieldName])) {
1260 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1262 elseif (!empty($fieldInfo['required'])) {
1263 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1266 if (!empty($fieldInfo['api.unique'])) {
1267 $params['entity'] = $entity;
1268 _civicrm_api3_validate_uniquekey($params, $fieldName, $fieldInfo);
1275 * Validate date fields being passed into API.
1276 * It currently converts both unique fields and DB field names to a mysql date.
1277 * @todo - probably the unique field handling & the if exists handling is now done before this
1278 * function is reached in the wrapper - can reduce this code down to assume we
1279 * are only checking the passed in field
1281 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1282 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1284 * @param array $params params from civicrm_api
1285 * @param string $fieldName uniquename of field being checked
1288 * @internal param array $fieldinfo array of fields from getfields function
1290 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1291 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1292 if (!empty($params[$fieldInfo['name']])) {
1293 //accept 'whatever strtotime accepts
1294 if (strtotime($params[$fieldInfo['name']]) === FALSE) {
1295 throw new Exception($fieldInfo['name'] . " is not a valid date: " . $params[$fieldInfo['name']]);
1297 $params[$fieldInfo['name']] = CRM_Utils_Date
::processDate($params[$fieldInfo['name']]);
1299 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($params[$fieldName])) {
1300 //If the unique field name differs from the db name & is set handle it here
1301 if (strtotime($params[$fieldName]) === FALSE) {
1302 throw new Exception($fieldName . " is not a valid date: " . $params[$fieldName]);
1304 $params[$fieldName] = CRM_Utils_Date
::processDate($params[$fieldName]);
1309 * Validate foreign constraint fields being passed into API.
1311 * @param array $params params from civicrm_api
1312 * @param string $fieldName uniquename of field being checked
1315 * @internal param array $fieldinfo array of fields from getfields function
1317 function _civicrm_api3_validate_constraint(&$params, &$fieldName, &$fieldInfo) {
1318 $dao = new $fieldInfo['FKClassName'];
1319 $dao->id
= $params[$fieldName];
1321 $dao->selectAdd('id');
1322 if (!$dao->find()) {
1323 throw new Exception("$fieldName is not valid : " . $params[$fieldName]);
1328 * Validate foreign constraint fields being passed into API.
1330 * @param array $params params from civicrm_api
1331 * @param string $fieldName uniquename of field being checked
1334 * @internal param array $fieldinfo array of fields from getfields function
1336 function _civicrm_api3_validate_uniquekey(&$params, &$fieldName, &$fieldInfo) {
1337 $existing = civicrm_api($params['entity'], 'get', array(
1338 'version' => $params['version'],
1339 $fieldName => $params[$fieldName],
1341 // an entry already exists for this unique field
1342 if ($existing['count'] == 1) {
1343 // question - could this ever be a security issue?
1344 throw new Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1349 * Generic implementation of the "replace" action.
1351 * Replace the old set of entities (matching some given keys) with a new set of
1352 * entities (matching the same keys).
1354 * Note: This will verify that 'values' is present, but it does not directly verify
1355 * any other parameters.
1357 * @param string $entity entity name
1358 * @param array $params params from civicrm_api, including:
1359 * - 'values': an array of records to save
1360 * - all other items: keys which identify new/pre-existing records
1363 function _civicrm_api3_generic_replace($entity, $params) {
1365 $transaction = new CRM_Core_Transaction();
1367 if (!is_array($params['values'])) {
1368 throw new Exception("Mandatory key(s) missing from params array: values");
1371 // Extract the keys -- somewhat scary, don't think too hard about it
1372 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1374 // Lookup pre-existing records
1375 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1376 if (civicrm_error($preexisting)) {
1377 $transaction->rollback();
1378 return $preexisting;
1381 // Save the new/updated records
1383 foreach ($params['values'] as $replacement) {
1384 // Sugar: Don't force clients to duplicate the 'key' data
1385 $replacement = array_merge($baseParams, $replacement);
1386 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1387 $create = civicrm_api($entity, $action, $replacement);
1388 if (civicrm_error($create)) {
1389 $transaction->rollback();
1392 foreach ($create['values'] as $entity_id => $entity_value) {
1393 $creates[$entity_id] = $entity_value;
1397 // Remove stale records
1398 $staleIDs = array_diff(
1399 array_keys($preexisting['values']),
1400 array_keys($creates)
1402 foreach ($staleIDs as $staleID) {
1403 $delete = civicrm_api($entity, 'delete', array(
1404 'version' => $params['version'],
1407 if (civicrm_error($delete)) {
1408 $transaction->rollback();
1413 return civicrm_api3_create_success($creates, $params);
1415 catch(PEAR_Exception
$e) {
1416 $transaction->rollback();
1417 return civicrm_api3_create_error($e->getMessage());
1419 catch(Exception
$e) {
1420 $transaction->rollback();
1421 return civicrm_api3_create_error($e->getMessage());
1430 function _civicrm_api3_generic_replace_base_params($params) {
1431 $baseParams = $params;
1432 unset($baseParams['values']);
1433 unset($baseParams['sequential']);
1434 unset($baseParams['options']);
1439 * returns fields allowable by api
1441 * @param $entity string Entity to query
1442 * @param bool $unique index by unique fields?
1443 * @param array $params
1447 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1448 $unsetIfEmpty = array('dataPattern', 'headerPattern', 'default', 'export', 'import');
1449 $dao = _civicrm_api3_get_DAO($entity);
1454 $fields = $d->fields();
1455 // replace uniqueNames by the normal names as the key
1456 if (empty($unique)) {
1457 foreach ($fields as $name => & $field) {
1458 //getting rid of unused attributes
1459 foreach ($unsetIfEmpty as $attr) {
1460 if (empty($field[$attr])) {
1461 unset($field[$attr]);
1464 if ($name == $field['name']) {
1467 if (array_key_exists($field['name'], $fields)) {
1468 $field['error'] = 'name conflict';
1469 // it should never happen, but better safe than sorry
1472 $fields[$field['name']] = $field;
1473 $fields[$field['name']]['uniqueName'] = $name;
1474 unset($fields[$name]);
1477 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1482 * Return an array of fields for a given entity - this is the same as the BAO function but
1483 * fields are prefixed with 'custom_' to represent api params
1485 function _civicrm_api_get_custom_fields($entity, &$params) {
1486 $customfields = array();
1487 $entity = _civicrm_api_get_camel_name($entity);
1488 if (strtolower($entity) == 'contact') {
1489 // Use sub-type if available, otherwise stick with 'Contact'
1490 $entity = CRM_Utils_Array
::value('contact_type', $params);
1492 $retrieveOnlyParent = FALSE;
1493 // we could / should probably test for other subtypes here - e.g. activity_type_id
1494 if($entity == 'Contact'){
1495 empty($params['contact_sub_type']);
1497 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1500 CRM_Utils_Array
::value('contact_sub_type', $params, FALSE),
1502 $retrieveOnlyParent,
1506 // find out if we have any requests to resolve options
1507 $getoptions = CRM_Utils_Array
::value('get_options', CRM_Utils_Array
::value('options',$params));
1508 if(!is_array($getoptions)){
1509 $getoptions = array($getoptions);
1512 foreach ($customfields as $key => $value) {
1513 // Regular fields have a 'name' property
1514 $value['name'] = 'custom_' . $key;
1515 $value['type'] = _getStandardTypeFromCustomDataType($value['data_type']);
1516 $customfields['custom_' . $key] = $value;
1517 if (in_array('custom_' . $key, $getoptions)) {
1518 $customfields['custom_' . $key]['options'] = CRM_Core_BAO_CustomOption
::valuesByID($key);
1520 unset($customfields[$key]);
1522 return $customfields;
1525 * Translate the custom field data_type attribute into a std 'type'
1527 function _getStandardTypeFromCustomDataType($dataType) {
1529 'String' => CRM_Utils_Type
::T_STRING
,
1530 'Int' => CRM_Utils_Type
::T_INT
,
1531 'Money' => CRM_Utils_Type
::T_MONEY
,
1532 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1533 'Float' => CRM_Utils_Type
::T_FLOAT
,
1534 'Date' => CRM_Utils_Type
::T_DATE
,
1535 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1536 'StateProvince' => CRM_Utils_Type
::T_INT
,
1537 'File' => CRM_Utils_Type
::T_STRING
,
1538 'Link' => CRM_Utils_Type
::T_STRING
,
1539 'ContactReference' => CRM_Utils_Type
::T_INT
,
1540 'Country' => CRM_Utils_Type
::T_INT
,
1542 return $mapping[$dataType];
1545 * Return array of defaults for the given API (function is a wrapper on getfields)
1547 function _civicrm_api3_getdefaults($apiRequest, $fields) {
1548 $defaults = array();
1550 foreach ($fields as $field => $values) {
1551 if (isset($values['api.default'])) {
1552 $defaults[$field] = $values['api.default'];
1559 * Return array of defaults for the given API (function is a wrapper on getfields)
1561 function _civicrm_api3_getrequired($apiRequest, $fields) {
1562 $required = array('version');
1564 foreach ($fields as $field => $values) {
1565 if (!empty($values['api.required'])) {
1566 $required[] = $field;
1573 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't
1574 * If multiple aliases the last takes precedence
1576 * Function also swaps unique fields for non-unique fields & vice versa.
1578 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1579 foreach ($fields as $field => $values) {
1580 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1581 if (!empty($values['api.aliases'])) {
1582 // if aliased field is not set we try to use field alias
1583 if (!isset($apiRequest['params'][$field])) {
1584 foreach ($values['api.aliases'] as $alias) {
1585 if (isset($apiRequest['params'][$alias])) {
1586 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1588 //unset original field nb - need to be careful with this as it may bring inconsistencies
1589 // out of the woodwork but will be implementing only as _spec function extended
1590 unset($apiRequest['params'][$alias]);
1594 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
1595 && isset($apiRequest['params'][$values['name']])
1597 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1598 // note that it would make sense to unset the original field here but tests need to be in place first
1600 if (!isset($apiRequest['params'][$field])
1602 && $field != $uniqueName
1603 && array_key_exists($uniqueName, $apiRequest['params'])
1606 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1607 // note that it would make sense to unset the original field here but tests need to be in place first
1614 * Validate integer fields being passed into API.
1615 * It currently converts the incoming value 'user_contact_id' into the id of the currenty logged in user
1617 * @param array $params params from civicrm_api
1618 * @param string $fieldName uniquename of field being checked
1621 * @throws API_Exception
1622 * @internal param array $fieldinfo array of fields from getfields function
1624 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1625 //if fieldname exists in params
1626 if (!empty($params[$fieldName])) {
1627 // if value = 'user_contact_id' (or similar), replace value with contact id
1628 if (!is_numeric($params[$fieldName]) && is_scalar($params[$fieldName])) {
1629 $realContactId = _civicrm_api3_resolve_contactID($params[$fieldName]);
1630 if ('unknown-user' === $realContactId) {
1631 throw new API_Exception("\"$fieldName\" \"{$params[$fieldName]}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName,"type"=>"integer"));
1632 } elseif (is_numeric($realContactId)) {
1633 $params[$fieldName] = $realContactId;
1636 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1637 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1640 // After swapping options, ensure we have an integer(s)
1641 foreach ((array) ($params[$fieldName]) as $value) {
1642 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1643 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1647 // Check our field length
1648 if(is_string($params[$fieldName]) && !empty($fieldInfo['maxlength']) && strlen($params[$fieldName]) > $fieldInfo['maxlength']
1650 throw new API_Exception( $params[$fieldName] . " is " . strlen($params[$fieldName]) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1651 2100, array('field' => $fieldName, "max_length"=>$fieldInfo['maxlength'])
1658 * Determine a contact ID using a string expression
1660 * @param string $contactIdExpr e.g. "user_contact_id" or "@user:username"
1661 * @return int|NULL|'unknown-user'
1663 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1664 //if value = 'user_contact_id' replace value with logged in user id
1665 if ($contactIdExpr == "user_contact_id") {
1666 $session = &CRM_Core_Session
::singleton();
1667 if (!is_numeric($session->get('userID'))) {
1670 return $session->get('userID');
1671 } elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1672 $config = CRM_Core_Config
::singleton();
1674 $ufID = $config->userSystem
->getUfId($matches[1]);
1676 return 'unknown-user';
1679 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
1681 return 'unknown-user';
1690 * Validate html (check for scripting attack)
1695 * @throws API_Exception
1697 function _civicrm_api3_validate_html(&$params, &$fieldName, &$fieldInfo) {
1698 if ($value = CRM_Utils_Array
::value($fieldName, $params)) {
1699 if (!CRM_Utils_Rule
::xssString($value)) {
1700 throw new API_Exception('Illegal characters in input (potential scripting attack)', array("field"=>$fieldName,"error_code"=>"xss"));
1706 * Validate string fields being passed into API.
1707 * @param array $params params from civicrm_api
1708 * @param string $fieldName uniquename of field being checked
1711 * @throws API_Exception
1713 * @internal param array $fieldinfo array of fields from getfields function
1715 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
1716 // If fieldname exists in params
1717 $value = CRM_Utils_Array
::value($fieldName, $params, '');
1718 if(!is_array($value)){
1719 $value = (string) $value;
1722 //@todo what do we do about passed in arrays. For many of these fields
1723 // the missing piece of functionality is separating them to a separated string
1724 // & many save incorrectly. But can we change them wholesale?
1727 if (!CRM_Utils_Rule
::xssString($value)) {
1728 throw new Exception('Illegal characters in input (potential scripting attack)');
1730 if ($fieldName == 'currency') {
1731 if (!CRM_Utils_Rule
::currencyCode($value)) {
1732 throw new Exception("Currency not a valid code: $value");
1735 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1736 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1738 // Check our field length
1739 elseif (is_string($value) && !empty($fieldInfo['maxlength']) && strlen($value) > $fieldInfo['maxlength']) {
1740 throw new API_Exception("Value for $fieldName is " . strlen($value) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
1741 2100, array('field' => $fieldName)
1748 * Validate & swap out any pseudoconstants / options
1750 * @param $params: api parameters
1751 * @param $entity: api entity name
1752 * @param $fieldName: field name used in api call (not necessarily the canonical name)
1753 * @param $fieldInfo: getfields meta-data
1755 function _civicrm_api3_api_match_pseudoconstant(&$params, $entity, $fieldName, $fieldInfo) {
1756 $options = CRM_Utils_Array
::value('options', $fieldInfo);
1758 if(strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
1759 // we need to get the options from the entity the field relates to
1760 $entity = $fieldInfo['entity'];
1762 $options = civicrm_api($entity, 'getoptions', array('version' => 3, 'field' => $fieldInfo['name'], 'context' => 'validate'));
1763 $options = CRM_Utils_Array
::value('values', $options, array());
1766 // If passed a value-separated string, explode to an array, then re-implode after matching values
1768 if (is_string($params[$fieldName]) && strpos($params[$fieldName], CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
1769 $params[$fieldName] = CRM_Utils_Array
::explodePadded($params[$fieldName]);
1772 // If passed multiple options, validate each
1773 if (is_array($params[$fieldName])) {
1774 foreach ($params[$fieldName] as &$value) {
1775 if (!is_array($value)) {
1776 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
1779 // TODO: unwrap the call to implodePadded from the conditional and do it always
1780 // need to verify that this is safe and doesn't break anything though.
1781 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
1783 CRM_Utils_Array
::implodePadded($params[$fieldName]);
1787 _civicrm_api3_api_match_pseudoconstant_value($params[$fieldName], $options, $fieldName);
1792 * Validate & swap a single option value for a field
1794 * @param $value: field value
1795 * @param $options: array of options for this field
1796 * @param $fieldName: field name used in api call (not necessarily the canonical name)
1797 * @throws API_Exception
1799 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
1800 // If option is a key, no need to translate
1801 if (array_key_exists($value, $options)) {
1805 // Translate value into key
1806 $newValue = array_search($value, $options);
1807 if ($newValue !== FALSE) {
1811 // Case-insensitive matching
1812 $newValue = strtolower($value);
1813 $options = array_map("strtolower", $options);
1814 $newValue = array_search($newValue, $options);
1815 if ($newValue === FALSE) {
1816 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
1822 * Returns the canonical name of a field
1823 * @param $entity: api entity name (string should already be standardized - no camelCase)
1824 * @param $fieldName: any variation of a field's name (name, unique_name, api.alias)
1826 * @return (string|bool) fieldName or FALSE if the field does not exist
1828 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
1829 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
1832 if ($fieldName == "{$entity}_id") {
1835 $result = civicrm_api($entity, 'getfields', array(
1837 'action' => 'create',
1839 $meta = $result['values'];
1840 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
1841 $fieldName = $fieldName . '_id';
1843 if (isset($meta[$fieldName])) {
1844 return $meta[$fieldName]['name'];
1846 foreach ($meta as $info) {
1847 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
1848 return $info['name'];
1850 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
1851 return $info['name'];