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 list of required fields options. One of the options is required
55 * @return null or throws error if there the required fields not present
58 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = array(
60 $keys = array(array());
61 foreach ($keyoptions as $key) {
64 civicrm_api3_verify_mandatory($params, $daoName, $keys);
68 * Function to check mandatory fields are included
70 * @param array $params array of fields to check
71 * @param array $daoName string DAO to check for required fields (create functions only)
72 * @param array $keys list of required fields. A value can be an array denoting that either this or that is required.
73 * @param bool $verifyDAO
75 * @throws API_Exception
76 * @return null or throws error if there the required fields not present
78 * @todo see notes on _civicrm_api3_check_required_fields regarding removing $daoName param
80 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = array(
81 ), $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']) && CRM_Utils_Array
::value('api.has_parent', $dao['params'])) {
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(
184 ), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
186 $result['is_error'] = 0;
187 //lets set the ['id'] field if it's not set & we know what the entity is
188 if (is_array($values) && !empty($entity)) {
189 foreach ($values as $key => $item) {
190 if (empty($item['id']) && !empty($item[$entity . "_id"])) {
191 $values[$key]['id'] = $item[$entity . "_id"];
193 if(!empty($item['financial_type_id'])){
194 //4.3 legacy handling
195 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
197 if(!empty($item['next_sched_contribution_date'])){
198 // 4.4 legacy handling
199 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
204 if (is_array($params) && !empty($params['debug'])) {
205 if (is_string($action) && $action != 'getfields') {
206 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) +
$params);
208 elseif ($action != 'getfields') {
209 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
215 $allFields = array();
216 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
217 $allFields = array_keys($apiFields['values']);
219 $paramFields = array_keys($params);
220 $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'));
222 $result['undefined_fields'] = array_merge($undefined);
225 if (is_object($dao)) {
229 $result['version'] = 3;
230 if (is_array($values)) {
231 $result['count'] = (int) count($values);
233 // Convert value-separated strings to array
234 _civicrm_api3_separate_values($values);
236 if ($result['count'] == 1) {
237 list($result['id']) = array_keys($values);
239 elseif (!empty($values['id']) && is_int($values['id'])) {
240 $result['id'] = $values['id'];
244 $result['count'] = !empty($values) ?
1 : 0;
247 if (is_array($values) && isset($params['sequential']) &&
248 $params['sequential'] == 1
250 $result['values'] = array_values($values);
253 $result['values'] = $values;
255 if(!empty($params['options']['metadata'])) {
256 // we've made metadata an array but only supporting 'fields' atm
257 if(in_array('fields', $params['options']['metadata'])) {
258 $fields = civicrm_api3($entity, 'getfields', array('action' => $action));
259 $result['metadata']['fields'] = $fields['values'];
262 return array_merge($result, $extraReturnValues);
266 * Load the DAO of the entity
268 function _civicrm_api3_load_DAO($entity) {
269 $dao = _civicrm_api3_get_DAO($entity);
278 * Function to return the DAO of the function or Entity
279 * @param String $name either a function of the api (civicrm_{entity}_create or the entity name
280 * return the DAO name to manipulate this function
281 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
282 * @return mixed|string
284 function _civicrm_api3_get_DAO($name) {
285 if (strpos($name, 'civicrm_api3') !== FALSE) {
286 $last = strrpos($name, '_');
287 // len ('civicrm_api3_') == 13
288 $name = substr($name, 13, $last - 13);
291 $name = _civicrm_api_get_camel_name($name, 3);
293 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
297 //hack to deal with incorrectly named BAO/DAO - see CRM-10859 -
298 // several of these have been removed but am not confident mailing_recipients is
299 // tests so have not tackled.
300 // correct approach for im is unclear
301 if($name == 'mailing_recipients' ||
$name == 'MailingRecipients'){
302 return 'CRM_Mailing_BAO_Recipients';
304 if(strtolower($name) == 'im'){
305 return 'CRM_Core_BAO_IM';
307 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
308 if ($dao ||
!$name) {
312 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
313 if(file_exists("api/v3/$name.php")) {
314 include_once "api/v3/$name.php";
316 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
317 if (function_exists($daoFn)) {
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 $dao = _civicrm_api3_get_DAO($name);
336 $bao = str_replace("DAO", "BAO", $dao);
337 $file = strtr($bao, '_', '/') . '.php';
338 // Check if this entity actually has a BAO. Fall back on the DAO if not.
339 return stream_resolve_include_path($file) ?
$bao : $dao;
343 * Recursive function to explode value-separated strings into arrays
346 function _civicrm_api3_separate_values(&$values) {
347 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
348 foreach ($values as $key => & $value) {
349 if (is_array($value)) {
350 _civicrm_api3_separate_values($value);
352 elseif (is_string($value)) {
353 if($key == 'case_type_id'){// this is to honor the way case API was originally written
354 $value = trim(str_replace($sp, ',', $value), ',');
356 elseif (strpos($value, $sp) !== FALSE) {
357 $value = explode($sp, trim($value, $sp));
364 * This is a legacy wrapper for api_store_values which will check the suitable fields using getfields
365 * rather than DAO->fields
367 * Getfields has handling for how to deal with uniquenames which dao->fields doesn't
369 * Note this is used by BAO type create functions - eg. contribution
370 * @param string $entity
371 * @param array $params
372 * @param array $values
374 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values){
375 $fields = civicrm_api($entity,'getfields', array('version' => 3,'action' => 'create'));
376 $fields = $fields['values'];
377 _civicrm_api3_store_values($fields, $params, $values);
381 * @param array $fields
382 * @param array $params
383 * @param array $values
385 * @return Bool $valueFound
387 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
390 $keys = array_intersect_key($params, $fields);
391 foreach ($keys as $name => $value) {
392 if ($name !== 'id') {
393 $values[$name] = $value;
401 * The API supports 2 types of get requestion. The more complex uses the BAO query object.
402 * This is a generic function for those functions that call it
404 * At the moment only called by contact we should extend to contribution &
405 * others that use the query object. Note that this function passes permission information in.
408 * * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
411 * @param array $params as passed into api get or getcount function
412 * @param array $additional_options array of options (so we can modify the filter)
413 * @param bool $getCount are we just after the count
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 = CRM_Utils_Array
::value('check_permissions', $params)?
0 :1;
480 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
491 if ($getCount) { // only return the count of contacts
499 * get dao query object based on input params
500 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
503 * @param array $params
504 * @param string $mode
505 * @param string $entity
506 * @return CRM_Core_DAO query object
508 function _civicrm_api3_get_query_object($params, $mode, $entity) {
509 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
510 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
511 $offset = CRM_Utils_Array
::value('offset', $options);
512 $rowCount = CRM_Utils_Array
::value('limit', $options);
513 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
514 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
515 if (empty($returnProperties)) {
516 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
519 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
520 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
522 empty($params['check_permissions'])
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);
572 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
573 // support for other syntaxes is discussed in ticket but being put off for now
574 $acceptedSQLOperators = array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN');
579 foreach ($fields as $field) {
580 if (is_array($params[$field])) {
581 //get the actual fieldname from db
582 $fieldName = $allfields[$field]['name'];
583 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
585 $dao->whereAdd($where);
590 $daoFieldName = $allfields[$field]['name'];
591 if (empty($daoFieldName)) {
592 throw new API_Exception("Failed to determine field name for \"$field\"");
594 $dao->{$daoFieldName} = $params[$field];
597 $dao->$field = $params[$field];
601 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
603 $options['return']['id'] = TRUE;// ensure 'id' is included
604 $allfields = _civicrm_api3_get_unique_name_array($dao);
605 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
606 foreach ($returnMatched as $returnValue) {
607 $dao->selectAdd($returnValue);
610 $unmatchedFields = array_diff(// not already matched on the field names
611 array_keys($options['return']),
615 $returnUniqueMatched = array_intersect(
617 array_flip($allfields)// but a match for the field keys
619 foreach ($returnUniqueMatched as $uniqueVal){
620 $dao->selectAdd($allfields[$uniqueVal]);
623 $dao->setApiFilter($params);
627 * Apply filters (e.g. high, low) to DAO object (prior to find)
628 * @param string $filterField field name of filter
629 * @param string $filterValue field value of filter
630 * @param object $dao DAO object
632 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
633 if (strstr($filterField, 'high')) {
634 $fieldName = substr($filterField, 0, -5);
635 $dao->whereAdd("($fieldName <= $filterValue )");
637 if (strstr($filterField, 'low')) {
638 $fieldName = substr($filterField, 0, -4);
639 $dao->whereAdd("($fieldName >= $filterValue )");
641 if($filterField == 'is_current' && $filterValue == 1){
642 $todayStart = date('Ymd000000', strtotime('now'));
643 $todayEnd = date('Ymd235959', strtotime('now'));
644 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
645 if(property_exists($dao, 'is_active')){
646 $dao->whereAdd('is_active = 1');
652 * Get sort, limit etc options from the params - supporting old & new formats.
653 * get returnproperties for legacy
655 * @param array $params params array as passed into civicrm_api
656 * @param bool $queryObject - is this supporting a queryobject api (e.g contact) - if so we support more options
657 * for legacy report & return a unique fields array
659 * @param string $entity
660 * @param string $action
662 * @return array $options options extracted from params
664 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
666 $sort = CRM_Utils_Array
::value('sort', $params, 0);
667 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
668 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
670 $offset = CRM_Utils_Array
::value('offset', $params, 0);
671 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
672 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
673 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
675 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
676 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
677 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
679 if (is_array(CRM_Utils_Array
::value('options', $params))) {
680 // is count is set by generic getcount not user
681 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
682 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
683 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
684 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
687 $returnProperties = array();
688 // handle the format return =sort_name,display_name...
689 if (array_key_exists('return', $params)) {
690 if (is_array($params['return'])) {
691 $returnProperties = array_fill_keys($params['return'], 1);
694 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
695 $returnProperties = array_fill_keys($returnProperties, 1);
698 if ($entity && $action =='get') {
699 if (CRM_Utils_Array
::value('id',$returnProperties)) {
700 $returnProperties[$entity . '_id'] = 1;
701 unset($returnProperties['id']);
703 switch (trim(strtolower($sort))){
707 $sort = str_replace('id', $entity . '_id',$sort);
712 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
713 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
714 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
715 'is_count' => $is_count,
716 'return' => !empty($returnProperties) ?
$returnProperties : NULL,
719 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
720 throw new API_Exception('invalid string in sort options');
726 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
727 // if the queryobject is being used this should be used
728 $inputParams = array();
729 $legacyreturnProperties = array();
731 'sort', 'offset', 'rowCount', 'options','return',
733 foreach ($params as $n => $v) {
734 if (substr($n, 0, 7) == 'return.') {
735 $legacyreturnProperties[substr($n, 7)] = $v;
737 elseif ($n == 'id') {
738 $inputParams[$entity. '_id'] = $v;
740 elseif (in_array($n, $otherVars)) {}
742 $inputParams[$n] = $v;
743 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
744 throw new API_Exception('invalid string');
748 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
749 $options['input_params'] = $inputParams;
754 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find)
756 * @param array $params params array as passed into civicrm_api
757 * @param object $dao DAO object
760 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
762 $options = _civicrm_api3_get_options_from_params($params,FALSE,$entity);
763 if(!$options['is_count']) {
764 if(!empty($options['limit'])) {
765 $dao->limit((int)$options['offset'], (int)$options['limit']);
767 if (!empty($options['sort'])) {
768 $dao->orderBy($options['sort']);
774 * build fields array. This is the array of fields as it relates to the given DAO
775 * returns unique fields as keys by default but if set but can return by DB fields
777 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
778 $fields = $bao->fields();
780 if(!CRM_Utils_Array
::value('id', $fields)){
781 $entity = _civicrm_api_get_entity_name_from_dao($bao);
782 $fields['id'] = $fields[$entity . '_id'];
783 unset($fields[$entity . '_id']);
788 foreach ($fields as $field) {
789 $dbFields[$field['name']] = $field;
795 * build fields array. This is the array of fields as it relates to the given DAO
796 * returns unique fields as keys by default but if set but can return by DB fields
798 function _civicrm_api3_get_unique_name_array(&$bao) {
799 $fields = $bao->fields();
800 foreach ($fields as $field => $values) {
801 $uniqueFields[$field] = CRM_Utils_Array
::value('name',$values, $field);
803 return $uniqueFields;
807 * Converts an DAO object to an array
809 * @param object $dao (reference )object to convert
810 * @param null $params
811 * @param bool $uniqueFields
812 * @param string $entity
816 * @params array of arrays (key = id) of array of fields
821 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
823 if(isset($params['options']) && CRM_Utils_Array
::value('is_count', $params['options'])) {
824 return $dao->count();
829 if ($autoFind && !$dao->find()) {
833 if(isset($dao->count
)) {
836 //if custom fields are required we will endeavour to set them . NB passing $entity in might be a bit clunky / unrequired
837 if (!empty($entity) && CRM_Utils_Array
::value('return', $params) && is_array($params['return'])) {
838 foreach ($params['return'] as $return) {
839 if (substr($return, 0, 6) == 'custom') {
846 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
848 while ($dao->fetch()) {
850 foreach ($fields as $key) {
851 if (array_key_exists($key, $dao)) {
852 // not sure on that one
853 if ($dao->$key !== NULL) {
854 $tmp[$key] = $dao->$key;
858 $result[$dao->id
] = $tmp;
859 if (!empty($custom)) {
860 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
869 * Converts an object to an array
871 * @param object $dao (reference) object to convert
872 * @param array $values (reference) array
873 * @param array|bool $uniqueFields
879 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
881 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
882 foreach ($fields as $key => $value) {
883 if (array_key_exists($key, $dao)) {
884 $values[$key] = $dao->$key;
890 * Wrapper for _civicrm_object_to_array when api supports unique fields
892 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
893 return _civicrm_api3_object_to_array($dao, $values, TRUE);
898 * @param array $params
899 * @param array $values
900 * @param string $extends entity that this custom field extends (e.g. contribution, event, contact)
901 * @param string $entityId ID of entity per $extends
903 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
904 $values['custom'] = array();
905 $checkCheckBoxField = FALSE;
907 if(in_array($extends, array('Household', 'Individual', 'Organization'))) {
911 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
912 if(!$fields['is_error']) {
913 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
914 $fields = $fields['values'];
915 $checkCheckBoxField = TRUE;
918 foreach ($params as $key => $value) {
919 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
920 if ($customFieldID && (!IS_NULL($value))) {
921 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
922 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
924 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
925 $value, $extends, $customValueID, $entityId, FALSE, FALSE
932 * we can't rely on downstream to add separators to checkboxes so we'll check here. We should look at pushing to BAO function
933 * and / or validate function but this is a safe place for now as it has massive test coverage & we can keep the change very specific
934 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
936 * We will only alter the value if we are sure that changing it will make it correct - if it appears wrong but does not appear to have a clear fix we
937 * don't touch - lots of very cautious code in here
939 * The resulting array should look like
945 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
947 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
950 * @param $checkboxFieldValue
951 * @param $customFieldLabel
955 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
957 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
958 // we can assume it's pre-formatted
961 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
962 if (!empty($options['is_error'])) {
963 //the check is precautionary - can probably be removed later
967 $options = $options['values'];
969 if (is_array($checkboxFieldValue)) {
970 foreach ($checkboxFieldValue as $key => $value) {
971 if (!array_key_exists($key, $options)) {
976 // we have been passed an array that is already in the 'odd' custom field format
981 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
982 // if the array only has one item we'll treat it like any other string
983 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
984 $possibleValue = reset($checkboxFieldValue);
986 if (is_string($checkboxFieldValue)) {
987 $possibleValue = $checkboxFieldValue;
989 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
990 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
993 elseif (is_array($checkboxFieldValue)) {
994 // so this time around we are considering the values in the array
995 $possibleValues = $checkboxFieldValue;
998 elseif (stristr($checkboxFieldValue, ',')) {
1000 //lets see if we should separate it - we do this near the end so we
1001 // ensure we have already checked that the comma is not part of a legitimate match
1002 // and of course, we don't make any changes if we don't now have matches
1003 $possibleValues = explode(',', $checkboxFieldValue);
1006 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1010 foreach ($possibleValues as $index => $possibleValue) {
1011 if (array_key_exists($possibleValue, $options)) {
1012 // do nothing - we will leave formatValue set to true unless another value is not found (which would cause us to ignore the whole value set)
1014 elseif (array_key_exists(trim($possibleValue), $options)) {
1015 $possibleValues[$index] = trim($possibleValue);
1018 $formatValue = FALSE;
1022 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1028 * This function ensures that we have the right input parameters
1030 * This function is only called when $dao is passed into verify_mandatory.
1031 * The practice of passing $dao into verify_mandatory turned out to be
1032 * unsatisfactory as the required fields @ the dao level is so diffent to the abstract
1033 * api level. Hence the intention is to remove this function
1034 * & the associated param from viery_mandatory
1036 * @param array $params Associative array of property name/value
1037 * pairs to insert in new history.
1039 * @param bool $return
1041 * @daoName string DAO to check params agains
1043 * @return bool should the missing fields be returned as an array (core error created as default)
1045 * @return bool true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1048 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1049 //@deprecated - see notes
1050 if (isset($params['extends'])) {
1051 if (($params['extends'] == 'Activity' ||
1052 $params['extends'] == 'Phonecall' ||
1053 $params['extends'] == 'Meeting' ||
1054 $params['extends'] == 'Group' ||
1055 $params['extends'] == 'Contribution'
1057 ($params['style'] == 'Tab')
1059 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1063 $dao = new $daoName();
1064 $fields = $dao->fields();
1067 foreach ($fields as $k => $v) {
1068 if ($v['name'] == 'id') {
1072 if (CRM_Utils_Array
::value('required', $v)) {
1073 // 0 is a valid input for numbers, CRM-8122
1074 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1080 if (!empty($missing)) {
1081 if (!empty($return)) {
1085 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1093 * Check permissions for a given API call.
1095 * @param $entity string API entity being accessed
1096 * @param $action string API action being performed
1097 * @param $params array params of the API call
1098 * @param $throw deprecated bool whether to throw exception instead of returning false
1101 * @return bool whether the current API user has the permission to make the call
1103 function _civicrm_api3_api_check_permission($entity, $action, &$params, $throw = TRUE) {
1104 // return early unless we’re told explicitly to do the permission check
1105 if (empty($params['check_permissions']) or $params['check_permissions'] == FALSE) {
1109 require_once 'CRM/Core/DAO/permissions.php';
1110 $permissions = _civicrm_api3_permissions($entity, $action, $params);
1112 // $params might’ve been reset by the alterAPIPermissions() hook
1113 if (isset($params['check_permissions']) and $params['check_permissions'] == FALSE) {
1117 if (!CRM_Core_Permission
::check($permissions)) {
1119 if(is_array($permissions)) {
1120 $permissions = implode(' and ', $permissions);
1122 throw new Exception("API permission check failed for $entity/$action call; insufficient permission: require $permissions");
1125 //@todo remove this - this is an internal api function called with $throw set to TRUE. It is only called with false
1126 // in tests & that should be tidied up
1135 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this
1137 * @param string $bao_name name of BAO
1138 * @param array $params params from api
1139 * @param bool $returnAsSuccess return in api success format
1140 * @param string $entity
1144 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1145 $bao = new $bao_name();
1146 _civicrm_api3_dao_set_filter($bao, $params, TRUE, $entity);
1147 if ($returnAsSuccess) {
1148 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1151 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity);
1156 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this
1157 * @param string $bao_name Name of BAO Class
1158 * @param array $params parameters passed into the api call
1159 * @param string $entity Entity - pass in if entity is non-standard & required $ids array
1162 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1164 $args = array(&$params);
1165 if (!empty($entity)) {
1166 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1170 if (method_exists($bao_name, 'create')) {
1172 $fct_name = $bao_name . '::' . $fct;
1173 $bao = call_user_func_array(array($bao_name, $fct), $args);
1175 elseif (method_exists($bao_name, 'add')) {
1177 $fct_name = $bao_name . '::' . $fct;
1178 $bao = call_user_func_array(array($bao_name, $fct), $args);
1181 $fct_name = '_civicrm_api3_basic_create_fallback';
1182 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1185 if (is_null($bao)) {
1186 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1188 elseif (is_a($bao, 'CRM_Core_Error')) {
1189 //some wierd circular thing means the error takes itself as an argument
1190 $msg = $bao->getMessages($bao);
1191 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1192 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1193 // so we need to reset the error object here to avoid getting concatenated errors
1194 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1195 CRM_Core_Error
::singleton()->reset();
1196 throw new API_Exception($msg);
1200 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1201 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1206 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1208 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1209 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1211 * @param string $bao_name
1212 * @param array $params
1214 * @throws API_Exception
1215 * @return CRM_Core_DAO|NULL an instance of the BAO
1217 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1218 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName(get_parent_class($bao_name));
1219 if (empty($entityName)) {
1220 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1221 'class_name' => $bao_name,
1224 $hook = empty($params['id']) ?
'create' : 'edit';
1226 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1227 $instance = new $bao_name();
1228 $instance->copyValues($params);
1230 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1236 * Function to do a 'standard' api del - when the api is only doing a $bao::del then use this
1237 * if api::del doesn't exist it will try DAO delete method
1239 function _civicrm_api3_basic_delete($bao_name, &$params) {
1241 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1242 $args = array(&$params['id']);
1243 if (method_exists($bao_name, 'del')) {
1244 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1245 if ($bao !== FALSE) {
1246 return civicrm_api3_create_success(TRUE);
1248 throw new API_Exception('Could not delete entity id ' . $params['id']);
1250 elseif (method_exists($bao_name, 'delete')) {
1251 $dao = new $bao_name();
1252 $dao->id
= $params['id'];
1254 while ($dao->fetch()) {
1256 return civicrm_api3_create_success();
1260 throw new API_Exception('Could not delete entity id ' . $params['id']);
1264 throw new API_Exception('no delete method found');
1268 * Get custom data for the given entity & Add it to the returnArray as 'custom_123' = 'custom string' AND 'custom_123_1' = 'custom string'
1269 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1271 * @param array $returnArray - array to append custom data too - generally $result[4] where 4 is the entity id.
1272 * @param string $entity e.g membership, event
1274 * @param int $groupID - per CRM_Core_BAO_CustomGroup::getTree
1275 * @param int $subType e.g. membership_type_id where custom data doesn't apply to all membership types
1276 * @param string $subName - Subtype of entity
1278 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1279 $groupTree = &CRM_Core_BAO_CustomGroup
::getTree($entity,
1280 CRM_Core_DAO
::$_nullObject,
1286 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1287 $customValues = array();
1288 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1289 if (!empty($customValues)) {
1290 foreach ($customValues as $key => $val) {
1291 if (strstr($key, '_id')) {
1292 $idkey = substr($key, 0, -3);
1293 $returnArray['custom_' . (CRM_Core_BAO_CustomField
::getKeyID($idkey) . "_id")] = $val;
1294 $returnArray[$key] = $val;
1297 // per standard - return custom_fieldID
1298 $returnArray['custom_' . (CRM_Core_BAO_CustomField
::getKeyID($key))] = $val;
1300 //not standard - but some api did this so guess we should keep - cheap as chips
1301 $returnArray[$key] = $val;
1308 * Validate fields being passed into API. This function relies on the getFields function working accurately
1309 * for the given API. If error mode is set to TRUE then it will also check
1312 * As of writing only date was implemented.
1313 * @param string $entity
1314 * @param string $action
1315 * @param array $params -
1316 * @param array $fields response from getfields all variables are the same as per civicrm_api
1317 * @param bool $errorMode errorMode do intensive post fail checks?
1320 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = False) {
1321 $fields = array_intersect_key($fields, $params);
1322 foreach ($fields as $fieldName => $fieldInfo) {
1323 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1324 case CRM_Utils_Type
::T_INT
:
1325 //field is of type integer
1326 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1331 //field is of type date or datetime
1332 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1336 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1339 case CRM_Utils_Type
::T_STRING
:
1340 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1343 case CRM_Utils_Type
::T_MONEY
:
1344 if (!CRM_Utils_Rule
::money($params[$fieldName]) && !empty($params[$fieldName])) {
1345 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1349 // intensive checks - usually only called after DB level fail
1350 if (!empty($errorMode) && strtolower($action) == 'create') {
1351 if (CRM_Utils_Array
::value('FKClassName', $fieldInfo)) {
1352 if (CRM_Utils_Array
::value($fieldName, $params)) {
1353 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1355 elseif (CRM_Utils_Array
::value('required', $fieldInfo)) {
1356 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1359 if (CRM_Utils_Array
::value('api.unique', $fieldInfo)) {
1360 $params['entity'] = $entity;
1361 _civicrm_api3_validate_uniquekey($params, $fieldName, $fieldInfo);
1368 * Validate date fields being passed into API.
1369 * It currently converts both unique fields and DB field names to a mysql date.
1370 * @todo - probably the unique field handling & the if exists handling is now done before this
1371 * function is reached in the wrapper - can reduce this code down to assume we
1372 * are only checking the passed in field
1374 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1375 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1377 * @param array $params params from civicrm_api
1378 * @param string $fieldName uniquename of field being checked
1379 * @param array $fieldInfo array of fields from getfields function
1382 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1383 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1384 if (CRM_Utils_Array
::value($fieldInfo['name'], $params)) {
1385 //accept 'whatever strtotime accepts
1386 if (strtotime($params[$fieldInfo['name']]) === FALSE) {
1387 throw new Exception($fieldInfo['name'] . " is not a valid date: " . $params[$fieldInfo['name']]);
1389 $format = ($fieldInfo['type'] == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1390 $params[$fieldInfo['name']] = CRM_Utils_Date
::processDate($params[$fieldInfo['name']], NULL, FALSE, $format);
1392 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && CRM_Utils_Array
::value($fieldName, $params)) {
1393 //If the unique field name differs from the db name & is set handle it here
1394 if (strtotime($params[$fieldName]) === FALSE) {
1395 throw new Exception($fieldName . " is not a valid date: " . $params[$fieldName]);
1397 $params[$fieldName] = CRM_Utils_Date
::processDate($params[$fieldName]);
1402 * Validate foreign constraint fields being passed into API.
1404 * @param array $params params from civicrm_api
1405 * @param string $fieldName uniquename of field being checked
1406 * @param array $fieldInfo array of fields from getfields function
1409 function _civicrm_api3_validate_constraint(&$params, &$fieldName, &$fieldInfo) {
1410 $dao = new $fieldInfo['FKClassName'];
1411 $dao->id
= $params[$fieldName];
1413 $dao->selectAdd('id');
1414 if (!$dao->find()) {
1415 throw new Exception("$fieldName is not valid : " . $params[$fieldName]);
1420 * Validate foreign constraint fields being passed into API.
1422 * @param array $params params from civicrm_api
1423 * @param string $fieldName uniquename of field being checked
1424 * @param $fieldInfo array of fields from getfields function
1427 function _civicrm_api3_validate_uniquekey(&$params, &$fieldName, &$fieldInfo) {
1428 $existing = civicrm_api($params['entity'], 'get', array(
1429 'version' => $params['version'],
1430 $fieldName => $params[$fieldName],
1432 // an entry already exists for this unique field
1433 if ($existing['count'] == 1) {
1434 // question - could this ever be a security issue?
1435 throw new Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1440 * Generic implementation of the "replace" action.
1442 * Replace the old set of entities (matching some given keys) with a new set of
1443 * entities (matching the same keys).
1445 * Note: This will verify that 'values' is present, but it does not directly verify
1446 * any other parameters.
1448 * @param string $entity entity name
1449 * @param array $params params from civicrm_api, including:
1450 * - 'values': an array of records to save
1451 * - all other items: keys which identify new/pre-existing records
1454 function _civicrm_api3_generic_replace($entity, $params) {
1456 $transaction = new CRM_Core_Transaction();
1458 if (!is_array($params['values'])) {
1459 throw new Exception("Mandatory key(s) missing from params array: values");
1462 // Extract the keys -- somewhat scary, don't think too hard about it
1463 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1465 // Lookup pre-existing records
1466 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1467 if (civicrm_error($preexisting)) {
1468 $transaction->rollback();
1469 return $preexisting;
1472 // Save the new/updated records
1474 foreach ($params['values'] as $replacement) {
1475 // Sugar: Don't force clients to duplicate the 'key' data
1476 $replacement = array_merge($baseParams, $replacement);
1477 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1478 $create = civicrm_api($entity, $action, $replacement);
1479 if (civicrm_error($create)) {
1480 $transaction->rollback();
1483 foreach ($create['values'] as $entity_id => $entity_value) {
1484 $creates[$entity_id] = $entity_value;
1488 // Remove stale records
1489 $staleIDs = array_diff(
1490 array_keys($preexisting['values']),
1491 array_keys($creates)
1493 foreach ($staleIDs as $staleID) {
1494 $delete = civicrm_api($entity, 'delete', array(
1495 'version' => $params['version'],
1498 if (civicrm_error($delete)) {
1499 $transaction->rollback();
1504 return civicrm_api3_create_success($creates, $params);
1506 catch(PEAR_Exception
$e) {
1507 $transaction->rollback();
1508 return civicrm_api3_create_error($e->getMessage());
1510 catch(Exception
$e) {
1511 $transaction->rollback();
1512 return civicrm_api3_create_error($e->getMessage());
1521 function _civicrm_api3_generic_replace_base_params($params) {
1522 $baseParams = $params;
1523 unset($baseParams['values']);
1524 unset($baseParams['sequential']);
1525 unset($baseParams['options']);
1530 * returns fields allowable by api
1532 * @param $entity string Entity to query
1533 * @param bool $unique index by unique fields?
1534 * @param array $params
1538 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array(
1540 $unsetIfEmpty = array('dataPattern', 'headerPattern', 'default', 'export', 'import');
1541 $dao = _civicrm_api3_get_DAO($entity);
1546 $fields = $d->fields();
1547 // replace uniqueNames by the normal names as the key
1548 if (empty($unique)) {
1549 foreach ($fields as $name => & $field) {
1550 //getting rid of unused attributes
1551 foreach ($unsetIfEmpty as $attr) {
1552 if (empty($field[$attr])) {
1553 unset($field[$attr]);
1556 if ($name == $field['name']) {
1559 if (array_key_exists($field['name'], $fields)) {
1560 $field['error'] = 'name conflict';
1561 // it should never happen, but better safe than sorry
1564 $fields[$field['name']] = $field;
1565 $fields[$field['name']]['uniqueName'] = $name;
1566 unset($fields[$name]);
1569 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1574 * Return an array of fields for a given entity - this is the same as the BAO function but
1575 * fields are prefixed with 'custom_' to represent api params
1577 function _civicrm_api_get_custom_fields($entity, &$params) {
1578 $customfields = array();
1579 $entity = _civicrm_api_get_camel_name($entity);
1580 if (strtolower($entity) == 'contact') {
1581 // Use sub-type if available, otherwise stick with 'Contact'
1582 $entity = CRM_Utils_Array
::value('contact_type', $params);
1584 $retrieveOnlyParent = FALSE;
1585 // we could / should probably test for other subtypes here - e.g. activity_type_id
1586 if($entity == 'Contact'){
1587 empty($params['contact_sub_type']);
1589 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1592 CRM_Utils_Array
::value('contact_sub_type', $params, FALSE),
1594 $retrieveOnlyParent,
1598 // find out if we have any requests to resolve options
1599 $getoptions = CRM_Utils_Array
::value('get_options', CRM_Utils_Array
::value('options',$params));
1600 if(!is_array($getoptions)){
1601 $getoptions = array($getoptions);
1604 foreach ($customfields as $key => $value) {
1605 // Regular fields have a 'name' property
1606 $value['name'] = 'custom_' . $key;
1607 $value['type'] = _getStandardTypeFromCustomDataType($value['data_type']);
1608 $customfields['custom_' . $key] = $value;
1609 if (in_array('custom_' . $key, $getoptions)) {
1610 $customfields['custom_' . $key]['options'] = CRM_Core_BAO_CustomOption
::valuesByID($key);
1612 unset($customfields[$key]);
1614 return $customfields;
1617 * Translate the custom field data_type attribute into a std 'type'
1619 function _getStandardTypeFromCustomDataType($dataType) {
1621 'String' => CRM_Utils_Type
::T_STRING
,
1622 'Int' => CRM_Utils_Type
::T_INT
,
1623 'Money' => CRM_Utils_Type
::T_MONEY
,
1624 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1625 'Float' => CRM_Utils_Type
::T_FLOAT
,
1626 'Date' => CRM_Utils_Type
::T_DATE
,
1627 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1628 'StateProvince' => CRM_Utils_Type
::T_INT
,
1629 'File' => CRM_Utils_Type
::T_STRING
,
1630 'Link' => CRM_Utils_Type
::T_STRING
,
1631 'ContactReference' => CRM_Utils_Type
::T_INT
,
1632 'Country' => CRM_Utils_Type
::T_INT
,
1634 return $mapping[$dataType];
1637 * Return array of defaults for the given API (function is a wrapper on getfields)
1639 function _civicrm_api3_getdefaults($apiRequest, $fields) {
1640 $defaults = array();
1642 foreach ($fields as $field => $values) {
1643 if (isset($values['api.default'])) {
1644 $defaults[$field] = $values['api.default'];
1651 * Return array of defaults for the given API (function is a wrapper on getfields)
1653 function _civicrm_api3_getrequired($apiRequest, $fields) {
1654 $required = array('version');
1656 foreach ($fields as $field => $values) {
1657 if (CRM_Utils_Array
::value('api.required', $values)) {
1658 $required[] = $field;
1665 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't
1666 * If multiple aliases the last takes precedence
1668 * Function also swaps unique fields for non-unique fields & vice versa.
1670 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1671 foreach ($fields as $field => $values) {
1672 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1673 if (CRM_Utils_Array
::value('api.aliases', $values)) {
1674 // if aliased field is not set we try to use field alias
1675 if (!isset($apiRequest['params'][$field])) {
1676 foreach ($values['api.aliases'] as $alias) {
1677 if (isset($apiRequest['params'][$alias])) {
1678 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1680 //unset original field nb - need to be careful with this as it may bring inconsistencies
1681 // out of the woodwork but will be implementing only as _spec function extended
1682 unset($apiRequest['params'][$alias]);
1686 if (!isset($apiRequest['params'][$field])
1687 && CRM_Utils_Array
::value('name', $values)
1688 && $field != $values['name']
1689 && isset($apiRequest['params'][$values['name']])
1691 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1692 // note that it would make sense to unset the original field here but tests need to be in place first
1694 if (!isset($apiRequest['params'][$field])
1696 && $field != $uniqueName
1697 && array_key_exists($uniqueName, $apiRequest['params'])
1700 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1701 // note that it would make sense to unset the original field here but tests need to be in place first
1708 * Validate integer fields being passed into API.
1709 * It currently converts the incoming value 'user_contact_id' into the id of the currenty logged in user
1711 * @param array $params params from civicrm_api
1712 * @param string $fieldName uniquename of field being checked
1713 * @param array $fieldInfo array of fields from getfields function
1714 * @param string $entity
1715 * @throws API_Exception
1717 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1718 //if fieldname exists in params
1719 if (CRM_Utils_Array
::value($fieldName, $params)) {
1720 // if value = 'user_contact_id' (or similar), replace value with contact id
1721 if (!is_numeric($params[$fieldName]) && is_scalar($params[$fieldName])) {
1722 $realContactId = _civicrm_api3_resolve_contactID($params[$fieldName]);
1723 if ('unknown-user' === $realContactId) {
1724 throw new API_Exception("\"$fieldName\" \"{$params[$fieldName]}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName,"type"=>"integer"));
1725 } elseif (is_numeric($realContactId)) {
1726 $params[$fieldName] = $realContactId;
1729 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1730 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1733 // After swapping options, ensure we have an integer(s)
1734 foreach ((array) ($params[$fieldName]) as $value) {
1735 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1736 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1740 // Check our field length
1741 if(is_string($params[$fieldName]) &&
1742 CRM_Utils_Array
::value('maxlength',$fieldInfo)
1743 && strlen($params[$fieldName]) > $fieldInfo['maxlength']
1745 throw new API_Exception( $params[$fieldName] . " is " . strlen($params[$fieldName]) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1746 2100, array('field' => $fieldName, "max_length"=>$fieldInfo['maxlength'])
1753 * Determine a contact ID using a string expression
1755 * @param string $contactIdExpr e.g. "user_contact_id" or "@user:username"
1756 * @return int|NULL|'unknown-user'
1758 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1759 //if value = 'user_contact_id' replace value with logged in user id
1760 if ($contactIdExpr == "user_contact_id") {
1761 return CRM_Core_Session
::getLoggedInContactID();
1763 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1764 $config = CRM_Core_Config
::singleton();
1766 $ufID = $config->userSystem
->getUfId($matches[1]);
1768 return 'unknown-user';
1771 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
1773 return 'unknown-user';
1782 * Validate html (check for scripting attack)
1783 * @param array $params
1784 * @param string $fieldName
1785 * @param array $fieldInfo
1787 * @throws API_Exception
1789 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
1790 if ($value = CRM_Utils_Array
::value($fieldName, $params)) {
1791 if (!CRM_Utils_Rule
::xssString($value)) {
1792 throw new API_Exception('Illegal characters in input (potential scripting attack)', array("field"=>$fieldName,"error_code"=>"xss"));
1798 * Validate string fields being passed into API.
1799 * @param array $params params from civicrm_api
1800 * @param string $fieldName uniquename of field being checked
1801 * @param array $fieldInfo array of fields from getfields function
1802 * @param string $entity
1803 * @throws API_Exception
1806 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
1807 // If fieldname exists in params
1808 $value = CRM_Utils_Array
::value($fieldName, $params, '');
1809 if(!is_array($value)){
1810 $value = (string) $value;
1813 //@todo what do we do about passed in arrays. For many of these fields
1814 // the missing piece of functionality is separating them to a separated string
1815 // & many save incorrectly. But can we change them wholesale?
1818 if (!CRM_Utils_Rule
::xssString($value)) {
1819 throw new Exception('Illegal characters in input (potential scripting attack)');
1821 if ($fieldName == 'currency') {
1822 if (!CRM_Utils_Rule
::currencyCode($value)) {
1823 throw new Exception("Currency not a valid code: $value");
1826 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options']) ||
!empty($fieldInfo['enumValues'])) {
1827 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1829 // Check our field length
1830 elseif (is_string($value) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($value)) > $fieldInfo['maxlength']) {
1831 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
1832 2100, array('field' => $fieldName)
1839 * Validate & swap out any pseudoconstants / options
1841 * @param array $params: api parameters
1842 * @param string $entity: api entity name
1843 * @param string $fieldName: field name used in api call (not necessarily the canonical name)
1844 * @param array $fieldInfo: getfields meta-data
1846 function _civicrm_api3_api_match_pseudoconstant(&$params, $entity, $fieldName, $fieldInfo) {
1847 $options = CRM_Utils_Array
::value('options', $fieldInfo);
1849 if(strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
1850 // we need to get the options from the entity the field relates to
1851 $entity = $fieldInfo['entity'];
1853 $options = civicrm_api($entity, 'getoptions', array('version' => 3, 'field' => $fieldInfo['name'], 'context' => 'validate'));
1854 $options = CRM_Utils_Array
::value('values', $options, array());
1857 // If passed a value-separated string, explode to an array, then re-implode after matching values
1859 if (is_string($params[$fieldName]) && strpos($params[$fieldName], CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
1860 $params[$fieldName] = CRM_Utils_Array
::explodePadded($params[$fieldName]);
1863 // If passed multiple options, validate each
1864 if (is_array($params[$fieldName])) {
1865 foreach ($params[$fieldName] as &$value) {
1866 if (!is_array($value)) {
1867 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
1870 // TODO: unwrap the call to implodePadded from the conditional and do it always
1871 // need to verify that this is safe and doesn't break anything though.
1872 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
1874 CRM_Utils_Array
::implodePadded($params[$fieldName]);
1878 _civicrm_api3_api_match_pseudoconstant_value($params[$fieldName], $options, $fieldName);
1883 * Validate & swap a single option value for a field
1885 * @param string $value: field value
1886 * @param array $options: array of options for this field
1887 * @param string $fieldName: field name used in api call (not necessarily the canonical name)
1888 * @throws API_Exception
1890 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
1891 // If option is a key, no need to translate
1892 if (array_key_exists($value, $options)) {
1896 // Translate value into key
1897 $newValue = array_search($value, $options);
1898 if ($newValue !== FALSE) {
1902 // Case-insensitive matching
1903 $newValue = strtolower($value);
1904 $options = array_map("strtolower", $options);
1905 $newValue = array_search($newValue, $options);
1906 if ($newValue === FALSE) {
1907 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
1913 * Returns the canonical name of a field
1914 * @param $entity: api entity name (string should already be standardized - no camelCase)
1915 * @param $fieldName: any variation of a field's name (name, unique_name, api.alias)
1917 * @return (string|bool) fieldName or FALSE if the field does not exist
1919 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
1920 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
1923 if ($fieldName == "{$entity}_id") {
1926 $result = civicrm_api($entity, 'getfields', array(
1928 'action' => 'create',
1930 $meta = $result['values'];
1931 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
1932 $fieldName = $fieldName . '_id';
1934 if (isset($meta[$fieldName])) {
1935 return $meta[$fieldName]['name'];
1937 foreach ($meta as $info) {
1938 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
1939 return $info['name'];
1941 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
1942 return $info['name'];