3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * File for CiviCRM APIv3 utilitity functions
31 * @package CiviCRM_APIv3
32 * @subpackage API_utils
34 * @copyright CiviCRM LLC (c) 2004-2014
35 * @version $Id: utils.php 30879 2010-11-22 15:45:55Z shot $
40 * Initialize CiviCRM - should be run at the start of each API function
42 function _civicrm_api3_initialize() {
43 require_once 'CRM/Core/ClassLoader.php';
44 CRM_Core_ClassLoader
::singleton()->register();
45 CRM_Core_Config
::singleton();
49 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking
51 * @param array $params array of fields to check
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(), $verifyDAO = TRUE) {
83 if ($daoName != NULL && $verifyDAO && empty($params['id'])) {
84 $unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
85 if (!is_array($unmatched)) {
90 if (!empty($params['id'])) {
91 $keys = array('version');
94 if (!in_array('version', $keys)) {
95 // required from v3 onwards
99 foreach ($keys as $key) {
100 if (is_array($key)) {
102 $optionset = array();
103 foreach ($key as $subkey) {
104 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
105 $optionset[] = $subkey;
108 // as long as there is one match then we don't need to rtn anything
112 if (empty($match) && !empty($optionset)) {
113 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
117 // Disallow empty values except for the number zero.
118 // TODO: create a utility for this since it's needed in many places
119 if (!array_key_exists($key, $params) ||
(empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
124 if (!empty($unmatched)) {
125 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched),"mandatory_missing",array("fields"=>$unmatched));
131 * @param <type> $data
134 * @throws API_Exception
135 * @return array <type>
137 function civicrm_api3_create_error($msg, $data = array()) {
138 $data['is_error'] = 1;
139 $data['error_message'] = $msg;
140 // we will show sql to privileged user only (not sure of a specific
141 // security hole here but seems sensible - perhaps should apply to the trace as well?)
142 if(isset($data['sql']) && CRM_Core_Permission
::check('Administer CiviCRM')) {
143 $data['debug_information'] = $data['sql']; // Isn't this redundant?
151 * Format array in result output styple
153 * @param array|int $values values generated by API operation (the result)
154 * @param array $params parameters passed into API call
155 * @param string $entity the entity being acted on
156 * @param string $action the action passed to the API
157 * @param object $dao DAO object to be freed here
158 * @param array $extraReturnValues additional values to be added to top level of result array(
159 * - this param is currently used for legacy behaviour support
161 * @return array $result
163 function civicrm_api3_create_success($values = 1, $params = array(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
165 $result['is_error'] = 0;
166 //lets set the ['id'] field if it's not set & we know what the entity is
167 if (is_array($values) && !empty($entity)) {
168 foreach ($values as $key => $item) {
169 if (empty($item['id']) && !empty($item[$entity . "_id"])) {
170 $values[$key]['id'] = $item[$entity . "_id"];
172 if(!empty($item['financial_type_id'])){
173 //4.3 legacy handling
174 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
176 if(!empty($item['next_sched_contribution_date'])){
177 // 4.4 legacy handling
178 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
183 if (is_array($params) && !empty($params['debug'])) {
184 if (is_string($action) && $action != 'getfields') {
185 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) +
$params);
187 elseif ($action != 'getfields') {
188 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
194 $allFields = array();
195 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
196 $allFields = array_keys($apiFields['values']);
198 $paramFields = array_keys($params);
199 $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), array('action', 'entity', 'debug', 'version', 'check_permissions', 'IDS_request_uri', 'IDS_user_agent', 'return', 'sequential', 'rowCount', 'option_offset', 'option_limit', 'custom', 'option_sort', 'options', 'prettyprint'));
201 $result['undefined_fields'] = array_merge($undefined);
204 if (is_object($dao)) {
208 $result['version'] = 3;
209 if (is_array($values)) {
210 $result['count'] = (int) count($values);
212 // Convert value-separated strings to array
213 _civicrm_api3_separate_values($values);
215 if ($result['count'] == 1) {
216 list($result['id']) = array_keys($values);
218 elseif (!empty($values['id']) && is_int($values['id'])) {
219 $result['id'] = $values['id'];
223 $result['count'] = !empty($values) ?
1 : 0;
226 if (is_array($values) && isset($params['sequential']) &&
227 $params['sequential'] == 1
229 $result['values'] = array_values($values);
232 $result['values'] = $values;
234 if(!empty($params['options']['metadata'])) {
235 // we've made metadata an array but only supporting 'fields' atm
236 if(in_array('fields', (array) $params['options']['metadata'])) {
237 $fields = civicrm_api3($entity, 'getfields', array('action' => substr($action, 0, 3) == 'get' ?
'get' : 'create'));
238 $result['metadata']['fields'] = $fields['values'];
241 return array_merge($result, $extraReturnValues);
245 * Load the DAO of the entity
247 function _civicrm_api3_load_DAO($entity) {
248 $dao = _civicrm_api3_get_DAO($entity);
257 * Function to return the DAO of the function or Entity
258 * @param String $name either a function of the api (civicrm_{entity}_create or the entity name
259 * return the DAO name to manipulate this function
260 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
261 * @return mixed|string
263 function _civicrm_api3_get_DAO($name) {
264 if (strpos($name, 'civicrm_api3') !== FALSE) {
265 $last = strrpos($name, '_');
266 // len ('civicrm_api3_') == 13
267 $name = substr($name, 13, $last - 13);
270 $name = _civicrm_api_get_camel_name($name, 3);
272 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
276 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
278 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
279 // but am not confident mailing_recipients is tested so have not tackled.
280 if ($name == 'MailingRecipients') {
281 return 'CRM_Mailing_DAO_Recipients';
283 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
284 if ($name == 'MailingComponent') {
285 return 'CRM_Mailing_DAO_Component';
287 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
288 if ($name == 'AclRole') {
289 return 'CRM_ACL_DAO_EntityRole';
291 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
292 // But this would impact SMS extensions so need to coordinate
293 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
294 if ($name == 'SmsProvider') {
295 return 'CRM_SMS_DAO_Provider';
297 // FIXME: DAO names should follow CamelCase convention
298 if ($name == 'Im' ||
$name == 'Acl') {
299 $name = strtoupper($name);
301 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
302 if ($dao ||
!$name) {
306 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
307 if(file_exists("api/v3/$name.php")) {
308 include_once "api/v3/$name.php";
311 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
312 if (function_exists($daoFn)) {
320 * Function to return the DAO of the function or Entity
321 * @param String $name is either a function of the api (civicrm_{entity}_create or the entity name
322 * return the DAO name to manipulate this function
323 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
326 function _civicrm_api3_get_BAO($name) {
327 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
328 if ($name == 'PrintLabel') {
329 return 'CRM_Badge_BAO_Layout';
331 $dao = _civicrm_api3_get_DAO($name);
335 $bao = str_replace("DAO", "BAO", $dao);
336 $file = strtr($bao, '_', '/') . '.php';
337 // Check if this entity actually has a BAO. Fall back on the DAO if not.
338 return stream_resolve_include_path($file) ?
$bao : $dao;
342 * Recursive function to explode value-separated strings into arrays
345 function _civicrm_api3_separate_values(&$values) {
346 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
347 foreach ($values as $key => & $value) {
348 if (is_array($value)) {
349 _civicrm_api3_separate_values($value);
351 elseif (is_string($value)) {
352 if($key == 'case_type_id'){// this is to honor the way case API was originally written
353 $value = trim(str_replace($sp, ',', $value), ',');
355 elseif (strpos($value, $sp) !== FALSE) {
356 $value = explode($sp, trim($value, $sp));
363 * This is a legacy wrapper for api_store_values which will check the suitable fields using getfields
364 * rather than DAO->fields
366 * Getfields has handling for how to deal with uniquenames which dao->fields doesn't
368 * Note this is used by BAO type create functions - eg. contribution
369 * @param string $entity
370 * @param array $params
371 * @param array $values
373 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values){
374 $fields = civicrm_api($entity,'getfields', array('version' => 3,'action' => 'create'));
375 $fields = $fields['values'];
376 _civicrm_api3_store_values($fields, $params, $values);
380 * @param array $fields
381 * @param array $params
382 * @param array $values
384 * @return Bool $valueFound
386 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
389 $keys = array_intersect_key($params, $fields);
390 foreach ($keys as $name => $value) {
391 if ($name !== 'id') {
392 $values[$name] = $value;
400 * The API supports 2 types of get requestion. The more complex uses the BAO query object.
401 * This is a generic function for those functions that call it
403 * At the moment only called by contact we should extend to contribution &
404 * others that use the query object. Note that this function passes permission information in.
407 * * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
410 * @param array $params as passed into api get or getcount function
411 * @param array $additional_options array of options (so we can modify the filter)
412 * @param bool $getCount are we just after the count
416 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL){
418 // Convert id to e.g. contact_id
419 if (empty($params[$entity . '_id']) && isset($params['id'])) {
420 $params[$entity . '_id'] = $params['id'];
422 unset($params['id']);
424 $options = _civicrm_api3_get_options_from_params($params, TRUE);
426 $inputParams = array_merge(
427 CRM_Utils_Array
::value('input_params', $options, array()),
428 CRM_Utils_Array
::value('input_params', $additional_options, array())
430 $returnProperties = array_merge(
431 CRM_Utils_Array
::value('return', $options, array()),
432 CRM_Utils_Array
::value('return', $additional_options, array())
434 if(empty($returnProperties)){
435 $returnProperties = NULL;
437 if(!empty($params['check_permissions'])){
438 // we will filter query object against getfields
439 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
440 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
441 $fields['values'][$entity . '_id'] = array();
442 $varsToFilter = array('returnProperties', 'inputParams');
443 foreach ($varsToFilter as $varToFilter){
444 if(!is_array($
$varToFilter)){
447 //I was going to throw an exception rather than silently filter out - but
448 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
449 //so we are silently ignoring parts of their request
450 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
451 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
454 $options = array_merge($options,$additional_options);
455 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
456 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
457 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
458 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
462 $returnProperties = NULL;
465 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
466 foreach ($newParams as &$newParam) {
467 if($newParam[1] == '=' && is_array($newParam[2])) {
468 // we may be looking at an attempt to use the 'IN' style syntax
469 // @todo at time of writing only 'IN' & 'NOT IN' are supported for the array style syntax
470 $sqlFilter = CRM_Core_DAO
::createSqlFilter($newParam[0], $params[$newParam[0]], 'String', NULL, TRUE);
472 $newParam[1] = key($newParam[2]);
473 $newParam[2] = $sqlFilter;
479 $skipPermissions = !empty($params['check_permissions']) ?
0 :1;
481 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
492 if ($getCount) { // only return the count of contacts
500 * get dao query object based on input params
501 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
504 * @param array $params
505 * @param string $mode
506 * @param string $entity
507 * @return CRM_Core_DAO query object
509 function _civicrm_api3_get_query_object($params, $mode, $entity) {
510 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
511 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
512 $offset = CRM_Utils_Array
::value('offset', $options);
513 $rowCount = CRM_Utils_Array
::value('limit', $options);
514 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
515 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
516 if (empty($returnProperties)) {
517 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
520 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
521 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
523 empty($params['check_permissions'])
525 list($select, $from, $where, $having) = $query->query();
527 $sql = "$select $from $where $having";
530 $sql .= " ORDER BY $sort ";
532 if(!empty($rowCount)) {
533 $sql .= " LIMIT $offset, $rowCount ";
535 $dao = CRM_Core_DAO
::executeQuery($sql);
536 return array($dao, $query);
540 * Function transfers the filters being passed into the DAO onto the params object
541 * @param CRM_Core_DAO $dao
542 * @param array $params
543 * @param bool $unique
544 * @param string $entity
546 * @throws API_Exception
549 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $entity) {
550 $entity = substr($dao->__table
, 8);
552 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
554 $fields = array_intersect(array_keys($allfields), array_keys($params));
555 if (isset($params[$entity . "_id"])) {
556 //if entity_id is set then treat it as ID (will be overridden by id if set)
557 $dao->id
= $params[$entity . "_id"];
560 $options = _civicrm_api3_get_options_from_params($params);
561 //apply options like sort
562 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
564 //accept filters like filter.activity_date_time_high
565 // std is now 'filters' => ..
566 if (strstr(implode(',', array_keys($params)), 'filter')) {
567 if (isset($params['filters']) && is_array($params['filters'])) {
568 foreach ($params['filters'] as $paramkey => $paramvalue) {
569 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
573 foreach ($params as $paramkey => $paramvalue) {
574 if (strstr($paramkey, 'filter')) {
575 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
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 * @throws API_Exception
668 * @return array $options options extracted from params
670 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
672 $sort = CRM_Utils_Array
::value('sort', $params, 0);
673 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
674 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
676 $offset = CRM_Utils_Array
::value('offset', $params, 0);
677 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
678 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
679 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
681 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
682 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
683 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
685 if (is_array(CRM_Utils_Array
::value('options', $params))) {
686 // is count is set by generic getcount not user
687 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
688 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
689 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
690 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
693 $returnProperties = array();
694 // handle the format return =sort_name,display_name...
695 if (array_key_exists('return', $params)) {
696 if (is_array($params['return'])) {
697 $returnProperties = array_fill_keys($params['return'], 1);
700 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
701 $returnProperties = array_fill_keys($returnProperties, 1);
704 if ($entity && $action =='get') {
705 if (!empty($returnProperties['id'])) {
706 $returnProperties[$entity . '_id'] = 1;
707 unset($returnProperties['id']);
709 switch (trim(strtolower($sort))){
713 $sort = str_replace('id', $entity . '_id',$sort);
718 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
719 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
720 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
721 'is_count' => $is_count,
722 'return' => !empty($returnProperties) ?
$returnProperties : array(),
725 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
726 throw new API_Exception('invalid string in sort options');
732 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
733 // if the queryobject is being used this should be used
734 $inputParams = array();
735 $legacyreturnProperties = array();
737 'sort', 'offset', 'rowCount', 'options','return',
739 foreach ($params as $n => $v) {
740 if (substr($n, 0, 7) == 'return.') {
741 $legacyreturnProperties[substr($n, 7)] = $v;
743 elseif ($n == 'id') {
744 $inputParams[$entity. '_id'] = $v;
746 elseif (in_array($n, $otherVars)) {}
748 $inputParams[$n] = $v;
749 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
750 throw new API_Exception('invalid string');
754 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
755 $options['input_params'] = $inputParams;
760 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find)
762 * @param array $params params array as passed into civicrm_api
763 * @param object $dao DAO object
766 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
768 $options = _civicrm_api3_get_options_from_params($params,FALSE,$entity);
769 if(!$options['is_count']) {
770 if(!empty($options['limit'])) {
771 $dao->limit((int)$options['offset'], (int)$options['limit']);
773 if (!empty($options['sort'])) {
774 $dao->orderBy($options['sort']);
780 * build fields array. This is the array of fields as it relates to the given DAO
781 * returns unique fields as keys by default but if set but can return by DB fields
783 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
784 $fields = $bao->fields();
786 if (empty($fields['id'])){
787 $entity = _civicrm_api_get_entity_name_from_dao($bao);
788 $fields['id'] = $fields[$entity . '_id'];
789 unset($fields[$entity . '_id']);
794 foreach ($fields as $field) {
795 $dbFields[$field['name']] = $field;
801 * build fields array. This is the array of fields as it relates to the given DAO
802 * returns unique fields as keys by default but if set but can return by DB fields
803 * @param CRM_Core_BAO $bao
807 function _civicrm_api3_get_unique_name_array(&$bao) {
808 $fields = $bao->fields();
809 foreach ($fields as $field => $values) {
810 $uniqueFields[$field] = CRM_Utils_Array
::value('name',$values, $field);
812 return $uniqueFields;
816 * Converts an DAO object to an array
818 * @param object $dao (reference )object to convert
819 * @param null $params
820 * @param bool $uniqueFields
821 * @param string $entity
823 * @param bool $autoFind
827 * @params array of arrays (key = id) of array of fields
832 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
834 if(isset($params['options']) && !empty($params['options']['is_count'])) {
835 return $dao->count();
840 if ($autoFind && !$dao->find()) {
844 if(isset($dao->count
)) {
848 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
850 while ($dao->fetch()) {
852 foreach ($fields as $key) {
853 if (array_key_exists($key, $dao)) {
854 // not sure on that one
855 if ($dao->$key !== NULL) {
856 $tmp[$key] = $dao->$key;
860 $result[$dao->id
] = $tmp;
862 if(_civicrm_api3_custom_fields_are_required($entity, $params)) {
863 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
872 * We currently retrieve all custom fields or none at this level so if we know the entity
873 * && it can take custom fields & there is the string 'custom' in their return request we get them all, they are filtered on the way out
874 * @todo filter so only required fields are queried
877 * @param string $entity - entity name in CamelCase
881 function _civicrm_api3_custom_fields_are_required($entity, $params) {
882 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
885 $options = _civicrm_api3_get_options_from_params($params);
886 //we check for possibility of 'custom' => 1 as well as specific custom fields
887 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
888 if(stristr($returnString, 'custom')) {
893 * Converts an object to an array
895 * @param object $dao (reference) object to convert
896 * @param array $values (reference) array
897 * @param array|bool $uniqueFields
903 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
905 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
906 foreach ($fields as $key => $value) {
907 if (array_key_exists($key, $dao)) {
908 $values[$key] = $dao->$key;
914 * Wrapper for _civicrm_object_to_array when api supports unique fields
916 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
917 return _civicrm_api3_object_to_array($dao, $values, TRUE);
922 * @param array $params
923 * @param array $values
924 * @param string $extends entity that this custom field extends (e.g. contribution, event, contact)
925 * @param string $entityId ID of entity per $extends
927 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
928 $values['custom'] = array();
929 $checkCheckBoxField = FALSE;
931 if(in_array($extends, array('Household', 'Individual', 'Organization'))) {
935 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
936 if(!$fields['is_error']) {
937 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
938 $fields = $fields['values'];
939 $checkCheckBoxField = TRUE;
942 foreach ($params as $key => $value) {
943 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
944 if ($customFieldID && (!IS_NULL($value))) {
945 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
946 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
948 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
949 $value, $extends, $customValueID, $entityId, FALSE, FALSE
959 function _civicrm_api3_format_params_for_create(&$params, $entity) {
960 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
962 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery
::$extendsMap, array_fill_keys($nonGenericEntities, 1));
963 if(!array_key_exists($entity, $customFieldEntities)) {
967 _civicrm_api3_custom_format_params($params, $values, $entity);
968 $params = array_merge($params, $values);
972 * we can't rely on downstream to add separators to checkboxes so we'll check here. We should look at pushing to BAO function
973 * 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
974 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
976 * 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
977 * don't touch - lots of very cautious code in here
979 * The resulting array should look like
985 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
987 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
990 * @param $checkboxFieldValue
991 * @param $customFieldLabel
995 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
997 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
998 // we can assume it's pre-formatted
1001 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1002 if (!empty($options['is_error'])) {
1003 //the check is precautionary - can probably be removed later
1007 $options = $options['values'];
1009 if (is_array($checkboxFieldValue)) {
1010 foreach ($checkboxFieldValue as $key => $value) {
1011 if (!array_key_exists($key, $options)) {
1012 $validValue = FALSE;
1016 // we have been passed an array that is already in the 'odd' custom field format
1021 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1022 // if the array only has one item we'll treat it like any other string
1023 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1024 $possibleValue = reset($checkboxFieldValue);
1026 if (is_string($checkboxFieldValue)) {
1027 $possibleValue = $checkboxFieldValue;
1029 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1030 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1033 elseif (is_array($checkboxFieldValue)) {
1034 // so this time around we are considering the values in the array
1035 $possibleValues = $checkboxFieldValue;
1036 $formatValue = TRUE;
1038 elseif (stristr($checkboxFieldValue, ',')) {
1039 $formatValue = TRUE;
1040 //lets see if we should separate it - we do this near the end so we
1041 // ensure we have already checked that the comma is not part of a legitimate match
1042 // and of course, we don't make any changes if we don't now have matches
1043 $possibleValues = explode(',', $checkboxFieldValue);
1046 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1050 foreach ($possibleValues as $index => $possibleValue) {
1051 if (array_key_exists($possibleValue, $options)) {
1052 // 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)
1054 elseif (array_key_exists(trim($possibleValue), $options)) {
1055 $possibleValues[$index] = trim($possibleValue);
1058 $formatValue = FALSE;
1062 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1068 * This function ensures that we have the right input parameters
1070 * This function is only called when $dao is passed into verify_mandatory.
1071 * The practice of passing $dao into verify_mandatory turned out to be
1072 * unsatisfactory as the required fields @ the dao level is so diffent to the abstract
1073 * api level. Hence the intention is to remove this function
1074 * & the associated param from viery_mandatory
1076 * @param array $params Associative array of property name/value
1077 * pairs to insert in new history.
1079 * @param bool $return
1081 * @daoName string DAO to check params agains
1083 * @return bool should the missing fields be returned as an array (core error created as default)
1085 * @return bool true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1088 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1089 //@deprecated - see notes
1090 if (isset($params['extends'])) {
1091 if (($params['extends'] == 'Activity' ||
1092 $params['extends'] == 'Phonecall' ||
1093 $params['extends'] == 'Meeting' ||
1094 $params['extends'] == 'Group' ||
1095 $params['extends'] == 'Contribution'
1097 ($params['style'] == 'Tab')
1099 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1103 $dao = new $daoName();
1104 $fields = $dao->fields();
1107 foreach ($fields as $k => $v) {
1108 if ($v['name'] == 'id') {
1112 if (!empty($v['required'])) {
1113 // 0 is a valid input for numbers, CRM-8122
1114 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1120 if (!empty($missing)) {
1121 if (!empty($return)) {
1125 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1133 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this
1135 * @param string $bao_name name of BAO
1136 * @param array $params params from api
1137 * @param bool $returnAsSuccess return in api success format
1138 * @param string $entity
1142 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1143 $bao = new $bao_name();
1144 _civicrm_api3_dao_set_filter($bao, $params, TRUE, $entity);
1145 if ($returnAsSuccess) {
1146 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1149 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity, 'get');
1154 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this
1156 * @param string $bao_name Name of BAO Class
1157 * @param array $params parameters passed into the api call
1158 * @param string $entity Entity - pass in if entity is non-standard & required $ids array
1160 * @throws API_Exception
1163 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1164 _civicrm_api3_format_params_for_create($params, $entity);
1165 $args = array(&$params);
1166 if (!empty($entity)) {
1167 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1171 if (method_exists($bao_name, 'create')) {
1173 $fct_name = $bao_name . '::' . $fct;
1174 $bao = call_user_func_array(array($bao_name, $fct), $args);
1176 elseif (method_exists($bao_name, 'add')) {
1178 $fct_name = $bao_name . '::' . $fct;
1179 $bao = call_user_func_array(array($bao_name, $fct), $args);
1182 $fct_name = '_civicrm_api3_basic_create_fallback';
1183 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1186 if (is_null($bao)) {
1187 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1189 elseif (is_a($bao, 'CRM_Core_Error')) {
1190 //some wierd circular thing means the error takes itself as an argument
1191 $msg = $bao->getMessages($bao);
1192 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1193 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1194 // so we need to reset the error object here to avoid getting concatenated errors
1195 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1196 CRM_Core_Error
::singleton()->reset();
1197 throw new API_Exception($msg);
1201 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1202 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1207 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1209 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1210 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1212 * @param string $bao_name
1213 * @param array $params
1215 * @throws API_Exception
1216 * @return CRM_Core_DAO|NULL an instance of the BAO
1218 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1219 $dao_name = get_parent_class($bao_name);
1220 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1221 $dao_name = $bao_name;
1223 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1224 if (empty($entityName)) {
1225 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1226 'class_name' => $bao_name,
1229 $hook = empty($params['id']) ?
'create' : 'edit';
1231 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1232 $instance = new $dao_name();
1233 $instance->copyValues($params);
1235 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1241 * Function to do a 'standard' api del - when the api is only doing a $bao::del then use this
1242 * if api::del doesn't exist it will try DAO delete method
1247 * @return array API result array
1248 * @throws API_Exception
1250 function _civicrm_api3_basic_delete($bao_name, &$params) {
1252 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1253 $args = array(&$params['id']);
1254 if (method_exists($bao_name, 'del')) {
1255 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1256 if ($bao !== FALSE) {
1257 return civicrm_api3_create_success(TRUE);
1259 throw new API_Exception('Could not delete entity id ' . $params['id']);
1261 elseif (method_exists($bao_name, 'delete')) {
1262 $dao = new $bao_name();
1263 $dao->id
= $params['id'];
1265 while ($dao->fetch()) {
1267 return civicrm_api3_create_success();
1271 throw new API_Exception('Could not delete entity id ' . $params['id']);
1275 throw new API_Exception('no delete method found');
1279 * Get custom data for the given entity & Add it to the returnArray as 'custom_123' = 'custom string' AND 'custom_123_1' = 'custom string'
1280 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1282 * @param array $returnArray - array to append custom data too - generally $result[4] where 4 is the entity id.
1283 * @param string $entity e.g membership, event
1285 * @param int $groupID - per CRM_Core_BAO_CustomGroup::getTree
1286 * @param int $subType e.g. membership_type_id where custom data doesn't apply to all membership types
1287 * @param string $subName - Subtype of entity
1289 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1290 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1291 CRM_Core_DAO
::$_nullObject,
1297 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1298 $customValues = array();
1299 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1300 $fieldInfo = array();
1301 foreach ($groupTree as $set) {
1302 $fieldInfo +
= $set['fields'];
1304 if (!empty($customValues)) {
1305 foreach ($customValues as $key => $val) {
1306 // per standard - return custom_fieldID
1307 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1308 $returnArray['custom_' . $id] = $val;
1310 //not standard - but some api did this so guess we should keep - cheap as chips
1311 $returnArray[$key] = $val;
1313 // Shim to restore legacy behavior of ContactReference custom fields
1314 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1315 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1316 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1323 * Validate fields being passed into API. This function relies on the getFields function working accurately
1324 * for the given API. If error mode is set to TRUE then it will also check
1327 * As of writing only date was implemented.
1328 * @param string $entity
1329 * @param string $action
1330 * @param array $params -
1331 * @param array $fields response from getfields all variables are the same as per civicrm_api
1332 * @param bool $errorMode errorMode do intensive post fail checks?
1335 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = False) {
1336 $fields = array_intersect_key($fields, $params);
1337 foreach ($fields as $fieldName => $fieldInfo) {
1338 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1339 case CRM_Utils_Type
::T_INT
:
1340 //field is of type integer
1341 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1346 case CRM_Utils_Type
::T_TIMESTAMP
:
1347 //field is of type date or datetime
1348 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1352 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1355 case CRM_Utils_Type
::T_STRING
:
1356 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1359 case CRM_Utils_Type
::T_MONEY
:
1360 if (!CRM_Utils_Rule
::money($params[$fieldName]) && !empty($params[$fieldName])) {
1361 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1365 // intensive checks - usually only called after DB level fail
1366 if (!empty($errorMode) && strtolower($action) == 'create') {
1367 if (!empty($fieldInfo['FKClassName'])) {
1368 if (!empty($params[$fieldName])) {
1369 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1371 elseif (!empty($fieldInfo['required'])) {
1372 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1375 if (!empty($fieldInfo['api.unique'])) {
1376 $params['entity'] = $entity;
1377 _civicrm_api3_validate_uniquekey($params, $fieldName, $fieldInfo);
1384 * Validate date fields being passed into API.
1385 * It currently converts both unique fields and DB field names to a mysql date.
1386 * @todo - probably the unique field handling & the if exists handling is now done before this
1387 * function is reached in the wrapper - can reduce this code down to assume we
1388 * are only checking the passed in field
1390 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1391 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1393 * @param array $params params from civicrm_api
1394 * @param string $fieldName uniquename of field being checked
1395 * @param array $fieldInfo array of fields from getfields function
1398 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1399 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1400 if (!empty($params[$fieldInfo['name']])) {
1401 $params[$fieldInfo['name']] = _civicrm_api3_getValidDate($params[$fieldInfo['name']], $fieldInfo['name'], $fieldInfo['type']);
1403 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($params[$fieldName])) {
1404 $params[$fieldName] = _civicrm_api3_getValidDate($params[$fieldName], $fieldName, $fieldInfo['type']);
1409 * convert date into BAO friendly date
1410 * we accept 'whatever strtotime accepts'
1412 * @param string $dateValue
1417 * @internal param $fieldInfo
1419 * @internal param $params
1422 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1423 if (is_array($dateValue)) {
1424 foreach ($dateValue as $key => $value) {
1425 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1429 if (strtotime($dateValue) === FALSE) {
1430 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1432 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1433 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1437 * Validate foreign constraint fields being passed into API.
1439 * @param array $params params from civicrm_api
1440 * @param string $fieldName uniquename of field being checked
1441 * @param array $fieldInfo array of fields from getfields function
1444 function _civicrm_api3_validate_constraint(&$params, &$fieldName, &$fieldInfo) {
1445 $dao = new $fieldInfo['FKClassName'];
1446 $dao->id
= $params[$fieldName];
1448 $dao->selectAdd('id');
1449 if (!$dao->find()) {
1450 throw new Exception("$fieldName is not valid : " . $params[$fieldName]);
1455 * Validate foreign constraint fields being passed into API.
1457 * @param array $params params from civicrm_api
1458 * @param string $fieldName uniquename of field being checked
1459 * @param $fieldInfo array of fields from getfields function
1462 function _civicrm_api3_validate_uniquekey(&$params, &$fieldName, &$fieldInfo) {
1463 $existing = civicrm_api($params['entity'], 'get', array(
1464 'version' => $params['version'],
1465 $fieldName => $params[$fieldName],
1467 // an entry already exists for this unique field
1468 if ($existing['count'] == 1) {
1469 // question - could this ever be a security issue?
1470 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1475 * Generic implementation of the "replace" action.
1477 * Replace the old set of entities (matching some given keys) with a new set of
1478 * entities (matching the same keys).
1480 * Note: This will verify that 'values' is present, but it does not directly verify
1481 * any other parameters.
1483 * @param string $entity entity name
1484 * @param array $params params from civicrm_api, including:
1485 * - 'values': an array of records to save
1486 * - all other items: keys which identify new/pre-existing records
1489 function _civicrm_api3_generic_replace($entity, $params) {
1491 $transaction = new CRM_Core_Transaction();
1493 if (!is_array($params['values'])) {
1494 throw new Exception("Mandatory key(s) missing from params array: values");
1497 // Extract the keys -- somewhat scary, don't think too hard about it
1498 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1500 // Lookup pre-existing records
1501 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1502 if (civicrm_error($preexisting)) {
1503 $transaction->rollback();
1504 return $preexisting;
1507 // Save the new/updated records
1509 foreach ($params['values'] as $replacement) {
1510 // Sugar: Don't force clients to duplicate the 'key' data
1511 $replacement = array_merge($baseParams, $replacement);
1512 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1513 $create = civicrm_api($entity, $action, $replacement);
1514 if (civicrm_error($create)) {
1515 $transaction->rollback();
1518 foreach ($create['values'] as $entity_id => $entity_value) {
1519 $creates[$entity_id] = $entity_value;
1523 // Remove stale records
1524 $staleIDs = array_diff(
1525 array_keys($preexisting['values']),
1526 array_keys($creates)
1528 foreach ($staleIDs as $staleID) {
1529 $delete = civicrm_api($entity, 'delete', array(
1530 'version' => $params['version'],
1533 if (civicrm_error($delete)) {
1534 $transaction->rollback();
1539 return civicrm_api3_create_success($creates, $params);
1541 catch(PEAR_Exception
$e) {
1542 $transaction->rollback();
1543 return civicrm_api3_create_error($e->getMessage());
1545 catch(Exception
$e) {
1546 $transaction->rollback();
1547 return civicrm_api3_create_error($e->getMessage());
1556 function _civicrm_api3_generic_replace_base_params($params) {
1557 $baseParams = $params;
1558 unset($baseParams['values']);
1559 unset($baseParams['sequential']);
1560 unset($baseParams['options']);
1565 * returns fields allowable by api
1567 * @param $entity string Entity to query
1568 * @param bool $unique index by unique fields?
1569 * @param array $params
1573 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1574 $unsetIfEmpty = array('dataPattern', 'headerPattern', 'default', 'export', 'import');
1575 $dao = _civicrm_api3_get_DAO($entity);
1580 $fields = $d->fields();
1581 // replace uniqueNames by the normal names as the key
1582 if (empty($unique)) {
1583 foreach ($fields as $name => & $field) {
1584 //getting rid of unused attributes
1585 foreach ($unsetIfEmpty as $attr) {
1586 if (empty($field[$attr])) {
1587 unset($field[$attr]);
1590 if ($name == $field['name']) {
1593 if (array_key_exists($field['name'], $fields)) {
1594 $field['error'] = 'name conflict';
1595 // it should never happen, but better safe than sorry
1598 $fields[$field['name']] = $field;
1599 $fields[$field['name']]['uniqueName'] = $name;
1600 unset($fields[$name]);
1603 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1608 * Return an array of fields for a given entity - this is the same as the BAO function but
1609 * fields are prefixed with 'custom_' to represent api params
1611 function _civicrm_api_get_custom_fields($entity, &$params) {
1612 $customfields = array();
1613 $entity = _civicrm_api_get_camel_name($entity);
1614 if (strtolower($entity) == 'contact') {
1615 // Use sub-type if available, otherwise stick with 'Contact'
1616 $entity = CRM_Utils_Array
::value('contact_type', $params);
1618 $retrieveOnlyParent = FALSE;
1619 // we could / should probably test for other subtypes here - e.g. activity_type_id
1620 if($entity == 'Contact'){
1621 empty($params['contact_sub_type']);
1623 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1626 CRM_Utils_Array
::value('contact_sub_type', $params, FALSE),
1628 $retrieveOnlyParent,
1635 foreach ($customfields as $key => $value) {
1636 // Regular fields have a 'name' property
1637 $value['name'] = 'custom_' . $key;
1638 $value['title'] = $value['label'];
1639 $value['type'] = _getStandardTypeFromCustomDataType($value['data_type']);
1640 $ret['custom_' . $key] = $value;
1645 * Translate the custom field data_type attribute into a std 'type'
1647 function _getStandardTypeFromCustomDataType($dataType) {
1649 'String' => CRM_Utils_Type
::T_STRING
,
1650 'Int' => CRM_Utils_Type
::T_INT
,
1651 'Money' => CRM_Utils_Type
::T_MONEY
,
1652 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1653 'Float' => CRM_Utils_Type
::T_FLOAT
,
1654 'Date' => CRM_Utils_Type
::T_DATE
,
1655 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1656 'StateProvince' => CRM_Utils_Type
::T_INT
,
1657 'File' => CRM_Utils_Type
::T_STRING
,
1658 'Link' => CRM_Utils_Type
::T_STRING
,
1659 'ContactReference' => CRM_Utils_Type
::T_INT
,
1660 'Country' => CRM_Utils_Type
::T_INT
,
1662 return $mapping[$dataType];
1667 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't
1668 * If multiple aliases the last takes precedence
1670 * Function also swaps unique fields for non-unique fields & vice versa.
1672 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1673 foreach ($fields as $field => $values) {
1674 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1675 if (!empty($values['api.aliases'])) {
1676 // if aliased field is not set we try to use field alias
1677 if (!isset($apiRequest['params'][$field])) {
1678 foreach ($values['api.aliases'] as $alias) {
1679 if (isset($apiRequest['params'][$alias])) {
1680 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1682 //unset original field nb - need to be careful with this as it may bring inconsistencies
1683 // out of the woodwork but will be implementing only as _spec function extended
1684 unset($apiRequest['params'][$alias]);
1688 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $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 (!empty($params[$fieldName])) {
1719 // if value = 'user_contact_id' (or similar), replace value with contact id
1720 if (!is_numeric($params[$fieldName]) && is_scalar($params[$fieldName])) {
1721 $realContactId = _civicrm_api3_resolve_contactID($params[$fieldName]);
1722 if ('unknown-user' === $realContactId) {
1723 throw new API_Exception("\"$fieldName\" \"{$params[$fieldName]}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName,"type"=>"integer"));
1724 } elseif (is_numeric($realContactId)) {
1725 $params[$fieldName] = $realContactId;
1728 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1729 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1732 // After swapping options, ensure we have an integer(s)
1733 foreach ((array) ($params[$fieldName]) as $value) {
1734 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1735 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1739 // Check our field length
1740 if(is_string($params[$fieldName]) && !empty($fieldInfo['maxlength']) && strlen($params[$fieldName]) > $fieldInfo['maxlength']
1742 throw new API_Exception( $params[$fieldName] . " is " . strlen($params[$fieldName]) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1743 2100, array('field' => $fieldName, "max_length"=>$fieldInfo['maxlength'])
1750 * Determine a contact ID using a string expression
1752 * @param string $contactIdExpr e.g. "user_contact_id" or "@user:username"
1753 * @return int|NULL|'unknown-user'
1755 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1756 //if value = 'user_contact_id' replace value with logged in user id
1757 if ($contactIdExpr == "user_contact_id") {
1758 return CRM_Core_Session
::getLoggedInContactID();
1760 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1761 $config = CRM_Core_Config
::singleton();
1763 $ufID = $config->userSystem
->getUfId($matches[1]);
1765 return 'unknown-user';
1768 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
1770 return 'unknown-user';
1779 * Validate html (check for scripting attack)
1780 * @param array $params
1781 * @param string $fieldName
1782 * @param array $fieldInfo
1784 * @throws API_Exception
1786 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
1787 if ($value = CRM_Utils_Array
::value($fieldName, $params)) {
1788 if (!CRM_Utils_Rule
::xssString($value)) {
1789 throw new API_Exception('Illegal characters in input (potential scripting attack)', array("field"=>$fieldName,"error_code"=>"xss"));
1795 * Validate string fields being passed into API.
1796 * @param array $params params from civicrm_api
1797 * @param string $fieldName uniquename of field being checked
1798 * @param array $fieldInfo array of fields from getfields function
1799 * @param string $entity
1800 * @throws API_Exception
1803 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
1804 // If fieldname exists in params
1805 $value = CRM_Utils_Array
::value($fieldName, $params, '');
1806 if(!is_array($value)){
1807 $value = (string) $value;
1810 //@todo what do we do about passed in arrays. For many of these fields
1811 // the missing piece of functionality is separating them to a separated string
1812 // & many save incorrectly. But can we change them wholesale?
1815 if (!CRM_Utils_Rule
::xssString($value)) {
1816 throw new Exception('Illegal characters in input (potential scripting attack)');
1818 if ($fieldName == 'currency') {
1819 if (!CRM_Utils_Rule
::currencyCode($value)) {
1820 throw new Exception("Currency not a valid code: $value");
1823 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1824 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1826 // Check our field length
1827 elseif (is_string($value) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($value)) > $fieldInfo['maxlength']) {
1828 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
1829 2100, array('field' => $fieldName)
1836 * Validate & swap out any pseudoconstants / options
1838 * @param array $params: api parameters
1839 * @param string $entity: api entity name
1840 * @param string $fieldName: field name used in api call (not necessarily the canonical name)
1841 * @param array $fieldInfo: getfields meta-data
1843 function _civicrm_api3_api_match_pseudoconstant(&$params, $entity, $fieldName, $fieldInfo) {
1844 $options = CRM_Utils_Array
::value('options', $fieldInfo);
1846 if(strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
1847 // we need to get the options from the entity the field relates to
1848 $entity = $fieldInfo['entity'];
1850 $options = civicrm_api($entity, 'getoptions', array('version' => 3, 'field' => $fieldInfo['name'], 'context' => 'validate'));
1851 $options = CRM_Utils_Array
::value('values', $options, array());
1854 // If passed a value-separated string, explode to an array, then re-implode after matching values
1856 if (is_string($params[$fieldName]) && strpos($params[$fieldName], CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
1857 $params[$fieldName] = CRM_Utils_Array
::explodePadded($params[$fieldName]);
1860 // If passed multiple options, validate each
1861 if (is_array($params[$fieldName])) {
1862 foreach ($params[$fieldName] as &$value) {
1863 if (!is_array($value)) {
1864 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
1867 // TODO: unwrap the call to implodePadded from the conditional and do it always
1868 // need to verify that this is safe and doesn't break anything though.
1869 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
1871 CRM_Utils_Array
::implodePadded($params[$fieldName]);
1875 _civicrm_api3_api_match_pseudoconstant_value($params[$fieldName], $options, $fieldName);
1880 * Validate & swap a single option value for a field
1882 * @param string $value: field value
1883 * @param array $options: array of options for this field
1884 * @param string $fieldName: field name used in api call (not necessarily the canonical name)
1885 * @throws API_Exception
1887 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
1888 // If option is a key, no need to translate
1889 if (array_key_exists($value, $options)) {
1893 // Translate value into key
1894 $newValue = array_search($value, $options);
1895 if ($newValue !== FALSE) {
1899 // Case-insensitive matching
1900 $newValue = strtolower($value);
1901 $options = array_map("strtolower", $options);
1902 $newValue = array_search($newValue, $options);
1903 if ($newValue === FALSE) {
1904 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
1910 * Returns the canonical name of a field
1912 * @param $entity : api entity name (string should already be standardized - no camelCase)
1913 * @param $fieldName : any variation of a field's name (name, unique_name, api.alias)
1915 * @return bool|string (string|bool) fieldName or FALSE if the field does not exist
1917 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
1918 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
1921 if ($fieldName == "{$entity}_id") {
1924 $result = civicrm_api($entity, 'getfields', array(
1926 'action' => 'create',
1928 $meta = $result['values'];
1929 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
1930 $fieldName = $fieldName . '_id';
1932 if (isset($meta[$fieldName])) {
1933 return $meta[$fieldName]['name'];
1935 foreach ($meta as $info) {
1936 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
1937 return $info['name'];
1939 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
1940 return $info['name'];