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
135 * @throws API_Exception
136 * @return array <type>
138 function civicrm_api3_create_error($msg, $data = array()) {
139 $data['is_error'] = 1;
140 $data['error_message'] = $msg;
141 // we will show sql to privileged user only (not sure of a specific
142 // security hole here but seems sensible - perhaps should apply to the trace as well?)
143 if(isset($data['sql']) && CRM_Core_Permission
::check('Administer CiviCRM')) {
144 $data['debug_information'] = $data['sql']; // Isn't this redundant?
152 * Format array in result output styple
154 * @param array $values values generated by API operation (the result)
155 * @param array $params parameters passed into API call
156 * @param string $entity the entity being acted on
157 * @param string $action the action passed to the API
158 * @param object $dao DAO object to be freed here
159 * @param array $extraReturnValues additional values to be added to top level of result array(
160 * - this param is currently used for legacy behaviour support
162 * @return array $result
164 function civicrm_api3_create_success($values = 1, $params = array(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
166 $result['is_error'] = 0;
167 //lets set the ['id'] field if it's not set & we know what the entity is
168 if (is_array($values) && !empty($entity)) {
169 foreach ($values as $key => $item) {
170 if (empty($item['id']) && !empty($item[$entity . "_id"])) {
171 $values[$key]['id'] = $item[$entity . "_id"];
173 if(!empty($item['financial_type_id'])){
174 //4.3 legacy handling
175 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
177 if(!empty($item['next_sched_contribution_date'])){
178 // 4.4 legacy handling
179 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
184 if (is_array($params) && !empty($params['debug'])) {
185 if (is_string($action) && $action != 'getfields') {
186 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) +
$params);
188 elseif ($action != 'getfields') {
189 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
195 $allFields = array();
196 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
197 $allFields = array_keys($apiFields['values']);
199 $paramFields = array_keys($params);
200 $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', 'prettyprint'));
202 $result['undefined_fields'] = array_merge($undefined);
205 if (is_object($dao)) {
209 $result['version'] = 3;
210 if (is_array($values)) {
211 $result['count'] = (int) count($values);
213 // Convert value-separated strings to array
214 _civicrm_api3_separate_values($values);
216 if ($result['count'] == 1) {
217 list($result['id']) = array_keys($values);
219 elseif (!empty($values['id']) && is_int($values['id'])) {
220 $result['id'] = $values['id'];
224 $result['count'] = !empty($values) ?
1 : 0;
227 if (is_array($values) && isset($params['sequential']) &&
228 $params['sequential'] == 1
230 $result['values'] = array_values($values);
233 $result['values'] = $values;
235 if(!empty($params['options']['metadata'])) {
236 // we've made metadata an array but only supporting 'fields' atm
237 if(in_array('fields', $params['options']['metadata'])) {
238 $fields = civicrm_api3($entity, 'getfields', array('action' => substr($action, 0, 3) == 'get' ?
'get' : 'create'));
239 $result['metadata']['fields'] = $fields['values'];
242 return array_merge($result, $extraReturnValues);
246 * Load the DAO of the entity
248 function _civicrm_api3_load_DAO($entity) {
249 $dao = _civicrm_api3_get_DAO($entity);
258 * Function to return the DAO of the function or Entity
259 * @param String $name either a function of the api (civicrm_{entity}_create or the entity name
260 * return the DAO name to manipulate this function
261 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
262 * @return mixed|string
264 function _civicrm_api3_get_DAO($name) {
265 if (strpos($name, 'civicrm_api3') !== FALSE) {
266 $last = strrpos($name, '_');
267 // len ('civicrm_api3_') == 13
268 $name = substr($name, 13, $last - 13);
271 $name = _civicrm_api_get_camel_name($name, 3);
273 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
277 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
279 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
280 // but am not confident mailing_recipients is tested so have not tackled.
281 if ($name == 'MailingRecipients') {
282 return 'CRM_Mailing_DAO_Recipients';
284 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
285 if ($name == 'MailingComponent') {
286 return 'CRM_Mailing_DAO_Component';
288 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
289 if ($name == 'AclRole') {
290 return 'CRM_ACL_DAO_EntityRole';
292 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
293 // But this would impact SMS extensions so need to coordinate
294 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
295 if ($name == 'SmsProvider') {
296 return 'CRM_SMS_DAO_Provider';
298 // FIXME: DAO names should follow CamelCase convention
299 if ($name == 'Im' ||
$name == 'Acl') {
300 $name = strtoupper($name);
302 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
303 if ($dao ||
!$name) {
307 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
308 if(file_exists("api/v3/$name.php")) {
309 include_once "api/v3/$name.php";
311 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
312 if (function_exists($daoFn)) {
320 * Function to return the DAO of the function or Entity
321 * @param String $name is either a function of the api (civicrm_{entity}_create or the entity name
322 * return the DAO name to manipulate this function
323 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
326 function _civicrm_api3_get_BAO($name) {
327 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
328 if ($name == 'PrintLabel') {
329 return 'CRM_Badge_BAO_Layout';
331 $dao = _civicrm_api3_get_DAO($name);
335 $bao = str_replace("DAO", "BAO", $dao);
336 $file = strtr($bao, '_', '/') . '.php';
337 // Check if this entity actually has a BAO. Fall back on the DAO if not.
338 return stream_resolve_include_path($file) ?
$bao : $dao;
342 * Recursive function to explode value-separated strings into arrays
345 function _civicrm_api3_separate_values(&$values) {
346 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
347 foreach ($values as $key => & $value) {
348 if (is_array($value)) {
349 _civicrm_api3_separate_values($value);
351 elseif (is_string($value)) {
352 if($key == 'case_type_id'){// this is to honor the way case API was originally written
353 $value = trim(str_replace($sp, ',', $value), ',');
355 elseif (strpos($value, $sp) !== FALSE) {
356 $value = explode($sp, trim($value, $sp));
363 * This is a legacy wrapper for api_store_values which will check the suitable fields using getfields
364 * rather than DAO->fields
366 * Getfields has handling for how to deal with uniquenames which dao->fields doesn't
368 * Note this is used by BAO type create functions - eg. contribution
369 * @param string $entity
370 * @param array $params
371 * @param array $values
373 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values){
374 $fields = civicrm_api($entity,'getfields', array('version' => 3,'action' => 'create'));
375 $fields = $fields['values'];
376 _civicrm_api3_store_values($fields, $params, $values);
380 * @param array $fields
381 * @param array $params
382 * @param array $values
384 * @return Bool $valueFound
386 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
389 $keys = array_intersect_key($params, $fields);
390 foreach ($keys as $name => $value) {
391 if ($name !== 'id') {
392 $values[$name] = $value;
400 * The API supports 2 types of get requestion. The more complex uses the BAO query object.
401 * This is a generic function for those functions that call it
403 * At the moment only called by contact we should extend to contribution &
404 * others that use the query object. Note that this function passes permission information in.
407 * * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
410 * @param array $params as passed into api get or getcount function
411 * @param array $additional_options
412 * @param bool $getCount are we just after the count
415 * @internal param array $options array of options (so we can modify the filter)
417 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL){
419 // Convert id to e.g. contact_id
420 if (empty($params[$entity . '_id']) && isset($params['id'])) {
421 $params[$entity . '_id'] = $params['id'];
423 unset($params['id']);
425 $options = _civicrm_api3_get_options_from_params($params, TRUE);
427 $inputParams = array_merge(
428 CRM_Utils_Array
::value('input_params', $options, array()),
429 CRM_Utils_Array
::value('input_params', $additional_options, array())
431 $returnProperties = array_merge(
432 CRM_Utils_Array
::value('return', $options, array()),
433 CRM_Utils_Array
::value('return', $additional_options, array())
435 if(empty($returnProperties)){
436 $returnProperties = NULL;
438 if(!empty($params['check_permissions'])){
439 // we will filter query object against getfields
440 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
441 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
442 $fields['values'][$entity . '_id'] = array();
443 $varsToFilter = array('returnProperties', 'inputParams');
444 foreach ($varsToFilter as $varToFilter){
445 if(!is_array($
$varToFilter)){
448 //I was going to throw an exception rather than silently filter out - but
449 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
450 //so we are silently ignoring parts of their request
451 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
452 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
455 $options = array_merge($options,$additional_options);
456 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
457 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
458 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
459 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
463 $returnProperties = NULL;
466 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
467 foreach ($newParams as &$newParam) {
468 if($newParam[1] == '=' && is_array($newParam[2])) {
469 // we may be looking at an attempt to use the 'IN' style syntax
470 // @todo at time of writing only 'IN' & 'NOT IN' are supported for the array style syntax
471 $sqlFilter = CRM_Core_DAO
::createSqlFilter($newParam[0], $params[$newParam[0]], 'String', NULL, TRUE);
473 $newParam[1] = key($newParam[2]);
474 $newParam[2] = $sqlFilter;
479 $skipPermissions = !empty($params['check_permissions']) ?
0 :1;
481 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
492 if ($getCount) { // only return the count of contacts
500 * get dao query object based on input params
501 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
504 * @param array $params
505 * @param string $mode
506 * @param string $entity
507 * @return CRM_Core_DAO query object
509 function _civicrm_api3_get_query_object($params, $mode, $entity) {
510 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
511 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
512 $offset = CRM_Utils_Array
::value('offset', $options);
513 $rowCount = CRM_Utils_Array
::value('limit', $options);
514 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
515 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
516 if (empty($returnProperties)) {
517 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
520 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
521 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
524 list($select, $from, $where, $having) = $query->query();
526 $sql = "$select $from $where $having";
529 $sql .= " ORDER BY $sort ";
531 if(!empty($rowCount)) {
532 $sql .= " LIMIT $offset, $rowCount ";
534 $dao = CRM_Core_DAO
::executeQuery($sql);
535 return array($dao, $query);
539 * Function transfers the filters being passed into the DAO onto the params object
541 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $entity) {
542 $entity = substr($dao->__table
, 8);
544 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
546 $fields = array_intersect(array_keys($allfields), array_keys($params));
547 if (isset($params[$entity . "_id"])) {
548 //if entity_id is set then treat it as ID (will be overridden by id if set)
549 $dao->id
= $params[$entity . "_id"];
552 $options = _civicrm_api3_get_options_from_params($params);
553 //apply options like sort
554 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
556 //accept filters like filter.activity_date_time_high
557 // std is now 'filters' => ..
558 if (strstr(implode(',', array_keys($params)), 'filter')) {
559 if (isset($params['filters']) && is_array($params['filters'])) {
560 foreach ($params['filters'] as $paramkey => $paramvalue) {
561 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
565 foreach ($params as $paramkey => $paramvalue) {
566 if (strstr($paramkey, 'filter')) {
567 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
576 foreach ($fields as $field) {
577 if (is_array($params[$field])) {
578 //get the actual fieldname from db
579 $fieldName = $allfields[$field]['name'];
580 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
582 $dao->whereAdd($where);
587 $daoFieldName = $allfields[$field]['name'];
588 if (empty($daoFieldName)) {
589 throw new API_Exception("Failed to determine field name for \"$field\"");
591 $dao->{$daoFieldName} = $params[$field];
594 $dao->$field = $params[$field];
598 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
600 $options['return']['id'] = TRUE;// ensure 'id' is included
601 $allfields = _civicrm_api3_get_unique_name_array($dao);
602 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
603 foreach ($returnMatched as $returnValue) {
604 $dao->selectAdd($returnValue);
607 $unmatchedFields = array_diff(// not already matched on the field names
608 array_keys($options['return']),
612 $returnUniqueMatched = array_intersect(
614 array_flip($allfields)// but a match for the field keys
616 foreach ($returnUniqueMatched as $uniqueVal){
617 $dao->selectAdd($allfields[$uniqueVal]);
620 $dao->setApiFilter($params);
624 * Apply filters (e.g. high, low) to DAO object (prior to find)
625 * @param string $filterField field name of filter
626 * @param string $filterValue field value of filter
627 * @param object $dao DAO object
629 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
630 if (strstr($filterField, 'high')) {
631 $fieldName = substr($filterField, 0, -5);
632 $dao->whereAdd("($fieldName <= $filterValue )");
634 if (strstr($filterField, 'low')) {
635 $fieldName = substr($filterField, 0, -4);
636 $dao->whereAdd("($fieldName >= $filterValue )");
638 if($filterField == 'is_current' && $filterValue == 1){
639 $todayStart = date('Ymd000000', strtotime('now'));
640 $todayEnd = date('Ymd235959', strtotime('now'));
641 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
642 if(property_exists($dao, 'is_active')){
643 $dao->whereAdd('is_active = 1');
649 * Get sort, limit etc options from the params - supporting old & new formats.
650 * get returnproperties for legacy
652 * @param array $params params array as passed into civicrm_api
653 * @param bool $queryObject - is this supporting a queryobject api (e.g contact) - if so we support more options
654 * for legacy report & return a unique fields array
656 * @param string $entity
657 * @param string $action
659 * @return array $options options extracted from params
661 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
663 $sort = CRM_Utils_Array
::value('sort', $params, 0);
664 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
665 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
667 $offset = CRM_Utils_Array
::value('offset', $params, 0);
668 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
669 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
670 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
672 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
673 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
674 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
676 if (is_array(CRM_Utils_Array
::value('options', $params))) {
677 // is count is set by generic getcount not user
678 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
679 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
680 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
681 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
684 $returnProperties = array();
685 // handle the format return =sort_name,display_name...
686 if (array_key_exists('return', $params)) {
687 if (is_array($params['return'])) {
688 $returnProperties = array_fill_keys($params['return'], 1);
691 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
692 $returnProperties = array_fill_keys($returnProperties, 1);
695 if ($entity && $action =='get') {
696 if (!empty($returnProperties['id'])) {
697 $returnProperties[$entity . '_id'] = 1;
698 unset($returnProperties['id']);
700 switch (trim(strtolower($sort))){
704 $sort = str_replace('id', $entity . '_id',$sort);
709 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
710 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
711 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
712 'is_count' => $is_count,
713 'return' => !empty($returnProperties) ?
$returnProperties : NULL,
716 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
717 throw new API_Exception('invalid string in sort options');
723 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
724 // if the queryobject is being used this should be used
725 $inputParams = array();
726 $legacyreturnProperties = array();
728 'sort', 'offset', 'rowCount', 'options','return',
730 foreach ($params as $n => $v) {
731 if (substr($n, 0, 7) == 'return.') {
732 $legacyreturnProperties[substr($n, 7)] = $v;
734 elseif ($n == 'id') {
735 $inputParams[$entity. '_id'] = $v;
737 elseif (in_array($n, $otherVars)) {}
739 $inputParams[$n] = $v;
740 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
741 throw new API_Exception('invalid string');
745 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
746 $options['input_params'] = $inputParams;
751 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find)
753 * @param array $params params array as passed into civicrm_api
754 * @param object $dao DAO object
757 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
759 $options = _civicrm_api3_get_options_from_params($params,FALSE,$entity);
760 if(!$options['is_count']) {
761 if(!empty($options['limit'])) {
762 $dao->limit((int)$options['offset'], (int)$options['limit']);
764 if (!empty($options['sort'])) {
765 $dao->orderBy($options['sort']);
771 * build fields array. This is the array of fields as it relates to the given DAO
772 * returns unique fields as keys by default but if set but can return by DB fields
774 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
775 $fields = $bao->fields();
777 if (empty($fields['id'])){
778 $entity = _civicrm_api_get_entity_name_from_dao($bao);
779 $fields['id'] = $fields[$entity . '_id'];
780 unset($fields[$entity . '_id']);
785 foreach ($fields as $field) {
786 $dbFields[$field['name']] = $field;
792 * build fields array. This is the array of fields as it relates to the given DAO
793 * returns unique fields as keys by default but if set but can return by DB fields
795 function _civicrm_api3_get_unique_name_array(&$bao) {
796 $fields = $bao->fields();
797 foreach ($fields as $field => $values) {
798 $uniqueFields[$field] = CRM_Utils_Array
::value('name',$values, $field);
800 return $uniqueFields;
804 * Converts an DAO object to an array
806 * @param object $dao (reference )object to convert
807 * @param null $params
808 * @param bool $uniqueFields
809 * @param string $entity
813 * @params array of arrays (key = id) of array of fields
818 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
820 if(isset($params['options']) && !empty($params['options']['is_count'])) {
821 return $dao->count();
826 if ($autoFind && !$dao->find()) {
830 if(isset($dao->count
)) {
833 //if custom fields are required we will endeavour to set them . NB passing $entity in might be a bit clunky / unrequired
834 if (!empty($entity) && !empty($params['return']) && is_array($params['return'])) {
835 foreach ($params['return'] as $return) {
836 if (substr($return, 0, 6) == 'custom') {
843 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
845 while ($dao->fetch()) {
847 foreach ($fields as $key) {
848 if (array_key_exists($key, $dao)) {
849 // not sure on that one
850 if ($dao->$key !== NULL) {
851 $tmp[$key] = $dao->$key;
855 $result[$dao->id
] = $tmp;
856 if (!empty($custom)) {
857 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
866 * Converts an object to an array
868 * @param object $dao (reference) object to convert
869 * @param array $values (reference) array
870 * @param array|bool $uniqueFields
876 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
878 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
879 foreach ($fields as $key => $value) {
880 if (array_key_exists($key, $dao)) {
881 $values[$key] = $dao->$key;
887 * Wrapper for _civicrm_object_to_array when api supports unique fields
889 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
890 return _civicrm_api3_object_to_array($dao, $values, TRUE);
895 * @param array $params
896 * @param array $values
897 * @param string $extends entity that this custom field extends (e.g. contribution, event, contact)
898 * @param string $entityId ID of entity per $extends
900 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
901 $values['custom'] = array();
902 foreach ($params as $key => $value) {
903 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
904 if ($customFieldID && (!IS_NULL($value))) {
905 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
906 $value, $extends, $customValueID, $entityId, FALSE, FALSE
914 * This function ensures that we have the right input parameters
916 * This function is only called when $dao is passed into verify_mandatory.
917 * The practice of passing $dao into verify_mandatory turned out to be
918 * unsatisfactory as the required fields @ the dao level is so diffent to the abstract
919 * api level. Hence the intention is to remove this function
920 * & the associated param from viery_mandatory
922 * @param array $params Associative array of property name/value
923 * pairs to insert in new history.
925 * @param bool $return
927 * @daoName string DAO to check params agains
929 * @return bool should the missing fields be returned as an array (core error created as default)
931 * @return bool true if all fields present, depending on $result a core error is created of an array of missing fields is returned
934 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
935 //@deprecated - see notes
936 if (isset($params['extends'])) {
937 if (($params['extends'] == 'Activity' ||
938 $params['extends'] == 'Phonecall' ||
939 $params['extends'] == 'Meeting' ||
940 $params['extends'] == 'Group' ||
941 $params['extends'] == 'Contribution'
943 ($params['style'] == 'Tab')
945 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
949 $dao = new $daoName();
950 $fields = $dao->fields();
953 foreach ($fields as $k => $v) {
954 if ($v['name'] == 'id') {
958 if (!empty($v['required'])) {
959 // 0 is a valid input for numbers, CRM-8122
960 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
966 if (!empty($missing)) {
967 if (!empty($return)) {
971 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
979 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this
981 * @param string $bao_name name of BAO
982 * @param array $params params from api
983 * @param bool $returnAsSuccess return in api success format
984 * @param string $entity
988 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
989 $bao = new $bao_name();
990 _civicrm_api3_dao_set_filter($bao, $params, TRUE, $entity);
991 if ($returnAsSuccess) {
992 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
995 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity);
1000 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this
1001 * @param string $bao_name Name of BAO Class
1002 * @param array $params parameters passed into the api call
1003 * @param string $entity Entity - pass in if entity is non-standard & required $ids array
1006 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1008 $args = array(&$params);
1009 if (!empty($entity)) {
1010 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1014 if (method_exists($bao_name, 'create')) {
1016 $fct_name = $bao_name . '::' . $fct;
1017 $bao = call_user_func_array(array($bao_name, $fct), $args);
1019 elseif (method_exists($bao_name, 'add')) {
1021 $fct_name = $bao_name . '::' . $fct;
1022 $bao = call_user_func_array(array($bao_name, $fct), $args);
1025 $fct_name = '_civicrm_api3_basic_create_fallback';
1026 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1029 if (is_null($bao)) {
1030 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1032 elseif (is_a($bao, 'CRM_Core_Error')) {
1033 //some wierd circular thing means the error takes itself as an argument
1034 $msg = $bao->getMessages($bao);
1035 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1036 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1037 // so we need to reset the error object here to avoid getting concatenated errors
1038 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1039 CRM_Core_Error
::singleton()->reset();
1040 throw new API_Exception($msg);
1044 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1045 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1050 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1052 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1053 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1055 * @param string $bao_name
1056 * @param array $params
1058 * @throws API_Exception
1059 * @return CRM_Core_DAO|NULL an instance of the BAO
1061 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1062 $dao_name = get_parent_class($bao_name);
1063 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1064 $dao_name = $bao_name;
1066 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1067 if (empty($entityName)) {
1068 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1069 'class_name' => $bao_name,
1072 $hook = empty($params['id']) ?
'create' : 'edit';
1074 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1075 $instance = new $dao_name();
1076 $instance->copyValues($params);
1078 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1084 * Function to do a 'standard' api del - when the api is only doing a $bao::del then use this
1085 * if api::del doesn't exist it will try DAO delete method
1087 function _civicrm_api3_basic_delete($bao_name, &$params) {
1089 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1090 $args = array(&$params['id']);
1091 if (method_exists($bao_name, 'del')) {
1092 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1093 if ($bao !== FALSE) {
1094 return civicrm_api3_create_success(TRUE);
1096 throw new API_Exception('Could not delete entity id ' . $params['id']);
1098 elseif (method_exists($bao_name, 'delete')) {
1099 $dao = new $bao_name();
1100 $dao->id
= $params['id'];
1102 while ($dao->fetch()) {
1104 return civicrm_api3_create_success();
1108 throw new API_Exception('Could not delete entity id ' . $params['id']);
1112 throw new API_Exception('no delete method found');
1116 * Get custom data for the given entity & Add it to the returnArray as 'custom_123' = 'custom string' AND 'custom_123_1' = 'custom string'
1117 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1119 * @param array $returnArray - array to append custom data too - generally $result[4] where 4 is the entity id.
1120 * @param string $entity e.g membership, event
1122 * @param int $groupID - per CRM_Core_BAO_CustomGroup::getTree
1123 * @param int $subType e.g. membership_type_id where custom data doesn't apply to all membership types
1124 * @param string $subName - Subtype of entity
1126 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1127 $groupTree = &CRM_Core_BAO_CustomGroup
::getTree($entity,
1128 CRM_Core_DAO
::$_nullObject,
1134 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1135 $customValues = array();
1136 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1137 if (!empty($customValues)) {
1138 foreach ($customValues as $key => $val) {
1139 if (strstr($key, '_id')) {
1140 $idkey = substr($key, 0, -3);
1141 $returnArray['custom_' . (CRM_Core_BAO_CustomField
::getKeyID($idkey) . "_id")] = $val;
1142 $returnArray[$key] = $val;
1145 // per standard - return custom_fieldID
1146 $returnArray['custom_' . (CRM_Core_BAO_CustomField
::getKeyID($key))] = $val;
1148 //not standard - but some api did this so guess we should keep - cheap as chips
1149 $returnArray[$key] = $val;
1156 * Validate fields being passed into API. This function relies on the getFields function working accurately
1157 * for the given API. If error mode is set to TRUE then it will also check
1160 * As of writing only date was implemented.
1161 * @param string $entity
1162 * @param string $action
1163 * @param array $params -
1164 * @param array $fields response from getfields all variables are the same as per civicrm_api
1165 * @param bool $errorMode errorMode do intensive post fail checks?
1168 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = False) {
1169 $fields = array_intersect_key($fields, $params);
1170 foreach ($fields as $fieldName => $fieldInfo) {
1171 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1172 case CRM_Utils_Type
::T_INT
:
1173 //field is of type integer
1174 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1179 //field is of type date or datetime
1180 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1184 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1187 case CRM_Utils_Type
::T_STRING
:
1188 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1191 case CRM_Utils_Type
::T_MONEY
:
1192 if (!CRM_Utils_Rule
::money($params[$fieldName]) && !empty($params[$fieldName])) {
1193 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1197 // intensive checks - usually only called after DB level fail
1198 if (!empty($errorMode) && strtolower($action) == 'create') {
1199 if (!empty($fieldInfo['FKClassName'])) {
1200 if (!empty($params[$fieldName])) {
1201 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1203 elseif (!empty($fieldInfo['required'])) {
1204 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1207 if (!empty($fieldInfo['api.unique'])) {
1208 $params['entity'] = $entity;
1209 _civicrm_api3_validate_uniquekey($params, $fieldName, $fieldInfo);
1216 * Validate date fields being passed into API.
1217 * It currently converts both unique fields and DB field names to a mysql date.
1218 * @todo - probably the unique field handling & the if exists handling is now done before this
1219 * function is reached in the wrapper - can reduce this code down to assume we
1220 * are only checking the passed in field
1222 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1223 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1225 * @param array $params params from civicrm_api
1226 * @param string $fieldName uniquename of field being checked
1229 * @internal param array $fieldinfo array of fields from getfields function
1231 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1232 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1233 if (!empty($params[$fieldInfo['name']])) {
1234 //accept 'whatever strtotime accepts
1235 if (strtotime($params[$fieldInfo['name']]) === FALSE) {
1236 throw new Exception($fieldInfo['name'] . " is not a valid date: " . $params[$fieldInfo['name']]);
1238 $params[$fieldInfo['name']] = CRM_Utils_Date
::processDate($params[$fieldInfo['name']]);
1240 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($params[$fieldName])) {
1241 //If the unique field name differs from the db name & is set handle it here
1242 if (strtotime($params[$fieldName]) === FALSE) {
1243 throw new Exception($fieldName . " is not a valid date: " . $params[$fieldName]);
1245 $params[$fieldName] = CRM_Utils_Date
::processDate($params[$fieldName]);
1250 * Validate foreign constraint fields being passed into API.
1252 * @param array $params params from civicrm_api
1253 * @param string $fieldName uniquename of field being checked
1256 * @internal param array $fieldinfo array of fields from getfields function
1258 function _civicrm_api3_validate_constraint(&$params, &$fieldName, &$fieldInfo) {
1259 $dao = new $fieldInfo['FKClassName'];
1260 $dao->id
= $params[$fieldName];
1262 $dao->selectAdd('id');
1263 if (!$dao->find()) {
1264 throw new Exception("$fieldName is not valid : " . $params[$fieldName]);
1269 * Validate foreign constraint fields being passed into API.
1271 * @param array $params params from civicrm_api
1272 * @param string $fieldName uniquename of field being checked
1275 * @internal param array $fieldinfo array of fields from getfields function
1277 function _civicrm_api3_validate_uniquekey(&$params, &$fieldName, &$fieldInfo) {
1278 $existing = civicrm_api($params['entity'], 'get', array(
1279 'version' => $params['version'],
1280 $fieldName => $params[$fieldName],
1282 // an entry already exists for this unique field
1283 if ($existing['count'] == 1) {
1284 // question - could this ever be a security issue?
1285 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1290 * Generic implementation of the "replace" action.
1292 * Replace the old set of entities (matching some given keys) with a new set of
1293 * entities (matching the same keys).
1295 * Note: This will verify that 'values' is present, but it does not directly verify
1296 * any other parameters.
1298 * @param string $entity entity name
1299 * @param array $params params from civicrm_api, including:
1300 * - 'values': an array of records to save
1301 * - all other items: keys which identify new/pre-existing records
1304 function _civicrm_api3_generic_replace($entity, $params) {
1306 $transaction = new CRM_Core_Transaction();
1308 if (!is_array($params['values'])) {
1309 throw new Exception("Mandatory key(s) missing from params array: values");
1312 // Extract the keys -- somewhat scary, don't think too hard about it
1313 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1315 // Lookup pre-existing records
1316 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1317 if (civicrm_error($preexisting)) {
1318 $transaction->rollback();
1319 return $preexisting;
1322 // Save the new/updated records
1324 foreach ($params['values'] as $replacement) {
1325 // Sugar: Don't force clients to duplicate the 'key' data
1326 $replacement = array_merge($baseParams, $replacement);
1327 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1328 $create = civicrm_api($entity, $action, $replacement);
1329 if (civicrm_error($create)) {
1330 $transaction->rollback();
1333 foreach ($create['values'] as $entity_id => $entity_value) {
1334 $creates[$entity_id] = $entity_value;
1338 // Remove stale records
1339 $staleIDs = array_diff(
1340 array_keys($preexisting['values']),
1341 array_keys($creates)
1343 foreach ($staleIDs as $staleID) {
1344 $delete = civicrm_api($entity, 'delete', array(
1345 'version' => $params['version'],
1348 if (civicrm_error($delete)) {
1349 $transaction->rollback();
1354 return civicrm_api3_create_success($creates, $params);
1356 catch(PEAR_Exception
$e) {
1357 $transaction->rollback();
1358 return civicrm_api3_create_error($e->getMessage());
1360 catch(Exception
$e) {
1361 $transaction->rollback();
1362 return civicrm_api3_create_error($e->getMessage());
1371 function _civicrm_api3_generic_replace_base_params($params) {
1372 $baseParams = $params;
1373 unset($baseParams['values']);
1374 unset($baseParams['sequential']);
1375 unset($baseParams['options']);
1380 * returns fields allowable by api
1382 * @param $entity string Entity to query
1383 * @param bool $unique index by unique fields?
1384 * @param array $params
1388 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1389 $unsetIfEmpty = array('dataPattern', 'headerPattern', 'default', 'export', 'import');
1390 $dao = _civicrm_api3_get_DAO($entity);
1395 $fields = $d->fields();
1396 // replace uniqueNames by the normal names as the key
1397 if (empty($unique)) {
1398 foreach ($fields as $name => & $field) {
1399 //getting rid of unused attributes
1400 foreach ($unsetIfEmpty as $attr) {
1401 if (empty($field[$attr])) {
1402 unset($field[$attr]);
1405 if ($name == $field['name']) {
1408 if (array_key_exists($field['name'], $fields)) {
1409 $field['error'] = 'name conflict';
1410 // it should never happen, but better safe than sorry
1413 $fields[$field['name']] = $field;
1414 $fields[$field['name']]['uniqueName'] = $name;
1415 unset($fields[$name]);
1418 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1423 * Return an array of fields for a given entity - this is the same as the BAO function but
1424 * fields are prefixed with 'custom_' to represent api params
1426 function _civicrm_api_get_custom_fields($entity, &$params) {
1427 $customfields = array();
1428 $entity = _civicrm_api_get_camel_name($entity);
1429 if (strtolower($entity) == 'contact') {
1430 // Use sub-type if available, otherwise stick with 'Contact'
1431 $entity = CRM_Utils_Array
::value('contact_type', $params);
1433 $retrieveOnlyParent = FALSE;
1434 // we could / should probably test for other subtypes here - e.g. activity_type_id
1435 if($entity == 'Contact'){
1436 empty($params['contact_sub_type']);
1438 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1441 CRM_Utils_Array
::value('contact_sub_type', $params, FALSE),
1443 $retrieveOnlyParent,
1450 foreach ($customfields as $key => $value) {
1451 // Regular fields have a 'name' property
1452 $value['name'] = 'custom_' . $key;
1453 $value['title'] = $value['label'];
1454 $value['type'] = _getStandardTypeFromCustomDataType($value['data_type']);
1455 $ret['custom_' . $key] = $value;
1460 * Translate the custom field data_type attribute into a std 'type'
1462 function _getStandardTypeFromCustomDataType($dataType) {
1464 'String' => CRM_Utils_Type
::T_STRING
,
1465 'Int' => CRM_Utils_Type
::T_INT
,
1466 'Money' => CRM_Utils_Type
::T_MONEY
,
1467 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1468 'Float' => CRM_Utils_Type
::T_FLOAT
,
1469 'Date' => CRM_Utils_Type
::T_DATE
,
1470 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1471 'StateProvince' => CRM_Utils_Type
::T_INT
,
1472 'File' => CRM_Utils_Type
::T_STRING
,
1473 'Link' => CRM_Utils_Type
::T_STRING
,
1474 'ContactReference' => CRM_Utils_Type
::T_INT
,
1475 'Country' => CRM_Utils_Type
::T_INT
,
1477 return $mapping[$dataType];
1482 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't
1483 * If multiple aliases the last takes precedence
1485 * Function also swaps unique fields for non-unique fields & vice versa.
1487 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1488 foreach ($fields as $field => $values) {
1489 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1490 if (!empty($values['api.aliases'])) {
1491 // if aliased field is not set we try to use field alias
1492 if (!isset($apiRequest['params'][$field])) {
1493 foreach ($values['api.aliases'] as $alias) {
1494 if (isset($apiRequest['params'][$alias])) {
1495 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1497 //unset original field nb - need to be careful with this as it may bring inconsistencies
1498 // out of the woodwork but will be implementing only as _spec function extended
1499 unset($apiRequest['params'][$alias]);
1503 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
1504 && isset($apiRequest['params'][$values['name']])
1506 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1507 // note that it would make sense to unset the original field here but tests need to be in place first
1509 if (!isset($apiRequest['params'][$field])
1511 && $field != $uniqueName
1512 && array_key_exists($uniqueName, $apiRequest['params'])
1515 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1516 // note that it would make sense to unset the original field here but tests need to be in place first
1523 * Validate integer fields being passed into API.
1524 * It currently converts the incoming value 'user_contact_id' into the id of the currenty logged in user
1526 * @param array $params params from civicrm_api
1527 * @param string $fieldName uniquename of field being checked
1530 * @throws API_Exception
1531 * @internal param array $fieldinfo array of fields from getfields function
1533 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1534 //if fieldname exists in params
1535 if (!empty($params[$fieldName])) {
1536 // if value = 'user_contact_id' (or similar), replace value with contact id
1537 if (!is_numeric($params[$fieldName]) && is_scalar($params[$fieldName])) {
1538 $realContactId = _civicrm_api3_resolve_contactID($params[$fieldName]);
1539 if ('unknown-user' === $realContactId) {
1540 throw new API_Exception("\"$fieldName\" \"{$params[$fieldName]}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName,"type"=>"integer"));
1541 } elseif (is_numeric($realContactId)) {
1542 $params[$fieldName] = $realContactId;
1545 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1546 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1549 // After swapping options, ensure we have an integer(s)
1550 foreach ((array) ($params[$fieldName]) as $value) {
1551 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1552 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1556 // Check our field length
1557 if(is_string($params[$fieldName]) && !empty($fieldInfo['maxlength']) && strlen($params[$fieldName]) > $fieldInfo['maxlength']
1559 throw new API_Exception( $params[$fieldName] . " is " . strlen($params[$fieldName]) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1560 2100, array('field' => $fieldName, "max_length"=>$fieldInfo['maxlength'])
1567 * Determine a contact ID using a string expression
1569 * @param string $contactIdExpr e.g. "user_contact_id" or "@user:username"
1570 * @return int|NULL|'unknown-user'
1572 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1573 //if value = 'user_contact_id' replace value with logged in user id
1574 if ($contactIdExpr == "user_contact_id") {
1575 $session = &CRM_Core_Session
::singleton();
1576 if (!is_numeric($session->get('userID'))) {
1579 return $session->get('userID');
1580 } elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1581 $config = CRM_Core_Config
::singleton();
1583 $ufID = $config->userSystem
->getUfId($matches[1]);
1585 return 'unknown-user';
1588 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
1590 return 'unknown-user';
1599 * Validate html (check for scripting attack)
1604 * @throws API_Exception
1606 function _civicrm_api3_validate_html(&$params, &$fieldName, &$fieldInfo) {
1607 if ($value = CRM_Utils_Array
::value($fieldName, $params)) {
1608 if (!CRM_Utils_Rule
::xssString($value)) {
1609 throw new API_Exception('Illegal characters in input (potential scripting attack)', array("field"=>$fieldName,"error_code"=>"xss"));
1615 * Validate string fields being passed into API.
1616 * @param array $params params from civicrm_api
1617 * @param string $fieldName uniquename of field being checked
1620 * @throws API_Exception
1622 * @internal param array $fieldinfo array of fields from getfields function
1624 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
1625 // If fieldname exists in params
1626 $value = CRM_Utils_Array
::value($fieldName, $params, '');
1627 if(!is_array($value)){
1628 $value = (string) $value;
1631 //@todo what do we do about passed in arrays. For many of these fields
1632 // the missing piece of functionality is separating them to a separated string
1633 // & many save incorrectly. But can we change them wholesale?
1636 if (!CRM_Utils_Rule
::xssString($value)) {
1637 throw new Exception('Illegal characters in input (potential scripting attack)');
1639 if ($fieldName == 'currency') {
1640 if (!CRM_Utils_Rule
::currencyCode($value)) {
1641 throw new Exception("Currency not a valid code: $value");
1644 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1645 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1647 // Check our field length
1648 elseif (is_string($value) && !empty($fieldInfo['maxlength']) && strlen($value) > $fieldInfo['maxlength']) {
1649 throw new API_Exception("Value for $fieldName is " . strlen($value) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
1650 2100, array('field' => $fieldName)
1657 * Validate & swap out any pseudoconstants / options
1659 * @param $params: api parameters
1660 * @param $entity: api entity name
1661 * @param $fieldName: field name used in api call (not necessarily the canonical name)
1662 * @param $fieldInfo: getfields meta-data
1664 function _civicrm_api3_api_match_pseudoconstant(&$params, $entity, $fieldName, $fieldInfo) {
1665 $options = CRM_Utils_Array
::value('options', $fieldInfo);
1667 if(strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
1668 // we need to get the options from the entity the field relates to
1669 $entity = $fieldInfo['entity'];
1671 $options = civicrm_api($entity, 'getoptions', array('version' => 3, 'field' => $fieldInfo['name'], 'context' => 'validate'));
1672 $options = CRM_Utils_Array
::value('values', $options, array());
1675 // If passed a value-separated string, explode to an array, then re-implode after matching values
1677 if (is_string($params[$fieldName]) && strpos($params[$fieldName], CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
1678 $params[$fieldName] = CRM_Utils_Array
::explodePadded($params[$fieldName]);
1681 // If passed multiple options, validate each
1682 if (is_array($params[$fieldName])) {
1683 foreach ($params[$fieldName] as &$value) {
1684 if (!is_array($value)) {
1685 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
1688 // TODO: unwrap the call to implodePadded from the conditional and do it always
1689 // need to verify that this is safe and doesn't break anything though.
1690 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
1692 CRM_Utils_Array
::implodePadded($params[$fieldName]);
1696 _civicrm_api3_api_match_pseudoconstant_value($params[$fieldName], $options, $fieldName);
1701 * Validate & swap a single option value for a field
1703 * @param $value: field value
1704 * @param $options: array of options for this field
1705 * @param $fieldName: field name used in api call (not necessarily the canonical name)
1706 * @throws API_Exception
1708 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
1709 // If option is a key, no need to translate
1710 if (array_key_exists($value, $options)) {
1714 // Translate value into key
1715 $newValue = array_search($value, $options);
1716 if ($newValue !== FALSE) {
1720 // Case-insensitive matching
1721 $newValue = strtolower($value);
1722 $options = array_map("strtolower", $options);
1723 $newValue = array_search($newValue, $options);
1724 if ($newValue === FALSE) {
1725 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
1731 * Returns the canonical name of a field
1732 * @param $entity: api entity name (string should already be standardized - no camelCase)
1733 * @param $fieldName: any variation of a field's name (name, unique_name, api.alias)
1735 * @return (string|bool) fieldName or FALSE if the field does not exist
1737 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
1738 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
1741 if ($fieldName == "{$entity}_id") {
1744 $result = civicrm_api($entity, 'getfields', array(
1746 'action' => 'create',
1748 $meta = $result['values'];
1749 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
1750 $fieldName = $fieldName . '_id';
1752 if (isset($meta[$fieldName])) {
1753 return $meta[$fieldName]['name'];
1755 foreach ($meta as $info) {
1756 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
1757 return $info['name'];
1759 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
1760 return $info['name'];