3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 * File for CiviCRM APIv3 utilitity functions
31 * @package CiviCRM_APIv3
32 * @subpackage API_utils
34 * @copyright CiviCRM LLC (c) 2004-2014
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 if(file_exists("api/v3/$name.php")) {
325 include_once "api/v3/$name.php";
327 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
328 if (function_exists($daoFn)) {
336 * Function to return the DAO of the function or Entity
337 * @param String $name is either a function of the api (civicrm_{entity}_create or the entity name
338 * return the DAO name to manipulate this function
339 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
342 function _civicrm_api3_get_BAO($name) {
343 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
344 if ($name == 'PrintLabel') {
345 return 'CRM_Badge_BAO_Layout';
347 $dao = _civicrm_api3_get_DAO($name);
351 $bao = str_replace("DAO", "BAO", $dao);
352 $file = strtr($bao, '_', '/') . '.php';
353 // Check if this entity actually has a BAO. Fall back on the DAO if not.
354 return stream_resolve_include_path($file) ?
$bao : $dao;
358 * Recursive function to explode value-separated strings into arrays
361 function _civicrm_api3_separate_values(&$values) {
362 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
363 foreach ($values as $key => & $value) {
364 if (is_array($value)) {
365 _civicrm_api3_separate_values($value);
367 elseif (is_string($value)) {
368 if($key == 'case_type_id'){// this is to honor the way case API was originally written
369 $value = trim(str_replace($sp, ',', $value), ',');
371 elseif (strpos($value, $sp) !== FALSE) {
372 $value = explode($sp, trim($value, $sp));
379 * This is a legacy wrapper for api_store_values which will check the suitable fields using getfields
380 * rather than DAO->fields
382 * Getfields has handling for how to deal with uniquenames which dao->fields doesn't
384 * Note this is used by BAO type create functions - eg. contribution
385 * @param string $entity
386 * @param array $params
387 * @param array $values
389 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values){
390 $fields = civicrm_api($entity,'getfields', array('version' => 3,'action' => 'create'));
391 $fields = $fields['values'];
392 _civicrm_api3_store_values($fields, $params, $values);
396 * @param array $fields
397 * @param array $params
398 * @param array $values
400 * @return Bool $valueFound
402 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
405 $keys = array_intersect_key($params, $fields);
406 foreach ($keys as $name => $value) {
407 if ($name !== 'id') {
408 $values[$name] = $value;
416 * The API supports 2 types of get requestion. The more complex uses the BAO query object.
417 * This is a generic function for those functions that call it
419 * At the moment only called by contact we should extend to contribution &
420 * others that use the query object. Note that this function passes permission information in.
423 * * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
426 * @param array $params as passed into api get or getcount function
427 * @param array $additional_options
428 * @param bool $getCount are we just after the count
431 * @internal param array $options array of options (so we can modify the filter)
433 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL){
435 // Convert id to e.g. contact_id
436 if (empty($params[$entity . '_id']) && isset($params['id'])) {
437 $params[$entity . '_id'] = $params['id'];
439 unset($params['id']);
441 $options = _civicrm_api3_get_options_from_params($params, TRUE);
443 $inputParams = array_merge(
444 CRM_Utils_Array
::value('input_params', $options, array()),
445 CRM_Utils_Array
::value('input_params', $additional_options, array())
447 $returnProperties = array_merge(
448 CRM_Utils_Array
::value('return', $options, array()),
449 CRM_Utils_Array
::value('return', $additional_options, array())
451 if(empty($returnProperties)){
452 $returnProperties = NULL;
454 if(!empty($params['check_permissions'])){
455 // we will filter query object against getfields
456 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
457 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
458 $fields['values'][$entity . '_id'] = array();
459 $varsToFilter = array('returnProperties', 'inputParams');
460 foreach ($varsToFilter as $varToFilter){
461 if(!is_array($
$varToFilter)){
464 //I was going to throw an exception rather than silently filter out - but
465 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
466 //so we are silently ignoring parts of their request
467 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
468 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
471 $options = array_merge($options,$additional_options);
472 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
473 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
474 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
475 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
479 $returnProperties = NULL;
482 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
483 foreach ($newParams as &$newParam) {
484 if($newParam[1] == '=' && is_array($newParam[2])) {
485 // we may be looking at an attempt to use the 'IN' style syntax
486 // @todo at time of writing only 'IN' & 'NOT IN' are supported for the array style syntax
487 $sqlFilter = CRM_Core_DAO
::createSqlFilter($newParam[0], $params[$newParam[0]], 'String', NULL, TRUE);
489 $newParam[1] = key($newParam[2]);
490 $newParam[2] = $sqlFilter;
495 $skipPermissions = !empty($params['check_permissions']) ?
0 :1;
497 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
508 if ($getCount) { // only return the count of contacts
516 * get dao query object based on input params
517 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
520 * @param array $params
521 * @param string $mode
522 * @param string $entity
523 * @return CRM_Core_DAO query object
525 function _civicrm_api3_get_query_object($params, $mode, $entity) {
526 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
527 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
528 $offset = CRM_Utils_Array
::value('offset', $options);
529 $rowCount = CRM_Utils_Array
::value('limit', $options);
530 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
531 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
532 if (empty($returnProperties)) {
533 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
536 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
537 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
540 list($select, $from, $where, $having) = $query->query();
542 $sql = "$select $from $where $having";
545 $sql .= " ORDER BY $sort ";
547 if(!empty($rowCount)) {
548 $sql .= " LIMIT $offset, $rowCount ";
550 $dao = CRM_Core_DAO
::executeQuery($sql);
551 return array($dao, $query);
555 * Function transfers the filters being passed into the DAO onto the params object
557 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $entity) {
558 $entity = substr($dao->__table
, 8);
560 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
562 $fields = array_intersect(array_keys($allfields), array_keys($params));
563 if (isset($params[$entity . "_id"])) {
564 //if entity_id is set then treat it as ID (will be overridden by id if set)
565 $dao->id
= $params[$entity . "_id"];
568 $options = _civicrm_api3_get_options_from_params($params);
569 //apply options like sort
570 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
572 //accept filters like filter.activity_date_time_high
573 // std is now 'filters' => ..
574 if (strstr(implode(',', array_keys($params)), 'filter')) {
575 if (isset($params['filters']) && is_array($params['filters'])) {
576 foreach ($params['filters'] as $paramkey => $paramvalue) {
577 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
581 foreach ($params as $paramkey => $paramvalue) {
582 if (strstr($paramkey, 'filter')) {
583 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
588 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
589 // support for other syntaxes is discussed in ticket but being put off for now
590 $acceptedSQLOperators = array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN');
595 foreach ($fields as $field) {
596 if (is_array($params[$field])) {
597 //get the actual fieldname from db
598 $fieldName = $allfields[$field]['name'];
599 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
601 $dao->whereAdd($where);
606 $daoFieldName = $allfields[$field]['name'];
607 if (empty($daoFieldName)) {
608 throw new API_Exception("Failed to determine field name for \"$field\"");
610 $dao->{$daoFieldName} = $params[$field];
613 $dao->$field = $params[$field];
617 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
619 $options['return']['id'] = TRUE;// ensure 'id' is included
620 $allfields = _civicrm_api3_get_unique_name_array($dao);
621 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
622 foreach ($returnMatched as $returnValue) {
623 $dao->selectAdd($returnValue);
626 $unmatchedFields = array_diff(// not already matched on the field names
627 array_keys($options['return']),
631 $returnUniqueMatched = array_intersect(
633 array_flip($allfields)// but a match for the field keys
635 foreach ($returnUniqueMatched as $uniqueVal){
636 $dao->selectAdd($allfields[$uniqueVal]);
639 $dao->setApiFilter($params);
643 * Apply filters (e.g. high, low) to DAO object (prior to find)
644 * @param string $filterField field name of filter
645 * @param string $filterValue field value of filter
646 * @param object $dao DAO object
648 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
649 if (strstr($filterField, 'high')) {
650 $fieldName = substr($filterField, 0, -5);
651 $dao->whereAdd("($fieldName <= $filterValue )");
653 if (strstr($filterField, 'low')) {
654 $fieldName = substr($filterField, 0, -4);
655 $dao->whereAdd("($fieldName >= $filterValue )");
657 if($filterField == 'is_current' && $filterValue == 1){
658 $todayStart = date('Ymd000000', strtotime('now'));
659 $todayEnd = date('Ymd235959', strtotime('now'));
660 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
661 if(property_exists($dao, 'is_active')){
662 $dao->whereAdd('is_active = 1');
668 * Get sort, limit etc options from the params - supporting old & new formats.
669 * get returnproperties for legacy
671 * @param array $params params array as passed into civicrm_api
672 * @param bool $queryObject - is this supporting a queryobject api (e.g contact) - if so we support more options
673 * for legacy report & return a unique fields array
675 * @param string $entity
676 * @param string $action
678 * @return array $options options extracted from params
680 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
682 $sort = CRM_Utils_Array
::value('sort', $params, 0);
683 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
684 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
686 $offset = CRM_Utils_Array
::value('offset', $params, 0);
687 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
688 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
689 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
691 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
692 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
693 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
695 if (is_array(CRM_Utils_Array
::value('options', $params))) {
696 // is count is set by generic getcount not user
697 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
698 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
699 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
700 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
703 $returnProperties = array();
704 // handle the format return =sort_name,display_name...
705 if (array_key_exists('return', $params)) {
706 if (is_array($params['return'])) {
707 $returnProperties = array_fill_keys($params['return'], 1);
710 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
711 $returnProperties = array_fill_keys($returnProperties, 1);
714 if ($entity && $action =='get') {
715 if (!empty($returnProperties['id'])) {
716 $returnProperties[$entity . '_id'] = 1;
717 unset($returnProperties['id']);
719 switch (trim(strtolower($sort))){
723 $sort = str_replace('id', $entity . '_id',$sort);
728 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
729 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
730 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
731 'is_count' => $is_count,
732 'return' => !empty($returnProperties) ?
$returnProperties : NULL,
735 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
736 throw new API_Exception('invalid string in sort options');
742 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
743 // if the queryobject is being used this should be used
744 $inputParams = array();
745 $legacyreturnProperties = array();
747 'sort', 'offset', 'rowCount', 'options','return',
749 foreach ($params as $n => $v) {
750 if (substr($n, 0, 7) == 'return.') {
751 $legacyreturnProperties[substr($n, 7)] = $v;
753 elseif ($n == 'id') {
754 $inputParams[$entity. '_id'] = $v;
756 elseif (in_array($n, $otherVars)) {}
758 $inputParams[$n] = $v;
759 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
760 throw new API_Exception('invalid string');
764 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
765 $options['input_params'] = $inputParams;
770 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find)
772 * @param array $params params array as passed into civicrm_api
773 * @param object $dao DAO object
776 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
778 $options = _civicrm_api3_get_options_from_params($params,FALSE,$entity);
779 if(!$options['is_count']) {
780 if(!empty($options['limit'])) {
781 $dao->limit((int)$options['offset'], (int)$options['limit']);
783 if (!empty($options['sort'])) {
784 $dao->orderBy($options['sort']);
790 * build fields array. This is the array of fields as it relates to the given DAO
791 * returns unique fields as keys by default but if set but can return by DB fields
793 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
794 $fields = $bao->fields();
796 if (empty($fields['id'])){
797 $entity = _civicrm_api_get_entity_name_from_dao($bao);
798 $fields['id'] = $fields[$entity . '_id'];
799 unset($fields[$entity . '_id']);
804 foreach ($fields as $field) {
805 $dbFields[$field['name']] = $field;
811 * build fields array. This is the array of fields as it relates to the given DAO
812 * returns unique fields as keys by default but if set but can return by DB fields
814 function _civicrm_api3_get_unique_name_array(&$bao) {
815 $fields = $bao->fields();
816 foreach ($fields as $field => $values) {
817 $uniqueFields[$field] = CRM_Utils_Array
::value('name',$values, $field);
819 return $uniqueFields;
823 * Converts an DAO object to an array
825 * @param object $dao (reference )object to convert
826 * @param null $params
827 * @param bool $uniqueFields
828 * @param string $entity
832 * @params array of arrays (key = id) of array of fields
837 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
839 if(isset($params['options']) && !empty($params['options']['is_count'])) {
840 return $dao->count();
845 if ($autoFind && !$dao->find()) {
849 if(isset($dao->count
)) {
852 //if custom fields are required we will endeavour to set them . NB passing $entity in might be a bit clunky / unrequired
853 if (!empty($entity) && !empty($params['return']) && is_array($params['return'])) {
854 foreach ($params['return'] as $return) {
855 if (substr($return, 0, 6) == 'custom') {
862 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
864 while ($dao->fetch()) {
866 foreach ($fields as $key) {
867 if (array_key_exists($key, $dao)) {
868 // not sure on that one
869 if ($dao->$key !== NULL) {
870 $tmp[$key] = $dao->$key;
874 $result[$dao->id
] = $tmp;
875 if (!empty($custom)) {
876 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
885 * Converts an object to an array
887 * @param object $dao (reference) object to convert
888 * @param array $values (reference) array
889 * @param array|bool $uniqueFields
895 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
897 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
898 foreach ($fields as $key => $value) {
899 if (array_key_exists($key, $dao)) {
900 $values[$key] = $dao->$key;
906 * Wrapper for _civicrm_object_to_array when api supports unique fields
908 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
909 return _civicrm_api3_object_to_array($dao, $values, TRUE);
914 * @param array $params
915 * @param array $values
916 * @param string $extends entity that this custom field extends (e.g. contribution, event, contact)
917 * @param string $entityId ID of entity per $extends
919 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
920 $values['custom'] = array();
921 foreach ($params as $key => $value) {
922 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
923 if ($customFieldID && (!IS_NULL($value))) {
924 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
925 $value, $extends, $customValueID, $entityId, FALSE, FALSE
933 * This function ensures that we have the right input parameters
935 * This function is only called when $dao is passed into verify_mandatory.
936 * The practice of passing $dao into verify_mandatory turned out to be
937 * unsatisfactory as the required fields @ the dao level is so diffent to the abstract
938 * api level. Hence the intention is to remove this function
939 * & the associated param from viery_mandatory
941 * @param array $params Associative array of property name/value
942 * pairs to insert in new history.
944 * @param bool $return
946 * @daoName string DAO to check params agains
948 * @return bool should the missing fields be returned as an array (core error created as default)
950 * @return bool true if all fields present, depending on $result a core error is created of an array of missing fields is returned
953 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
954 //@deprecated - see notes
955 if (isset($params['extends'])) {
956 if (($params['extends'] == 'Activity' ||
957 $params['extends'] == 'Phonecall' ||
958 $params['extends'] == 'Meeting' ||
959 $params['extends'] == 'Group' ||
960 $params['extends'] == 'Contribution'
962 ($params['style'] == 'Tab')
964 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
968 $dao = new $daoName();
969 $fields = $dao->fields();
972 foreach ($fields as $k => $v) {
973 if ($v['name'] == 'id') {
977 if (!empty($v['required'])) {
978 // 0 is a valid input for numbers, CRM-8122
979 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
985 if (!empty($missing)) {
986 if (!empty($return)) {
990 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
998 * Check permissions for a given API call.
1000 * @param $entity string API entity being accessed
1001 * @param $action string API action being performed
1002 * @param $params array params of the API call
1003 * @param $throw deprecated bool whether to throw exception instead of returning false
1006 * @return bool whether the current API user has the permission to make the call
1008 function _civicrm_api3_api_check_permission($entity, $action, &$params, $throw = TRUE) {
1009 // return early unless we’re told explicitly to do the permission check
1010 if (empty($params['check_permissions']) or $params['check_permissions'] == FALSE) {
1014 require_once 'CRM/Core/DAO/permissions.php';
1015 $permissions = _civicrm_api3_permissions($entity, $action, $params);
1017 // $params might’ve been reset by the alterAPIPermissions() hook
1018 if (isset($params['check_permissions']) and $params['check_permissions'] == FALSE) {
1022 if (!CRM_Core_Permission
::check($permissions)) {
1024 if(is_array($permissions)) {
1025 $permissions = implode(' and ', $permissions);
1027 throw new Exception("API permission check failed for $entity/$action call; insufficient permission: require $permissions");
1030 //@todo remove this - this is an internal api function called with $throw set to TRUE. It is only called with false
1031 // in tests & that should be tidied up
1040 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this
1042 * @param string $bao_name name of BAO
1043 * @param array $params params from api
1044 * @param bool $returnAsSuccess return in api success format
1045 * @param string $entity
1049 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1050 $bao = new $bao_name();
1051 _civicrm_api3_dao_set_filter($bao, $params, TRUE, $entity);
1052 if ($returnAsSuccess) {
1053 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1056 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity);
1061 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this
1062 * @param string $bao_name Name of BAO Class
1063 * @param array $params parameters passed into the api call
1064 * @param string $entity Entity - pass in if entity is non-standard & required $ids array
1067 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1069 $args = array(&$params);
1070 if (!empty($entity)) {
1071 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1075 if (method_exists($bao_name, 'create')) {
1077 $fct_name = $bao_name . '::' . $fct;
1078 $bao = call_user_func_array(array($bao_name, $fct), $args);
1080 elseif (method_exists($bao_name, 'add')) {
1082 $fct_name = $bao_name . '::' . $fct;
1083 $bao = call_user_func_array(array($bao_name, $fct), $args);
1086 $fct_name = '_civicrm_api3_basic_create_fallback';
1087 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1090 if (is_null($bao)) {
1091 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1093 elseif (is_a($bao, 'CRM_Core_Error')) {
1094 //some wierd circular thing means the error takes itself as an argument
1095 $msg = $bao->getMessages($bao);
1096 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1097 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1098 // so we need to reset the error object here to avoid getting concatenated errors
1099 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1100 CRM_Core_Error
::singleton()->reset();
1101 throw new API_Exception($msg);
1105 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1106 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1111 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1113 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1114 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1116 * @param string $bao_name
1117 * @param array $params
1119 * @throws API_Exception
1120 * @return CRM_Core_DAO|NULL an instance of the BAO
1122 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1123 $dao_name = get_parent_class($bao_name);
1124 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1125 $dao_name = $bao_name;
1127 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1128 if (empty($entityName)) {
1129 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1130 'class_name' => $bao_name,
1133 $hook = empty($params['id']) ?
'create' : 'edit';
1135 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1136 $instance = new $dao_name();
1137 $instance->copyValues($params);
1139 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1145 * Function to do a 'standard' api del - when the api is only doing a $bao::del then use this
1146 * if api::del doesn't exist it will try DAO delete method
1148 function _civicrm_api3_basic_delete($bao_name, &$params) {
1150 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1151 $args = array(&$params['id']);
1152 if (method_exists($bao_name, 'del')) {
1153 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1154 if ($bao !== FALSE) {
1155 return civicrm_api3_create_success(TRUE);
1157 throw new API_Exception('Could not delete entity id ' . $params['id']);
1159 elseif (method_exists($bao_name, 'delete')) {
1160 $dao = new $bao_name();
1161 $dao->id
= $params['id'];
1163 while ($dao->fetch()) {
1165 return civicrm_api3_create_success();
1169 throw new API_Exception('Could not delete entity id ' . $params['id']);
1173 throw new API_Exception('no delete method found');
1177 * Get custom data for the given entity & Add it to the returnArray as 'custom_123' = 'custom string' AND 'custom_123_1' = 'custom string'
1178 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1180 * @param array $returnArray - array to append custom data too - generally $result[4] where 4 is the entity id.
1181 * @param string $entity e.g membership, event
1183 * @param int $groupID - per CRM_Core_BAO_CustomGroup::getTree
1184 * @param int $subType e.g. membership_type_id where custom data doesn't apply to all membership types
1185 * @param string $subName - Subtype of entity
1187 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1188 $groupTree = &CRM_Core_BAO_CustomGroup
::getTree($entity,
1189 CRM_Core_DAO
::$_nullObject,
1195 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1196 $customValues = array();
1197 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1198 if (!empty($customValues)) {
1199 foreach ($customValues as $key => $val) {
1200 if (strstr($key, '_id')) {
1201 $idkey = substr($key, 0, -3);
1202 $returnArray['custom_' . (CRM_Core_BAO_CustomField
::getKeyID($idkey) . "_id")] = $val;
1203 $returnArray[$key] = $val;
1206 // per standard - return custom_fieldID
1207 $returnArray['custom_' . (CRM_Core_BAO_CustomField
::getKeyID($key))] = $val;
1209 //not standard - but some api did this so guess we should keep - cheap as chips
1210 $returnArray[$key] = $val;
1217 * Validate fields being passed into API. This function relies on the getFields function working accurately
1218 * for the given API. If error mode is set to TRUE then it will also check
1221 * As of writing only date was implemented.
1222 * @param string $entity
1223 * @param string $action
1224 * @param array $params -
1225 * @param array $fields response from getfields all variables are the same as per civicrm_api
1226 * @param bool $errorMode errorMode do intensive post fail checks?
1229 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = False) {
1230 $fields = array_intersect_key($fields, $params);
1231 foreach ($fields as $fieldName => $fieldInfo) {
1232 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1233 case CRM_Utils_Type
::T_INT
:
1234 //field is of type integer
1235 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1240 //field is of type date or datetime
1241 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1245 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1248 case CRM_Utils_Type
::T_STRING
:
1249 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1252 case CRM_Utils_Type
::T_MONEY
:
1253 if (!CRM_Utils_Rule
::money($params[$fieldName]) && !empty($params[$fieldName])) {
1254 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1258 // intensive checks - usually only called after DB level fail
1259 if (!empty($errorMode) && strtolower($action) == 'create') {
1260 if (!empty($fieldInfo['FKClassName'])) {
1261 if (!empty($params[$fieldName])) {
1262 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1264 elseif (!empty($fieldInfo['required'])) {
1265 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1268 if (!empty($fieldInfo['api.unique'])) {
1269 $params['entity'] = $entity;
1270 _civicrm_api3_validate_uniquekey($params, $fieldName, $fieldInfo);
1277 * Validate date fields being passed into API.
1278 * It currently converts both unique fields and DB field names to a mysql date.
1279 * @todo - probably the unique field handling & the if exists handling is now done before this
1280 * function is reached in the wrapper - can reduce this code down to assume we
1281 * are only checking the passed in field
1283 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1284 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1286 * @param array $params params from civicrm_api
1287 * @param string $fieldName uniquename of field being checked
1290 * @internal param array $fieldinfo array of fields from getfields function
1292 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1293 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1294 if (!empty($params[$fieldInfo['name']])) {
1295 //accept 'whatever strtotime accepts
1296 if (strtotime($params[$fieldInfo['name']]) === FALSE) {
1297 throw new Exception($fieldInfo['name'] . " is not a valid date: " . $params[$fieldInfo['name']]);
1299 $params[$fieldInfo['name']] = CRM_Utils_Date
::processDate($params[$fieldInfo['name']]);
1301 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($params[$fieldName])) {
1302 //If the unique field name differs from the db name & is set handle it here
1303 if (strtotime($params[$fieldName]) === FALSE) {
1304 throw new Exception($fieldName . " is not a valid date: " . $params[$fieldName]);
1306 $params[$fieldName] = CRM_Utils_Date
::processDate($params[$fieldName]);
1311 * Validate foreign constraint fields being passed into API.
1313 * @param array $params params from civicrm_api
1314 * @param string $fieldName uniquename of field being checked
1317 * @internal param array $fieldinfo array of fields from getfields function
1319 function _civicrm_api3_validate_constraint(&$params, &$fieldName, &$fieldInfo) {
1320 $dao = new $fieldInfo['FKClassName'];
1321 $dao->id
= $params[$fieldName];
1323 $dao->selectAdd('id');
1324 if (!$dao->find()) {
1325 throw new Exception("$fieldName is not valid : " . $params[$fieldName]);
1330 * Validate foreign constraint fields being passed into API.
1332 * @param array $params params from civicrm_api
1333 * @param string $fieldName uniquename of field being checked
1336 * @internal param array $fieldinfo array of fields from getfields function
1338 function _civicrm_api3_validate_uniquekey(&$params, &$fieldName, &$fieldInfo) {
1339 $existing = civicrm_api($params['entity'], 'get', array(
1340 'version' => $params['version'],
1341 $fieldName => $params[$fieldName],
1343 // an entry already exists for this unique field
1344 if ($existing['count'] == 1) {
1345 // question - could this ever be a security issue?
1346 throw new Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1351 * Generic implementation of the "replace" action.
1353 * Replace the old set of entities (matching some given keys) with a new set of
1354 * entities (matching the same keys).
1356 * Note: This will verify that 'values' is present, but it does not directly verify
1357 * any other parameters.
1359 * @param string $entity entity name
1360 * @param array $params params from civicrm_api, including:
1361 * - 'values': an array of records to save
1362 * - all other items: keys which identify new/pre-existing records
1365 function _civicrm_api3_generic_replace($entity, $params) {
1367 $transaction = new CRM_Core_Transaction();
1369 if (!is_array($params['values'])) {
1370 throw new Exception("Mandatory key(s) missing from params array: values");
1373 // Extract the keys -- somewhat scary, don't think too hard about it
1374 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1376 // Lookup pre-existing records
1377 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1378 if (civicrm_error($preexisting)) {
1379 $transaction->rollback();
1380 return $preexisting;
1383 // Save the new/updated records
1385 foreach ($params['values'] as $replacement) {
1386 // Sugar: Don't force clients to duplicate the 'key' data
1387 $replacement = array_merge($baseParams, $replacement);
1388 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1389 $create = civicrm_api($entity, $action, $replacement);
1390 if (civicrm_error($create)) {
1391 $transaction->rollback();
1394 foreach ($create['values'] as $entity_id => $entity_value) {
1395 $creates[$entity_id] = $entity_value;
1399 // Remove stale records
1400 $staleIDs = array_diff(
1401 array_keys($preexisting['values']),
1402 array_keys($creates)
1404 foreach ($staleIDs as $staleID) {
1405 $delete = civicrm_api($entity, 'delete', array(
1406 'version' => $params['version'],
1409 if (civicrm_error($delete)) {
1410 $transaction->rollback();
1415 return civicrm_api3_create_success($creates, $params);
1417 catch(PEAR_Exception
$e) {
1418 $transaction->rollback();
1419 return civicrm_api3_create_error($e->getMessage());
1421 catch(Exception
$e) {
1422 $transaction->rollback();
1423 return civicrm_api3_create_error($e->getMessage());
1432 function _civicrm_api3_generic_replace_base_params($params) {
1433 $baseParams = $params;
1434 unset($baseParams['values']);
1435 unset($baseParams['sequential']);
1436 unset($baseParams['options']);
1441 * returns fields allowable by api
1443 * @param $entity string Entity to query
1444 * @param bool $unique index by unique fields?
1445 * @param array $params
1449 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1450 $unsetIfEmpty = array('dataPattern', 'headerPattern', 'default', 'export', 'import');
1451 $dao = _civicrm_api3_get_DAO($entity);
1456 $fields = $d->fields();
1457 // replace uniqueNames by the normal names as the key
1458 if (empty($unique)) {
1459 foreach ($fields as $name => & $field) {
1460 //getting rid of unused attributes
1461 foreach ($unsetIfEmpty as $attr) {
1462 if (empty($field[$attr])) {
1463 unset($field[$attr]);
1466 if ($name == $field['name']) {
1469 if (array_key_exists($field['name'], $fields)) {
1470 $field['error'] = 'name conflict';
1471 // it should never happen, but better safe than sorry
1474 $fields[$field['name']] = $field;
1475 $fields[$field['name']]['uniqueName'] = $name;
1476 unset($fields[$name]);
1479 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1484 * Return an array of fields for a given entity - this is the same as the BAO function but
1485 * fields are prefixed with 'custom_' to represent api params
1487 function _civicrm_api_get_custom_fields($entity, &$params) {
1488 $customfields = array();
1489 $entity = _civicrm_api_get_camel_name($entity);
1490 if (strtolower($entity) == 'contact') {
1491 // Use sub-type if available, otherwise stick with 'Contact'
1492 $entity = CRM_Utils_Array
::value('contact_type', $params);
1494 $retrieveOnlyParent = FALSE;
1495 // we could / should probably test for other subtypes here - e.g. activity_type_id
1496 if($entity == 'Contact'){
1497 empty($params['contact_sub_type']);
1499 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1502 CRM_Utils_Array
::value('contact_sub_type', $params, FALSE),
1504 $retrieveOnlyParent,
1508 // find out if we have any requests to resolve options
1509 $getoptions = CRM_Utils_Array
::value('get_options', CRM_Utils_Array
::value('options',$params));
1510 if(!is_array($getoptions)){
1511 $getoptions = array($getoptions);
1514 foreach ($customfields as $key => $value) {
1515 // Regular fields have a 'name' property
1516 $value['name'] = 'custom_' . $key;
1517 $value['type'] = _getStandardTypeFromCustomDataType($value['data_type']);
1518 $customfields['custom_' . $key] = $value;
1519 if (in_array('custom_' . $key, $getoptions)) {
1520 $customfields['custom_' . $key]['options'] = CRM_Core_BAO_CustomOption
::valuesByID($key);
1522 unset($customfields[$key]);
1524 return $customfields;
1527 * Translate the custom field data_type attribute into a std 'type'
1529 function _getStandardTypeFromCustomDataType($dataType) {
1531 'String' => CRM_Utils_Type
::T_STRING
,
1532 'Int' => CRM_Utils_Type
::T_INT
,
1533 'Money' => CRM_Utils_Type
::T_MONEY
,
1534 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1535 'Float' => CRM_Utils_Type
::T_FLOAT
,
1536 'Date' => CRM_Utils_Type
::T_DATE
,
1537 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1538 'StateProvince' => CRM_Utils_Type
::T_INT
,
1539 'File' => CRM_Utils_Type
::T_STRING
,
1540 'Link' => CRM_Utils_Type
::T_STRING
,
1541 'ContactReference' => CRM_Utils_Type
::T_INT
,
1542 'Country' => CRM_Utils_Type
::T_INT
,
1544 return $mapping[$dataType];
1547 * Return array of defaults for the given API (function is a wrapper on getfields)
1549 function _civicrm_api3_getdefaults($apiRequest, $fields) {
1550 $defaults = array();
1552 foreach ($fields as $field => $values) {
1553 if (isset($values['api.default'])) {
1554 $defaults[$field] = $values['api.default'];
1561 * Return array of defaults for the given API (function is a wrapper on getfields)
1563 function _civicrm_api3_getrequired($apiRequest, $fields) {
1564 $required = array('version');
1566 foreach ($fields as $field => $values) {
1567 if (!empty($values['api.required'])) {
1568 $required[] = $field;
1575 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't
1576 * If multiple aliases the last takes precedence
1578 * Function also swaps unique fields for non-unique fields & vice versa.
1580 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1581 foreach ($fields as $field => $values) {
1582 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1583 if (!empty($values['api.aliases'])) {
1584 // if aliased field is not set we try to use field alias
1585 if (!isset($apiRequest['params'][$field])) {
1586 foreach ($values['api.aliases'] as $alias) {
1587 if (isset($apiRequest['params'][$alias])) {
1588 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1590 //unset original field nb - need to be careful with this as it may bring inconsistencies
1591 // out of the woodwork but will be implementing only as _spec function extended
1592 unset($apiRequest['params'][$alias]);
1596 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
1597 && isset($apiRequest['params'][$values['name']])
1599 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1600 // note that it would make sense to unset the original field here but tests need to be in place first
1602 if (!isset($apiRequest['params'][$field])
1604 && $field != $uniqueName
1605 && array_key_exists($uniqueName, $apiRequest['params'])
1608 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1609 // note that it would make sense to unset the original field here but tests need to be in place first
1616 * Validate integer fields being passed into API.
1617 * It currently converts the incoming value 'user_contact_id' into the id of the currenty logged in user
1619 * @param array $params params from civicrm_api
1620 * @param string $fieldName uniquename of field being checked
1623 * @throws API_Exception
1624 * @internal param array $fieldinfo array of fields from getfields function
1626 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1627 //if fieldname exists in params
1628 if (!empty($params[$fieldName])) {
1629 // if value = 'user_contact_id' (or similar), replace value with contact id
1630 if (!is_numeric($params[$fieldName]) && is_scalar($params[$fieldName])) {
1631 $realContactId = _civicrm_api3_resolve_contactID($params[$fieldName]);
1632 if ('unknown-user' === $realContactId) {
1633 throw new API_Exception("\"$fieldName\" \"{$params[$fieldName]}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName,"type"=>"integer"));
1634 } elseif (is_numeric($realContactId)) {
1635 $params[$fieldName] = $realContactId;
1638 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1639 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1642 // After swapping options, ensure we have an integer(s)
1643 foreach ((array) ($params[$fieldName]) as $value) {
1644 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1645 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1649 // Check our field length
1650 if(is_string($params[$fieldName]) && !empty($fieldInfo['maxlength']) && strlen($params[$fieldName]) > $fieldInfo['maxlength']
1652 throw new API_Exception( $params[$fieldName] . " is " . strlen($params[$fieldName]) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1653 2100, array('field' => $fieldName, "max_length"=>$fieldInfo['maxlength'])
1660 * Determine a contact ID using a string expression
1662 * @param string $contactIdExpr e.g. "user_contact_id" or "@user:username"
1663 * @return int|NULL|'unknown-user'
1665 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1666 //if value = 'user_contact_id' replace value with logged in user id
1667 if ($contactIdExpr == "user_contact_id") {
1668 $session = &CRM_Core_Session
::singleton();
1669 if (!is_numeric($session->get('userID'))) {
1672 return $session->get('userID');
1673 } elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1674 $config = CRM_Core_Config
::singleton();
1676 $ufID = $config->userSystem
->getUfId($matches[1]);
1678 return 'unknown-user';
1681 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
1683 return 'unknown-user';
1692 * Validate html (check for scripting attack)
1697 * @throws API_Exception
1699 function _civicrm_api3_validate_html(&$params, &$fieldName, &$fieldInfo) {
1700 if ($value = CRM_Utils_Array
::value($fieldName, $params)) {
1701 if (!CRM_Utils_Rule
::xssString($value)) {
1702 throw new API_Exception('Illegal characters in input (potential scripting attack)', array("field"=>$fieldName,"error_code"=>"xss"));
1708 * Validate string fields being passed into API.
1709 * @param array $params params from civicrm_api
1710 * @param string $fieldName uniquename of field being checked
1713 * @throws API_Exception
1715 * @internal param array $fieldinfo array of fields from getfields function
1717 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
1718 // If fieldname exists in params
1719 $value = CRM_Utils_Array
::value($fieldName, $params, '');
1720 if(!is_array($value)){
1721 $value = (string) $value;
1724 //@todo what do we do about passed in arrays. For many of these fields
1725 // the missing piece of functionality is separating them to a separated string
1726 // & many save incorrectly. But can we change them wholesale?
1729 if (!CRM_Utils_Rule
::xssString($value)) {
1730 throw new Exception('Illegal characters in input (potential scripting attack)');
1732 if ($fieldName == 'currency') {
1733 if (!CRM_Utils_Rule
::currencyCode($value)) {
1734 throw new Exception("Currency not a valid code: $value");
1737 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1738 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1740 // Check our field length
1741 elseif (is_string($value) && !empty($fieldInfo['maxlength']) && strlen($value) > $fieldInfo['maxlength']) {
1742 throw new API_Exception("Value for $fieldName is " . strlen($value) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
1743 2100, array('field' => $fieldName)
1750 * Validate & swap out any pseudoconstants / options
1752 * @param $params: api parameters
1753 * @param $entity: api entity name
1754 * @param $fieldName: field name used in api call (not necessarily the canonical name)
1755 * @param $fieldInfo: getfields meta-data
1757 function _civicrm_api3_api_match_pseudoconstant(&$params, $entity, $fieldName, $fieldInfo) {
1758 $options = CRM_Utils_Array
::value('options', $fieldInfo);
1760 if(strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
1761 // we need to get the options from the entity the field relates to
1762 $entity = $fieldInfo['entity'];
1764 $options = civicrm_api($entity, 'getoptions', array('version' => 3, 'field' => $fieldInfo['name'], 'context' => 'validate'));
1765 $options = CRM_Utils_Array
::value('values', $options, array());
1768 // If passed a value-separated string, explode to an array, then re-implode after matching values
1770 if (is_string($params[$fieldName]) && strpos($params[$fieldName], CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
1771 $params[$fieldName] = CRM_Utils_Array
::explodePadded($params[$fieldName]);
1774 // If passed multiple options, validate each
1775 if (is_array($params[$fieldName])) {
1776 foreach ($params[$fieldName] as &$value) {
1777 if (!is_array($value)) {
1778 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
1781 // TODO: unwrap the call to implodePadded from the conditional and do it always
1782 // need to verify that this is safe and doesn't break anything though.
1783 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
1785 CRM_Utils_Array
::implodePadded($params[$fieldName]);
1789 _civicrm_api3_api_match_pseudoconstant_value($params[$fieldName], $options, $fieldName);
1794 * Validate & swap a single option value for a field
1796 * @param $value: field value
1797 * @param $options: array of options for this field
1798 * @param $fieldName: field name used in api call (not necessarily the canonical name)
1799 * @throws API_Exception
1801 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
1802 // If option is a key, no need to translate
1803 if (array_key_exists($value, $options)) {
1807 // Translate value into key
1808 $newValue = array_search($value, $options);
1809 if ($newValue !== FALSE) {
1813 // Case-insensitive matching
1814 $newValue = strtolower($value);
1815 $options = array_map("strtolower", $options);
1816 $newValue = array_search($newValue, $options);
1817 if ($newValue === FALSE) {
1818 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
1824 * Returns the canonical name of a field
1825 * @param $entity: api entity name (string should already be standardized - no camelCase)
1826 * @param $fieldName: any variation of a field's name (name, unique_name, api.alias)
1828 * @return (string|bool) fieldName or FALSE if the field does not exist
1830 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
1831 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
1834 if ($fieldName == "{$entity}_id") {
1837 $result = civicrm_api($entity, 'getfields', array(
1839 'action' => 'create',
1841 $meta = $result['values'];
1842 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
1843 $fieldName = $fieldName . '_id';
1845 if (isset($meta[$fieldName])) {
1846 return $meta[$fieldName]['name'];
1848 foreach ($meta as $info) {
1849 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
1850 return $info['name'];
1852 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
1853 return $info['name'];