3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * File for CiviCRM APIv3 utilitity functions
31 * @package CiviCRM_APIv3
32 * @subpackage API_utils
34 * @copyright CiviCRM LLC (c) 2004-2013
35 * @version $Id: utils.php 30879 2010-11-22 15:45:55Z shot $
40 * Initialize CiviCRM - should be run at the start of each API function
42 function _civicrm_api3_initialize() {
43 require_once 'CRM/Core/ClassLoader.php';
44 CRM_Core_ClassLoader
::singleton()->register();
45 CRM_Core_Config
::singleton();
49 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking
51 * @param array $params array of fields to checkl
52 * @param array $daoName string DAO to check for required fields (create functions only)
53 * @param array $keyoptions
55 * @internal param array $keys list of required fields options. One of the options is required
56 * @return null or throws error if there the required fields not present
59 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = array(
61 $keys = array(array());
62 foreach ($keyoptions as $key) {
65 civicrm_api3_verify_mandatory($params, $daoName, $keys);
69 * Function to check mandatory fields are included
71 * @param array $params array of fields to check
72 * @param array $daoName string DAO to check for required fields (create functions only)
73 * @param array $keys list of required fields. A value can be an array denoting that either this or that is required.
74 * @param bool $verifyDAO
76 * @throws API_Exception
77 * @return null or throws error if there the required fields not present
79 * @todo see notes on _civicrm_api3_check_required_fields regarding removing $daoName param
81 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = array(), $verifyDAO = TRUE) {
84 if ($daoName != NULL && $verifyDAO && empty($params['id'])) {
85 $unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
86 if (!is_array($unmatched)) {
91 if (!empty($params['id'])) {
92 $keys = array('version');
95 if (!in_array('version', $keys)) {
96 // required from v3 onwards
100 foreach ($keys as $key) {
101 if (is_array($key)) {
103 $optionset = array();
104 foreach ($key as $subkey) {
105 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
106 $optionset[] = $subkey;
109 // as long as there is one match then we don't need to rtn anything
113 if (empty($match) && !empty($optionset)) {
114 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
118 // Disallow empty values except for the number zero.
119 // TODO: create a utility for this since it's needed in many places
120 if (!array_key_exists($key, $params) ||
(empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
125 if (!empty($unmatched)) {
126 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched),"mandatory_missing",array("fields"=>$unmatched));
132 * @param <type> $data
134 * @param object $dao DAO / BAO object to be freed here
136 * @throws API_Exception
137 * @return array <type>
139 function civicrm_api3_create_error($msg, $data = array(), &$dao = NULL) {
140 //fix me - $dao should be param 4 & 3 should be $apiRequest
141 if (is_object($dao)) {
145 if (is_array($dao)) {
146 if ($msg == 'DB Error: constraint violation' ||
substr($msg, 0,9) == 'DB Error:' ||
$msg == 'DB Error: already exists') {
148 $fields = _civicrm_api3_api_getfields($dao);
149 _civicrm_api3_validate_fields($dao['entity'], $dao['action'], $dao['params'], $fields, TRUE);
151 catch(Exception
$e) {
152 $msg = $e->getMessage();
156 $data['is_error'] = 1;
157 $data['error_message'] = $msg;
158 // we will show sql to privelledged user only (not sure of a specific
159 // security hole here but seems sensible - perhaps should apply to the trace as well?
160 if(isset($data['sql']) && CRM_Core_Permission
::check('Administer CiviCRM')) {
161 $data['debug_information'] = $data['sql'];
163 if (is_array($dao) && isset($dao['params']) && is_array($dao['params']) && !empty($dao['params']['api.has_parent'])) {
164 $errorCode = empty($data['error_code']) ?
'chained_api_failed' : $data['error_code'];
165 throw new API_Exception('Error in call to ' . $dao['entity'] . '_' . $dao['action'] . ' : ' . $msg, $errorCode, $data);
171 * Format array in result output styple
173 * @param array $values values generated by API operation (the result)
174 * @param array $params parameters passed into API call
175 * @param string $entity the entity being acted on
176 * @param string $action the action passed to the API
177 * @param object $dao DAO object to be freed here
178 * @param array $extraReturnValues additional values to be added to top level of result array(
179 * - this param is currently used for legacy behaviour support
181 * @return array $result
183 function civicrm_api3_create_success($values = 1, $params = array(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
185 $result['is_error'] = 0;
186 //lets set the ['id'] field if it's not set & we know what the entity is
187 if (is_array($values) && !empty($entity)) {
188 foreach ($values as $key => $item) {
189 if (empty($item['id']) && !empty($item[$entity . "_id"])) {
190 $values[$key]['id'] = $item[$entity . "_id"];
192 if(!empty($item['financial_type_id'])){
193 //4.3 legacy handling
194 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
196 if(!empty($item['next_sched_contribution_date'])){
197 // 4.4 legacy handling
198 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
203 if (is_array($params) && !empty($params['debug'])) {
204 if (is_string($action) && $action != 'getfields') {
205 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) +
$params);
207 elseif ($action != 'getfields') {
208 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
214 $allFields = array();
215 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
216 $allFields = array_keys($apiFields['values']);
218 $paramFields = array_keys($params);
219 $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'));
221 $result['undefined_fields'] = array_merge($undefined);
224 if (is_object($dao)) {
228 $result['version'] = 3;
229 if (is_array($values)) {
230 $result['count'] = (int) count($values);
232 // Convert value-separated strings to array
233 _civicrm_api3_separate_values($values);
235 if ($result['count'] == 1) {
236 list($result['id']) = array_keys($values);
238 elseif (!empty($values['id']) && is_int($values['id'])) {
239 $result['id'] = $values['id'];
243 $result['count'] = !empty($values) ?
1 : 0;
246 if (is_array($values) && isset($params['sequential']) &&
247 $params['sequential'] == 1
249 $result['values'] = array_values($values);
252 $result['values'] = $values;
254 if(!empty($params['options']['metadata'])) {
255 // we've made metadata an array but only supporting 'fields' atm
256 if(in_array('fields', $params['options']['metadata'])) {
257 $fields = civicrm_api3($entity, 'getfields', array('action' => substr($action, 0, 3) == 'get' ?
'get' : 'create'));
258 $result['metadata']['fields'] = $fields['values'];
261 return array_merge($result, $extraReturnValues);
265 * Load the DAO of the entity
267 function _civicrm_api3_load_DAO($entity) {
268 $dao = _civicrm_api3_get_DAO($entity);
277 * Function to return the DAO of the function or Entity
278 * @param String $name either a function of the api (civicrm_{entity}_create or the entity name
279 * return the DAO name to manipulate this function
280 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
281 * @return mixed|string
283 function _civicrm_api3_get_DAO($name) {
284 if (strpos($name, 'civicrm_api3') !== FALSE) {
285 $last = strrpos($name, '_');
286 // len ('civicrm_api3_') == 13
287 $name = substr($name, 13, $last - 13);
290 $name = _civicrm_api_get_camel_name($name, 3);
292 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
296 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
298 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
299 // but am not confident mailing_recipients is tested so have not tackled.
300 if ($name == 'MailingRecipients') {
301 return 'CRM_Mailing_DAO_Recipients';
303 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
304 if ($name == 'MailingComponent') {
305 return 'CRM_Mailing_DAO_Component';
307 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
308 if ($name == 'AclRole') {
309 return 'CRM_ACL_DAO_EntityRole';
311 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
312 // But this would impact SMS extensions so need to coordinate
313 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
314 if ($name == 'SmsProvider') {
315 return 'CRM_SMS_DAO_Provider';
317 // FIXME: DAO names should follow CamelCase convention
318 if ($name == 'Im' ||
$name == 'Acl') {
319 $name = strtoupper($name);
321 return CRM_Core_DAO_AllCoreTables
::getFullName($name);
325 * Function to return the DAO of the function or Entity
326 * @param String $name is either a function of the api (civicrm_{entity}_create or the entity name
327 * return the DAO name to manipulate this function
328 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
331 function _civicrm_api3_get_BAO($name) {
332 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
333 if ($name == 'PrintLabel') {
334 return 'CRM_Badge_BAO_Layout';
336 $dao = _civicrm_api3_get_DAO($name);
340 $bao = str_replace("DAO", "BAO", $dao);
341 $file = strtr($bao, '_', '/') . '.php';
342 // Check if this entity actually has a BAO. Fall back on the DAO if not.
343 return stream_resolve_include_path($file) ?
$bao : $dao;
347 * Recursive function to explode value-separated strings into arrays
350 function _civicrm_api3_separate_values(&$values) {
351 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
352 foreach ($values as $key => & $value) {
353 if (is_array($value)) {
354 _civicrm_api3_separate_values($value);
356 elseif (is_string($value)) {
357 if($key == 'case_type_id'){// this is to honor the way case API was originally written
358 $value = trim(str_replace($sp, ',', $value), ',');
360 elseif (strpos($value, $sp) !== FALSE) {
361 $value = explode($sp, trim($value, $sp));
368 * This is a legacy wrapper for api_store_values which will check the suitable fields using getfields
369 * rather than DAO->fields
371 * Getfields has handling for how to deal with uniquenames which dao->fields doesn't
373 * Note this is used by BAO type create functions - eg. contribution
374 * @param string $entity
375 * @param array $params
376 * @param array $values
378 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values){
379 $fields = civicrm_api($entity,'getfields', array('version' => 3,'action' => 'create'));
380 $fields = $fields['values'];
381 _civicrm_api3_store_values($fields, $params, $values);
385 * @param array $fields
386 * @param array $params
387 * @param array $values
389 * @return Bool $valueFound
391 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
394 $keys = array_intersect_key($params, $fields);
395 foreach ($keys as $name => $value) {
396 if ($name !== 'id') {
397 $values[$name] = $value;
405 * The API supports 2 types of get requestion. The more complex uses the BAO query object.
406 * This is a generic function for those functions that call it
408 * At the moment only called by contact we should extend to contribution &
409 * others that use the query object. Note that this function passes permission information in.
412 * * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
415 * @param array $params as passed into api get or getcount function
416 * @param array $additional_options
417 * @param bool $getCount are we just after the count
420 * @internal param array $options array of options (so we can modify the filter)
422 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL){
424 // Convert id to e.g. contact_id
425 if (empty($params[$entity . '_id']) && isset($params['id'])) {
426 $params[$entity . '_id'] = $params['id'];
428 unset($params['id']);
430 $options = _civicrm_api3_get_options_from_params($params, TRUE);
432 $inputParams = array_merge(
433 CRM_Utils_Array
::value('input_params', $options, array()),
434 CRM_Utils_Array
::value('input_params', $additional_options, array())
436 $returnProperties = array_merge(
437 CRM_Utils_Array
::value('return', $options, array()),
438 CRM_Utils_Array
::value('return', $additional_options, array())
440 if(empty($returnProperties)){
441 $returnProperties = NULL;
443 if(!empty($params['check_permissions'])){
444 // we will filter query object against getfields
445 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
446 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
447 $fields['values'][$entity . '_id'] = array();
448 $varsToFilter = array('returnProperties', 'inputParams');
449 foreach ($varsToFilter as $varToFilter){
450 if(!is_array($
$varToFilter)){
453 //I was going to throw an exception rather than silently filter out - but
454 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
455 //so we are silently ignoring parts of their request
456 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
457 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
460 $options = array_merge($options,$additional_options);
461 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
462 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
463 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
464 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
468 $returnProperties = NULL;
471 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
472 foreach ($newParams as &$newParam) {
473 if($newParam[1] == '=' && is_array($newParam[2])) {
474 // we may be looking at an attempt to use the 'IN' style syntax
475 // @todo at time of writing only 'IN' & 'NOT IN' are supported for the array style syntax
476 $sqlFilter = CRM_Core_DAO
::createSqlFilter($newParam[0], $params[$newParam[0]], 'String', NULL, TRUE);
478 $newParam[1] = key($newParam[2]);
479 $newParam[2] = $sqlFilter;
484 $skipPermissions = !empty($params['check_permissions']) ?
0 :1;
486 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
497 if ($getCount) { // only return the count of contacts
505 * get dao query object based on input params
506 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
509 * @param array $params
510 * @param string $mode
511 * @param string $entity
512 * @return CRM_Core_DAO query object
514 function _civicrm_api3_get_query_object($params, $mode, $entity) {
515 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
516 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
517 $offset = CRM_Utils_Array
::value('offset', $options);
518 $rowCount = CRM_Utils_Array
::value('limit', $options);
519 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
520 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
521 if (empty($returnProperties)) {
522 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
525 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
526 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
529 list($select, $from, $where, $having) = $query->query();
531 $sql = "$select $from $where $having";
534 $sql .= " ORDER BY $sort ";
536 if(!empty($rowCount)) {
537 $sql .= " LIMIT $offset, $rowCount ";
539 $dao = CRM_Core_DAO
::executeQuery($sql);
540 return array($dao, $query);
544 * Function transfers the filters being passed into the DAO onto the params object
546 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $entity) {
547 $entity = substr($dao->__table
, 8);
549 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
551 $fields = array_intersect(array_keys($allfields), array_keys($params));
552 if (isset($params[$entity . "_id"])) {
553 //if entity_id is set then treat it as ID (will be overridden by id if set)
554 $dao->id
= $params[$entity . "_id"];
557 $options = _civicrm_api3_get_options_from_params($params);
558 //apply options like sort
559 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
561 //accept filters like filter.activity_date_time_high
562 // std is now 'filters' => ..
563 if (strstr(implode(',', array_keys($params)), 'filter')) {
564 if (isset($params['filters']) && is_array($params['filters'])) {
565 foreach ($params['filters'] as $paramkey => $paramvalue) {
566 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
570 foreach ($params as $paramkey => $paramvalue) {
571 if (strstr($paramkey, 'filter')) {
572 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
577 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
578 // support for other syntaxes is discussed in ticket but being put off for now
579 $acceptedSQLOperators = array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN');
584 foreach ($fields as $field) {
585 if (is_array($params[$field])) {
586 //get the actual fieldname from db
587 $fieldName = $allfields[$field]['name'];
588 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
590 $dao->whereAdd($where);
595 $daoFieldName = $allfields[$field]['name'];
596 if (empty($daoFieldName)) {
597 throw new API_Exception("Failed to determine field name for \"$field\"");
599 $dao->{$daoFieldName} = $params[$field];
602 $dao->$field = $params[$field];
606 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
608 $options['return']['id'] = TRUE;// ensure 'id' is included
609 $allfields = _civicrm_api3_get_unique_name_array($dao);
610 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
611 foreach ($returnMatched as $returnValue) {
612 $dao->selectAdd($returnValue);
615 $unmatchedFields = array_diff(// not already matched on the field names
616 array_keys($options['return']),
620 $returnUniqueMatched = array_intersect(
622 array_flip($allfields)// but a match for the field keys
624 foreach ($returnUniqueMatched as $uniqueVal){
625 $dao->selectAdd($allfields[$uniqueVal]);
628 $dao->setApiFilter($params);
632 * Apply filters (e.g. high, low) to DAO object (prior to find)
633 * @param string $filterField field name of filter
634 * @param string $filterValue field value of filter
635 * @param object $dao DAO object
637 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
638 if (strstr($filterField, 'high')) {
639 $fieldName = substr($filterField, 0, -5);
640 $dao->whereAdd("($fieldName <= $filterValue )");
642 if (strstr($filterField, 'low')) {
643 $fieldName = substr($filterField, 0, -4);
644 $dao->whereAdd("($fieldName >= $filterValue )");
646 if($filterField == 'is_current' && $filterValue == 1){
647 $todayStart = date('Ymd000000', strtotime('now'));
648 $todayEnd = date('Ymd235959', strtotime('now'));
649 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
650 if(property_exists($dao, 'is_active')){
651 $dao->whereAdd('is_active = 1');
657 * Get sort, limit etc options from the params - supporting old & new formats.
658 * get returnproperties for legacy
660 * @param array $params params array as passed into civicrm_api
661 * @param bool $queryObject - is this supporting a queryobject api (e.g contact) - if so we support more options
662 * for legacy report & return a unique fields array
664 * @param string $entity
665 * @param string $action
667 * @return array $options options extracted from params
669 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
671 $sort = CRM_Utils_Array
::value('sort', $params, 0);
672 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
673 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
675 $offset = CRM_Utils_Array
::value('offset', $params, 0);
676 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
677 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
678 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
680 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
681 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
682 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
684 if (is_array(CRM_Utils_Array
::value('options', $params))) {
685 // is count is set by generic getcount not user
686 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
687 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
688 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
689 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
692 $returnProperties = array();
693 // handle the format return =sort_name,display_name...
694 if (array_key_exists('return', $params)) {
695 if (is_array($params['return'])) {
696 $returnProperties = array_fill_keys($params['return'], 1);
699 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
700 $returnProperties = array_fill_keys($returnProperties, 1);
703 if ($entity && $action =='get') {
704 if (!empty($returnProperties['id'])) {
705 $returnProperties[$entity . '_id'] = 1;
706 unset($returnProperties['id']);
708 switch (trim(strtolower($sort))){
712 $sort = str_replace('id', $entity . '_id',$sort);
717 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
718 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
719 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
720 'is_count' => $is_count,
721 'return' => !empty($returnProperties) ?
$returnProperties : NULL,
724 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
725 throw new API_Exception('invalid string in sort options');
731 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
732 // if the queryobject is being used this should be used
733 $inputParams = array();
734 $legacyreturnProperties = array();
736 'sort', 'offset', 'rowCount', 'options','return',
738 foreach ($params as $n => $v) {
739 if (substr($n, 0, 7) == 'return.') {
740 $legacyreturnProperties[substr($n, 7)] = $v;
742 elseif ($n == 'id') {
743 $inputParams[$entity. '_id'] = $v;
745 elseif (in_array($n, $otherVars)) {}
747 $inputParams[$n] = $v;
748 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
749 throw new API_Exception('invalid string');
753 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
754 $options['input_params'] = $inputParams;
759 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find)
761 * @param array $params params array as passed into civicrm_api
762 * @param object $dao DAO object
765 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
767 $options = _civicrm_api3_get_options_from_params($params,FALSE,$entity);
768 if(!$options['is_count']) {
769 if(!empty($options['limit'])) {
770 $dao->limit((int)$options['offset'], (int)$options['limit']);
772 if (!empty($options['sort'])) {
773 $dao->orderBy($options['sort']);
779 * build fields array. This is the array of fields as it relates to the given DAO
780 * returns unique fields as keys by default but if set but can return by DB fields
782 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
783 $fields = $bao->fields();
785 if (empty($fields['id'])){
786 $entity = _civicrm_api_get_entity_name_from_dao($bao);
787 $fields['id'] = $fields[$entity . '_id'];
788 unset($fields[$entity . '_id']);
793 foreach ($fields as $field) {
794 $dbFields[$field['name']] = $field;
800 * build fields array. This is the array of fields as it relates to the given DAO
801 * returns unique fields as keys by default but if set but can return by DB fields
803 function _civicrm_api3_get_unique_name_array(&$bao) {
804 $fields = $bao->fields();
805 foreach ($fields as $field => $values) {
806 $uniqueFields[$field] = CRM_Utils_Array
::value('name',$values, $field);
808 return $uniqueFields;
812 * Converts an DAO object to an array
814 * @param object $dao (reference )object to convert
815 * @param null $params
816 * @param bool $uniqueFields
817 * @param string $entity
821 * @params array of arrays (key = id) of array of fields
826 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
828 if(isset($params['options']) && !empty($params['options']['is_count'])) {
829 return $dao->count();
834 if ($autoFind && !$dao->find()) {
838 if(isset($dao->count
)) {
841 //if custom fields are required we will endeavour to set them . NB passing $entity in might be a bit clunky / unrequired
842 if (!empty($entity) && !empty($params['return']) && is_array($params['return'])) {
843 foreach ($params['return'] as $return) {
844 if (substr($return, 0, 6) == 'custom') {
851 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
853 while ($dao->fetch()) {
855 foreach ($fields as $key) {
856 if (array_key_exists($key, $dao)) {
857 // not sure on that one
858 if ($dao->$key !== NULL) {
859 $tmp[$key] = $dao->$key;
863 $result[$dao->id
] = $tmp;
864 if (!empty($custom)) {
865 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
874 * Converts an object to an array
876 * @param object $dao (reference) object to convert
877 * @param array $values (reference) array
878 * @param array|bool $uniqueFields
884 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
886 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
887 foreach ($fields as $key => $value) {
888 if (array_key_exists($key, $dao)) {
889 $values[$key] = $dao->$key;
895 * Wrapper for _civicrm_object_to_array when api supports unique fields
897 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
898 return _civicrm_api3_object_to_array($dao, $values, TRUE);
903 * @param array $params
904 * @param array $values
905 * @param string $extends entity that this custom field extends (e.g. contribution, event, contact)
906 * @param string $entityId ID of entity per $extends
908 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
909 $values['custom'] = array();
910 foreach ($params as $key => $value) {
911 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
912 if ($customFieldID && (!IS_NULL($value))) {
913 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
914 $value, $extends, $customValueID, $entityId, FALSE, FALSE
922 * This function ensures that we have the right input parameters
924 * This function is only called when $dao is passed into verify_mandatory.
925 * The practice of passing $dao into verify_mandatory turned out to be
926 * unsatisfactory as the required fields @ the dao level is so diffent to the abstract
927 * api level. Hence the intention is to remove this function
928 * & the associated param from viery_mandatory
930 * @param array $params Associative array of property name/value
931 * pairs to insert in new history.
933 * @param bool $return
935 * @daoName string DAO to check params agains
937 * @return bool should the missing fields be returned as an array (core error created as default)
939 * @return bool true if all fields present, depending on $result a core error is created of an array of missing fields is returned
942 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
943 //@deprecated - see notes
944 if (isset($params['extends'])) {
945 if (($params['extends'] == 'Activity' ||
946 $params['extends'] == 'Phonecall' ||
947 $params['extends'] == 'Meeting' ||
948 $params['extends'] == 'Group' ||
949 $params['extends'] == 'Contribution'
951 ($params['style'] == 'Tab')
953 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
957 $dao = new $daoName();
958 $fields = $dao->fields();
961 foreach ($fields as $k => $v) {
962 if ($v['name'] == 'id') {
966 if (!empty($v['required'])) {
967 // 0 is a valid input for numbers, CRM-8122
968 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
974 if (!empty($missing)) {
975 if (!empty($return)) {
979 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
987 * Check permissions for a given API call.
989 * @param $entity string API entity being accessed
990 * @param $action string API action being performed
991 * @param $params array params of the API call
992 * @param $throw deprecated bool whether to throw exception instead of returning false
995 * @return bool whether the current API user has the permission to make the call
997 function _civicrm_api3_api_check_permission($entity, $action, &$params, $throw = TRUE) {
998 // return early unless we’re told explicitly to do the permission check
999 if (empty($params['check_permissions']) or $params['check_permissions'] == FALSE) {
1003 require_once 'CRM/Core/DAO/permissions.php';
1004 $permissions = _civicrm_api3_permissions($entity, $action, $params);
1006 // $params might’ve been reset by the alterAPIPermissions() hook
1007 if (isset($params['check_permissions']) and $params['check_permissions'] == FALSE) {
1011 if (!CRM_Core_Permission
::check($permissions)) {
1013 if(is_array($permissions)) {
1014 $permissions = implode(' and ', $permissions);
1016 throw new Exception("API permission check failed for $entity/$action call; insufficient permission: require $permissions");
1019 //@todo remove this - this is an internal api function called with $throw set to TRUE. It is only called with false
1020 // in tests & that should be tidied up
1029 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this
1031 * @param string $bao_name name of BAO
1032 * @param array $params params from api
1033 * @param bool $returnAsSuccess return in api success format
1034 * @param string $entity
1038 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1039 $bao = new $bao_name();
1040 _civicrm_api3_dao_set_filter($bao, $params, TRUE, $entity);
1041 if ($returnAsSuccess) {
1042 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1045 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity);
1050 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this
1051 * @param string $bao_name Name of BAO Class
1052 * @param array $params parameters passed into the api call
1053 * @param string $entity Entity - pass in if entity is non-standard & required $ids array
1056 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1058 $args = array(&$params);
1059 if (!empty($entity)) {
1060 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1064 if (method_exists($bao_name, 'create')) {
1066 $fct_name = $bao_name . '::' . $fct;
1067 $bao = call_user_func_array(array($bao_name, $fct), $args);
1069 elseif (method_exists($bao_name, 'add')) {
1071 $fct_name = $bao_name . '::' . $fct;
1072 $bao = call_user_func_array(array($bao_name, $fct), $args);
1075 $fct_name = '_civicrm_api3_basic_create_fallback';
1076 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1079 if (is_null($bao)) {
1080 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1082 elseif (is_a($bao, 'CRM_Core_Error')) {
1083 //some wierd circular thing means the error takes itself as an argument
1084 $msg = $bao->getMessages($bao);
1085 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1086 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1087 // so we need to reset the error object here to avoid getting concatenated errors
1088 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1089 CRM_Core_Error
::singleton()->reset();
1090 throw new API_Exception($msg);
1094 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1095 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1100 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1102 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1103 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1105 * @param string $bao_name
1106 * @param array $params
1108 * @throws API_Exception
1109 * @return CRM_Core_DAO|NULL an instance of the BAO
1111 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1112 $dao_name = get_parent_class($bao_name);
1113 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1114 $dao_name = $bao_name;
1116 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1117 if (empty($entityName)) {
1118 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1119 'class_name' => $bao_name,
1122 $hook = empty($params['id']) ?
'create' : 'edit';
1124 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1125 $instance = new $dao_name();
1126 $instance->copyValues($params);
1128 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1134 * Function to do a 'standard' api del - when the api is only doing a $bao::del then use this
1135 * if api::del doesn't exist it will try DAO delete method
1137 function _civicrm_api3_basic_delete($bao_name, &$params) {
1139 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1140 $args = array(&$params['id']);
1141 if (method_exists($bao_name, 'del')) {
1142 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1143 if ($bao !== FALSE) {
1144 return civicrm_api3_create_success(TRUE);
1146 throw new API_Exception('Could not delete entity id ' . $params['id']);
1148 elseif (method_exists($bao_name, 'delete')) {
1149 $dao = new $bao_name();
1150 $dao->id
= $params['id'];
1152 while ($dao->fetch()) {
1154 return civicrm_api3_create_success();
1158 throw new API_Exception('Could not delete entity id ' . $params['id']);
1162 throw new API_Exception('no delete method found');
1166 * Get custom data for the given entity & Add it to the returnArray as 'custom_123' = 'custom string' AND 'custom_123_1' = 'custom string'
1167 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1169 * @param array $returnArray - array to append custom data too - generally $result[4] where 4 is the entity id.
1170 * @param string $entity e.g membership, event
1172 * @param int $groupID - per CRM_Core_BAO_CustomGroup::getTree
1173 * @param int $subType e.g. membership_type_id where custom data doesn't apply to all membership types
1174 * @param string $subName - Subtype of entity
1176 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1177 $groupTree = &CRM_Core_BAO_CustomGroup
::getTree($entity,
1178 CRM_Core_DAO
::$_nullObject,
1184 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1185 $customValues = array();
1186 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1187 if (!empty($customValues)) {
1188 foreach ($customValues as $key => $val) {
1189 if (strstr($key, '_id')) {
1190 $idkey = substr($key, 0, -3);
1191 $returnArray['custom_' . (CRM_Core_BAO_CustomField
::getKeyID($idkey) . "_id")] = $val;
1192 $returnArray[$key] = $val;
1195 // per standard - return custom_fieldID
1196 $returnArray['custom_' . (CRM_Core_BAO_CustomField
::getKeyID($key))] = $val;
1198 //not standard - but some api did this so guess we should keep - cheap as chips
1199 $returnArray[$key] = $val;
1206 * Validate fields being passed into API. This function relies on the getFields function working accurately
1207 * for the given API. If error mode is set to TRUE then it will also check
1210 * As of writing only date was implemented.
1211 * @param string $entity
1212 * @param string $action
1213 * @param array $params -
1214 * @param array $fields response from getfields all variables are the same as per civicrm_api
1215 * @param bool $errorMode errorMode do intensive post fail checks?
1218 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = False) {
1219 $fields = array_intersect_key($fields, $params);
1220 foreach ($fields as $fieldName => $fieldInfo) {
1221 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1222 case CRM_Utils_Type
::T_INT
:
1223 //field is of type integer
1224 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1229 //field is of type date or datetime
1230 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1234 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1237 case CRM_Utils_Type
::T_STRING
:
1238 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1241 case CRM_Utils_Type
::T_MONEY
:
1242 if (!CRM_Utils_Rule
::money($params[$fieldName]) && !empty($params[$fieldName])) {
1243 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1247 // intensive checks - usually only called after DB level fail
1248 if (!empty($errorMode) && strtolower($action) == 'create') {
1249 if (!empty($fieldInfo['FKClassName'])) {
1250 if (!empty($params[$fieldName])) {
1251 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1253 elseif (!empty($fieldInfo['required'])) {
1254 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1257 if (!empty($fieldInfo['api.unique'])) {
1258 $params['entity'] = $entity;
1259 _civicrm_api3_validate_uniquekey($params, $fieldName, $fieldInfo);
1266 * Validate date fields being passed into API.
1267 * It currently converts both unique fields and DB field names to a mysql date.
1268 * @todo - probably the unique field handling & the if exists handling is now done before this
1269 * function is reached in the wrapper - can reduce this code down to assume we
1270 * are only checking the passed in field
1272 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1273 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1275 * @param array $params params from civicrm_api
1276 * @param string $fieldName uniquename of field being checked
1279 * @internal param array $fieldinfo array of fields from getfields function
1281 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1282 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1283 if (!empty($params[$fieldInfo['name']])) {
1284 //accept 'whatever strtotime accepts
1285 if (strtotime($params[$fieldInfo['name']]) === FALSE) {
1286 throw new Exception($fieldInfo['name'] . " is not a valid date: " . $params[$fieldInfo['name']]);
1288 $params[$fieldInfo['name']] = CRM_Utils_Date
::processDate($params[$fieldInfo['name']]);
1290 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($params[$fieldName])) {
1291 //If the unique field name differs from the db name & is set handle it here
1292 if (strtotime($params[$fieldName]) === FALSE) {
1293 throw new Exception($fieldName . " is not a valid date: " . $params[$fieldName]);
1295 $params[$fieldName] = CRM_Utils_Date
::processDate($params[$fieldName]);
1300 * Validate foreign constraint fields being passed into API.
1302 * @param array $params params from civicrm_api
1303 * @param string $fieldName uniquename of field being checked
1306 * @internal param array $fieldinfo array of fields from getfields function
1308 function _civicrm_api3_validate_constraint(&$params, &$fieldName, &$fieldInfo) {
1309 $dao = new $fieldInfo['FKClassName'];
1310 $dao->id
= $params[$fieldName];
1312 $dao->selectAdd('id');
1313 if (!$dao->find()) {
1314 throw new Exception("$fieldName is not valid : " . $params[$fieldName]);
1319 * Validate foreign constraint fields being passed into API.
1321 * @param array $params params from civicrm_api
1322 * @param string $fieldName uniquename of field being checked
1325 * @internal param array $fieldinfo array of fields from getfields function
1327 function _civicrm_api3_validate_uniquekey(&$params, &$fieldName, &$fieldInfo) {
1328 $existing = civicrm_api($params['entity'], 'get', array(
1329 'version' => $params['version'],
1330 $fieldName => $params[$fieldName],
1332 // an entry already exists for this unique field
1333 if ($existing['count'] == 1) {
1334 // question - could this ever be a security issue?
1335 throw new Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1340 * Generic implementation of the "replace" action.
1342 * Replace the old set of entities (matching some given keys) with a new set of
1343 * entities (matching the same keys).
1345 * Note: This will verify that 'values' is present, but it does not directly verify
1346 * any other parameters.
1348 * @param string $entity entity name
1349 * @param array $params params from civicrm_api, including:
1350 * - 'values': an array of records to save
1351 * - all other items: keys which identify new/pre-existing records
1354 function _civicrm_api3_generic_replace($entity, $params) {
1356 $transaction = new CRM_Core_Transaction();
1358 if (!is_array($params['values'])) {
1359 throw new Exception("Mandatory key(s) missing from params array: values");
1362 // Extract the keys -- somewhat scary, don't think too hard about it
1363 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1365 // Lookup pre-existing records
1366 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1367 if (civicrm_error($preexisting)) {
1368 $transaction->rollback();
1369 return $preexisting;
1372 // Save the new/updated records
1374 foreach ($params['values'] as $replacement) {
1375 // Sugar: Don't force clients to duplicate the 'key' data
1376 $replacement = array_merge($baseParams, $replacement);
1377 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1378 $create = civicrm_api($entity, $action, $replacement);
1379 if (civicrm_error($create)) {
1380 $transaction->rollback();
1383 foreach ($create['values'] as $entity_id => $entity_value) {
1384 $creates[$entity_id] = $entity_value;
1388 // Remove stale records
1389 $staleIDs = array_diff(
1390 array_keys($preexisting['values']),
1391 array_keys($creates)
1393 foreach ($staleIDs as $staleID) {
1394 $delete = civicrm_api($entity, 'delete', array(
1395 'version' => $params['version'],
1398 if (civicrm_error($delete)) {
1399 $transaction->rollback();
1404 return civicrm_api3_create_success($creates, $params);
1406 catch(PEAR_Exception
$e) {
1407 $transaction->rollback();
1408 return civicrm_api3_create_error($e->getMessage());
1410 catch(Exception
$e) {
1411 $transaction->rollback();
1412 return civicrm_api3_create_error($e->getMessage());
1421 function _civicrm_api3_generic_replace_base_params($params) {
1422 $baseParams = $params;
1423 unset($baseParams['values']);
1424 unset($baseParams['sequential']);
1425 unset($baseParams['options']);
1430 * returns fields allowable by api
1432 * @param $entity string Entity to query
1433 * @param bool $unique index by unique fields?
1434 * @param array $params
1438 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1439 $unsetIfEmpty = array('dataPattern', 'headerPattern', 'default', 'export', 'import');
1440 $dao = _civicrm_api3_get_DAO($entity);
1445 $fields = $d->fields();
1446 // replace uniqueNames by the normal names as the key
1447 if (empty($unique)) {
1448 foreach ($fields as $name => & $field) {
1449 //getting rid of unused attributes
1450 foreach ($unsetIfEmpty as $attr) {
1451 if (empty($field[$attr])) {
1452 unset($field[$attr]);
1455 if ($name == $field['name']) {
1458 if (array_key_exists($field['name'], $fields)) {
1459 $field['error'] = 'name conflict';
1460 // it should never happen, but better safe than sorry
1463 $fields[$field['name']] = $field;
1464 $fields[$field['name']]['uniqueName'] = $name;
1465 unset($fields[$name]);
1468 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1473 * Return an array of fields for a given entity - this is the same as the BAO function but
1474 * fields are prefixed with 'custom_' to represent api params
1476 function _civicrm_api_get_custom_fields($entity, &$params) {
1477 $customfields = array();
1478 $entity = _civicrm_api_get_camel_name($entity);
1479 if (strtolower($entity) == 'contact') {
1480 // Use sub-type if available, otherwise stick with 'Contact'
1481 $entity = CRM_Utils_Array
::value('contact_type', $params);
1483 $retrieveOnlyParent = FALSE;
1484 // we could / should probably test for other subtypes here - e.g. activity_type_id
1485 if($entity == 'Contact'){
1486 empty($params['contact_sub_type']);
1488 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1491 CRM_Utils_Array
::value('contact_sub_type', $params, FALSE),
1493 $retrieveOnlyParent,
1497 // find out if we have any requests to resolve options
1498 $getoptions = CRM_Utils_Array
::value('get_options', CRM_Utils_Array
::value('options',$params));
1499 if(!is_array($getoptions)){
1500 $getoptions = array($getoptions);
1503 foreach ($customfields as $key => $value) {
1504 // Regular fields have a 'name' property
1505 $value['name'] = 'custom_' . $key;
1506 $value['type'] = _getStandardTypeFromCustomDataType($value['data_type']);
1507 $customfields['custom_' . $key] = $value;
1508 if (in_array('custom_' . $key, $getoptions)) {
1509 $customfields['custom_' . $key]['options'] = CRM_Core_BAO_CustomOption
::valuesByID($key);
1511 unset($customfields[$key]);
1513 return $customfields;
1516 * Translate the custom field data_type attribute into a std 'type'
1518 function _getStandardTypeFromCustomDataType($dataType) {
1520 'String' => CRM_Utils_Type
::T_STRING
,
1521 'Int' => CRM_Utils_Type
::T_INT
,
1522 'Money' => CRM_Utils_Type
::T_MONEY
,
1523 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1524 'Float' => CRM_Utils_Type
::T_FLOAT
,
1525 'Date' => CRM_Utils_Type
::T_DATE
,
1526 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1527 'StateProvince' => CRM_Utils_Type
::T_INT
,
1528 'File' => CRM_Utils_Type
::T_STRING
,
1529 'Link' => CRM_Utils_Type
::T_STRING
,
1530 'ContactReference' => CRM_Utils_Type
::T_INT
,
1531 'Country' => CRM_Utils_Type
::T_INT
,
1533 return $mapping[$dataType];
1536 * Return array of defaults for the given API (function is a wrapper on getfields)
1538 function _civicrm_api3_getdefaults($apiRequest, $fields) {
1539 $defaults = array();
1541 foreach ($fields as $field => $values) {
1542 if (isset($values['api.default'])) {
1543 $defaults[$field] = $values['api.default'];
1550 * Return array of defaults for the given API (function is a wrapper on getfields)
1552 function _civicrm_api3_getrequired($apiRequest, $fields) {
1553 $required = array('version');
1555 foreach ($fields as $field => $values) {
1556 if (!empty($values['api.required'])) {
1557 $required[] = $field;
1564 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't
1565 * If multiple aliases the last takes precedence
1567 * Function also swaps unique fields for non-unique fields & vice versa.
1569 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1570 foreach ($fields as $field => $values) {
1571 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1572 if (!empty($values['api.aliases'])) {
1573 // if aliased field is not set we try to use field alias
1574 if (!isset($apiRequest['params'][$field])) {
1575 foreach ($values['api.aliases'] as $alias) {
1576 if (isset($apiRequest['params'][$alias])) {
1577 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1579 //unset original field nb - need to be careful with this as it may bring inconsistencies
1580 // out of the woodwork but will be implementing only as _spec function extended
1581 unset($apiRequest['params'][$alias]);
1585 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
1586 && isset($apiRequest['params'][$values['name']])
1588 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1589 // note that it would make sense to unset the original field here but tests need to be in place first
1591 if (!isset($apiRequest['params'][$field])
1593 && $field != $uniqueName
1594 && array_key_exists($uniqueName, $apiRequest['params'])
1597 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1598 // note that it would make sense to unset the original field here but tests need to be in place first
1605 * Validate integer fields being passed into API.
1606 * It currently converts the incoming value 'user_contact_id' into the id of the currenty logged in user
1608 * @param array $params params from civicrm_api
1609 * @param string $fieldName uniquename of field being checked
1612 * @throws API_Exception
1613 * @internal param array $fieldinfo array of fields from getfields function
1615 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1616 //if fieldname exists in params
1617 if (!empty($params[$fieldName])) {
1618 // if value = 'user_contact_id' (or similar), replace value with contact id
1619 if (!is_numeric($params[$fieldName]) && is_scalar($params[$fieldName])) {
1620 $realContactId = _civicrm_api3_resolve_contactID($params[$fieldName]);
1621 if ('unknown-user' === $realContactId) {
1622 throw new API_Exception("\"$fieldName\" \"{$params[$fieldName]}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName,"type"=>"integer"));
1623 } elseif (is_numeric($realContactId)) {
1624 $params[$fieldName] = $realContactId;
1627 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1628 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1631 // After swapping options, ensure we have an integer(s)
1632 foreach ((array) ($params[$fieldName]) as $value) {
1633 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1634 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1638 // Check our field length
1639 if(is_string($params[$fieldName]) && !empty($fieldInfo['maxlength']) && strlen($params[$fieldName]) > $fieldInfo['maxlength']
1641 throw new API_Exception( $params[$fieldName] . " is " . strlen($params[$fieldName]) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1642 2100, array('field' => $fieldName, "max_length"=>$fieldInfo['maxlength'])
1649 * Determine a contact ID using a string expression
1651 * @param string $contactIdExpr e.g. "user_contact_id" or "@user:username"
1652 * @return int|NULL|'unknown-user'
1654 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1655 //if value = 'user_contact_id' replace value with logged in user id
1656 if ($contactIdExpr == "user_contact_id") {
1657 $session = &CRM_Core_Session
::singleton();
1658 if (!is_numeric($session->get('userID'))) {
1661 return $session->get('userID');
1662 } elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1663 $config = CRM_Core_Config
::singleton();
1665 $ufID = $config->userSystem
->getUfId($matches[1]);
1667 return 'unknown-user';
1670 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
1672 return 'unknown-user';
1681 * Validate html (check for scripting attack)
1686 * @throws API_Exception
1688 function _civicrm_api3_validate_html(&$params, &$fieldName, &$fieldInfo) {
1689 if ($value = CRM_Utils_Array
::value($fieldName, $params)) {
1690 if (!CRM_Utils_Rule
::xssString($value)) {
1691 throw new API_Exception('Illegal characters in input (potential scripting attack)', array("field"=>$fieldName,"error_code"=>"xss"));
1697 * Validate string fields being passed into API.
1698 * @param array $params params from civicrm_api
1699 * @param string $fieldName uniquename of field being checked
1702 * @throws API_Exception
1704 * @internal param array $fieldinfo array of fields from getfields function
1706 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
1707 // If fieldname exists in params
1708 $value = CRM_Utils_Array
::value($fieldName, $params, '');
1709 if(!is_array($value)){
1710 $value = (string) $value;
1713 //@todo what do we do about passed in arrays. For many of these fields
1714 // the missing piece of functionality is separating them to a separated string
1715 // & many save incorrectly. But can we change them wholesale?
1718 if (!CRM_Utils_Rule
::xssString($value)) {
1719 throw new Exception('Illegal characters in input (potential scripting attack)');
1721 if ($fieldName == 'currency') {
1722 if (!CRM_Utils_Rule
::currencyCode($value)) {
1723 throw new Exception("Currency not a valid code: $value");
1726 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1727 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1729 // Check our field length
1730 elseif (is_string($value) && !empty($fieldInfo['maxlength']) && strlen($value) > $fieldInfo['maxlength']) {
1731 throw new API_Exception("Value for $fieldName is " . strlen($value) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
1732 2100, array('field' => $fieldName)
1739 * Validate & swap out any pseudoconstants / options
1741 * @param $params: api parameters
1742 * @param $entity: api entity name
1743 * @param $fieldName: field name used in api call (not necessarily the canonical name)
1744 * @param $fieldInfo: getfields meta-data
1746 function _civicrm_api3_api_match_pseudoconstant(&$params, $entity, $fieldName, $fieldInfo) {
1747 $options = CRM_Utils_Array
::value('options', $fieldInfo);
1749 if(strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
1750 // we need to get the options from the entity the field relates to
1751 $entity = $fieldInfo['entity'];
1753 $options = civicrm_api($entity, 'getoptions', array('version' => 3, 'field' => $fieldInfo['name'], 'context' => 'validate'));
1754 $options = CRM_Utils_Array
::value('values', $options, array());
1757 // If passed a value-separated string, explode to an array, then re-implode after matching values
1759 if (is_string($params[$fieldName]) && strpos($params[$fieldName], CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
1760 $params[$fieldName] = CRM_Utils_Array
::explodePadded($params[$fieldName]);
1763 // If passed multiple options, validate each
1764 if (is_array($params[$fieldName])) {
1765 foreach ($params[$fieldName] as &$value) {
1766 if (!is_array($value)) {
1767 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
1770 // TODO: unwrap the call to implodePadded from the conditional and do it always
1771 // need to verify that this is safe and doesn't break anything though.
1772 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
1774 CRM_Utils_Array
::implodePadded($params[$fieldName]);
1778 _civicrm_api3_api_match_pseudoconstant_value($params[$fieldName], $options, $fieldName);
1783 * Validate & swap a single option value for a field
1785 * @param $value: field value
1786 * @param $options: array of options for this field
1787 * @param $fieldName: field name used in api call (not necessarily the canonical name)
1788 * @throws API_Exception
1790 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
1791 // If option is a key, no need to translate
1792 if (array_key_exists($value, $options)) {
1796 // Translate value into key
1797 $newValue = array_search($value, $options);
1798 if ($newValue !== FALSE) {
1802 // Case-insensitive matching
1803 $newValue = strtolower($value);
1804 $options = array_map("strtolower", $options);
1805 $newValue = array_search($newValue, $options);
1806 if ($newValue === FALSE) {
1807 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
1813 * Returns the canonical name of a field
1814 * @param $entity: api entity name (string should already be standardized - no camelCase)
1815 * @param $fieldName: any variation of a field's name (name, unique_name, api.alias)
1817 * @return (string|bool) fieldName or FALSE if the field does not exist
1819 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
1820 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
1823 if ($fieldName == "{$entity}_id") {
1826 $result = civicrm_api($entity, 'getfields', array(
1828 'action' => 'create',
1830 $meta = $result['values'];
1831 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
1832 $fieldName = $fieldName . '_id';
1834 if (isset($meta[$fieldName])) {
1835 return $meta[$fieldName]['name'];
1837 foreach ($meta as $info) {
1838 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
1839 return $info['name'];
1841 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
1842 return $info['name'];