3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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
52 * Array of fields to check.
53 * @param array $daoName
54 * String DAO to check for required fields (create functions only).
55 * @param array $keyoptions
56 * List of required fields options. One of the options is required.
58 * @return null or throws error if there the required fields not present
61 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = array()) {
62 $keys = array(array());
63 foreach ($keyoptions as $key) {
66 civicrm_api3_verify_mandatory($params, $daoName, $keys);
70 * check mandatory fields are included
72 * @param array $params
73 * Array of fields to check.
74 * @param array $daoName
75 * String DAO to check for required fields (create functions only).
77 * List of required fields. A value can be an array denoting that either this or that is required.
78 * @param bool $verifyDAO
80 * @throws API_Exception
81 * @return null or throws error if there the required fields not present
83 * @todo see notes on _civicrm_api3_check_required_fields regarding removing $daoName param
85 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = array(), $verifyDAO = TRUE) {
88 if ($daoName != NULL && $verifyDAO && empty($params['id'])) {
89 $unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
90 if (!is_array($unmatched)) {
95 if (!empty($params['id'])) {
96 $keys = array('version');
99 if (!in_array('version', $keys)) {
100 // required from v3 onwards
104 foreach ($keys as $key) {
105 if (is_array($key)) {
107 $optionset = array();
108 foreach ($key as $subkey) {
109 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
110 $optionset[] = $subkey;
113 // as long as there is one match then we don't need to rtn anything
117 if (empty($match) && !empty($optionset)) {
118 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
122 // Disallow empty values except for the number zero.
123 // TODO: create a utility for this since it's needed in many places
124 if (!array_key_exists($key, $params) ||
(empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
129 if (!empty($unmatched)) {
130 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched), "mandatory_missing", array("fields" => $unmatched));
136 * @param <type> $data
139 * @throws API_Exception
140 * @return array <type>
142 function civicrm_api3_create_error($msg, $data = array()) {
143 $data['is_error'] = 1;
144 $data['error_message'] = $msg;
145 // we will show sql to privileged user only (not sure of a specific
146 // security hole here but seems sensible - perhaps should apply to the trace as well?)
147 if(isset($data['sql']) && CRM_Core_Permission
::check('Administer CiviCRM')) {
148 $data['debug_information'] = $data['sql']; // Isn't this redundant?
156 * Format array in result output styple
158 * @param array|int $values values generated by API operation (the result)
159 * @param array $params
160 * Parameters passed into API call.
161 * @param string $entity
162 * The entity being acted on.
163 * @param string $action
164 * The action passed to the API.
166 * DAO object to be freed here.
167 * @param array $extraReturnValues
168 * Additional values to be added to top level of result array(.
169 * - this param is currently used for legacy behaviour support
171 * @return array $result
173 function civicrm_api3_create_success($values = 1, $params = array(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
175 $result['is_error'] = 0;
176 //lets set the ['id'] field if it's not set & we know what the entity is
177 if (is_array($values) && !empty($entity) && $action != 'getfields') {
178 foreach ($values as $key => $item) {
179 if (empty($item['id']) && !empty($item[$entity . "_id"])) {
180 $values[$key]['id'] = $item[$entity . "_id"];
182 if(!empty($item['financial_type_id'])){
183 //4.3 legacy handling
184 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
186 if(!empty($item['next_sched_contribution_date'])){
187 // 4.4 legacy handling
188 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
193 if (is_array($params) && !empty($params['debug'])) {
194 if (is_string($action) && $action != 'getfields') {
195 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) +
$params);
197 elseif ($action != 'getfields') {
198 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
204 $allFields = array();
205 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
206 $allFields = array_keys($apiFields['values']);
208 $paramFields = array_keys($params);
209 $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'));
211 $result['undefined_fields'] = array_merge($undefined);
214 if (is_object($dao)) {
218 $result['version'] = 3;
219 if (is_array($values)) {
220 $result['count'] = (int) count($values);
222 // Convert value-separated strings to array
223 _civicrm_api3_separate_values($values);
225 if ($result['count'] == 1) {
226 list($result['id']) = array_keys($values);
228 elseif (!empty($values['id']) && is_int($values['id'])) {
229 $result['id'] = $values['id'];
233 $result['count'] = !empty($values) ?
1 : 0;
236 if (is_array($values) && isset($params['sequential']) &&
237 $params['sequential'] == 1
239 $result['values'] = array_values($values);
242 $result['values'] = $values;
244 if(!empty($params['options']['metadata'])) {
245 // we've made metadata an array but only supporting 'fields' atm
246 if(in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
247 $fields = civicrm_api3($entity, 'getfields', array('action' => substr($action, 0, 3) == 'get' ?
'get' : 'create'));
248 $result['metadata']['fields'] = $fields['values'];
251 // Report deprecations
252 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
253 // Always report "update" action as deprecated
254 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'update')) {
255 $deprecated = ((array) $deprecated) +
array('update' => 'The "update" action is deprecated. Use "create" with an id instead.');
258 // Metadata-level deprecations or wholesale entity deprecations
259 if ($entity == 'entity' ||
$action == 'getactions' ||
is_string($deprecated)) {
260 $result['deprecated'] = $deprecated;
262 // Action-specific deprecations
263 elseif (!empty($deprecated[$action])) {
264 $result['deprecated'] = $deprecated[$action];
267 return array_merge($result, $extraReturnValues);
271 * Load the DAO of the entity
273 function _civicrm_api3_load_DAO($entity) {
274 $dao = _civicrm_api3_get_DAO($entity);
283 * return the DAO of the function or Entity
284 * @param string $name
285 * Either a function of the api (civicrm_{entity}_create or the entity name.
286 * return the DAO name to manipulate this function
287 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
288 * @return mixed|string
290 function _civicrm_api3_get_DAO($name) {
291 if (strpos($name, 'civicrm_api3') !== FALSE) {
292 $last = strrpos($name, '_');
293 // len ('civicrm_api3_') == 13
294 $name = substr($name, 13, $last - 13);
297 $name = _civicrm_api_get_camel_name($name, 3);
299 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
303 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
305 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
306 if ($name == 'MailingEventQueue') {
307 return 'CRM_Mailing_Event_DAO_Queue';
309 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
310 // but am not confident mailing_recipients is tested so have not tackled.
311 if ($name == 'MailingRecipients') {
312 return 'CRM_Mailing_DAO_Recipients';
314 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
315 if ($name == 'MailingComponent') {
316 return 'CRM_Mailing_DAO_Component';
318 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
319 if ($name == 'AclRole') {
320 return 'CRM_ACL_DAO_EntityRole';
322 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
323 // But this would impact SMS extensions so need to coordinate
324 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
325 if ($name == 'SmsProvider') {
326 return 'CRM_SMS_DAO_Provider';
328 // FIXME: DAO names should follow CamelCase convention
329 if ($name == 'Im' ||
$name == 'Acl') {
330 $name = strtoupper($name);
332 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
333 if ($dao ||
!$name) {
337 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
338 if(file_exists("api/v3/$name.php")) {
339 include_once "api/v3/$name.php";
342 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
343 if (function_exists($daoFn)) {
351 * return the DAO of the function or Entity
352 * @param string $name
353 * Is either a function of the api (civicrm_{entity}_create or the entity name.
354 * return the DAO name to manipulate this function
355 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
358 function _civicrm_api3_get_BAO($name) {
359 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
360 if ($name == 'PrintLabel') {
361 return 'CRM_Badge_BAO_Layout';
363 $dao = _civicrm_api3_get_DAO($name);
367 $bao = str_replace("DAO", "BAO", $dao);
368 $file = strtr($bao, '_', '/') . '.php';
369 // Check if this entity actually has a BAO. Fall back on the DAO if not.
370 return stream_resolve_include_path($file) ?
$bao : $dao;
374 * Recursive function to explode value-separated strings into arrays
377 function _civicrm_api3_separate_values(&$values) {
378 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
379 foreach ($values as $key => & $value) {
380 if (is_array($value)) {
381 _civicrm_api3_separate_values($value);
383 elseif (is_string($value)) {
384 if($key == 'case_type_id'){// this is to honor the way case API was originally written
385 $value = trim(str_replace($sp, ',', $value), ',');
387 elseif (strpos($value, $sp) !== FALSE) {
388 $value = explode($sp, trim($value, $sp));
395 * This is a legacy wrapper for api_store_values which will check the suitable fields using getfields
396 * rather than DAO->fields
398 * Getfields has handling for how to deal with uniquenames which dao->fields doesn't
400 * Note this is used by BAO type create functions - eg. contribution
401 * @param string $entity
402 * @param array $params
403 * @param array $values
405 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values){
406 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
407 $fields = $fields['values'];
408 _civicrm_api3_store_values($fields, $params, $values);
412 * @param array $fields
413 * @param array $params
414 * @param array $values
416 * @return Bool $valueFound
418 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
421 $keys = array_intersect_key($params, $fields);
422 foreach ($keys as $name => $value) {
423 if ($name !== 'id') {
424 $values[$name] = $value;
432 * The API supports 2 types of get requestion. The more complex uses the BAO query object.
433 * This is a generic function for those functions that call it
435 * At the moment only called by contact we should extend to contribution &
436 * others that use the query object. Note that this function passes permission information in.
439 * * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
442 * @param array $params
443 * As passed into api get or getcount function.
444 * @param array $additional_options
445 * Array of options (so we can modify the filter).
446 * @param bool $getCount
447 * Are we just after the count.
451 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL){
453 // Convert id to e.g. contact_id
454 if (empty($params[$entity . '_id']) && isset($params['id'])) {
455 $params[$entity . '_id'] = $params['id'];
457 unset($params['id']);
459 $options = _civicrm_api3_get_options_from_params($params, TRUE);
461 $inputParams = array_merge(
462 CRM_Utils_Array
::value('input_params', $options, array()),
463 CRM_Utils_Array
::value('input_params', $additional_options, array())
465 $returnProperties = array_merge(
466 CRM_Utils_Array
::value('return', $options, array()),
467 CRM_Utils_Array
::value('return', $additional_options, array())
469 if(empty($returnProperties)){
470 $returnProperties = NULL;
472 if(!empty($params['check_permissions'])){
473 // we will filter query object against getfields
474 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
475 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
476 $fields['values'][$entity . '_id'] = array();
477 $varsToFilter = array('returnProperties', 'inputParams');
478 foreach ($varsToFilter as $varToFilter){
479 if(!is_array($
$varToFilter)){
482 //I was going to throw an exception rather than silently filter out - but
483 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
484 //so we are silently ignoring parts of their request
485 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
486 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
489 $options = array_merge($options, $additional_options);
490 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
491 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
492 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
493 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
497 $returnProperties = NULL;
500 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
501 foreach ($newParams as &$newParam) {
502 if($newParam[1] == '=' && is_array($newParam[2])) {
503 // we may be looking at an attempt to use the 'IN' style syntax
504 // @todo at time of writing only 'IN' & 'NOT IN' are supported for the array style syntax
505 $sqlFilter = CRM_Core_DAO
::createSqlFilter($newParam[0], $params[$newParam[0]], 'String', NULL, TRUE);
507 $newParam[1] = key($newParam[2]);
508 $newParam[2] = $sqlFilter;
514 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
516 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
527 if ($getCount) { // only return the count of contacts
535 * get dao query object based on input params
536 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
539 * @param array $params
540 * @param string $mode
541 * @param string $entity
542 * @return CRM_Core_DAO query object
544 function _civicrm_api3_get_query_object($params, $mode, $entity) {
545 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
546 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
547 $offset = CRM_Utils_Array
::value('offset', $options);
548 $rowCount = CRM_Utils_Array
::value('limit', $options);
549 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
550 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
551 if (empty($returnProperties)) {
552 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
555 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
556 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
558 empty($params['check_permissions'])
560 list($select, $from, $where, $having) = $query->query();
562 $sql = "$select $from $where $having";
565 $sql .= " ORDER BY $sort ";
567 if(!empty($rowCount)) {
568 $sql .= " LIMIT $offset, $rowCount ";
570 $dao = CRM_Core_DAO
::executeQuery($sql);
571 return array($dao, $query);
575 * Function transfers the filters being passed into the DAO onto the params object
576 * @param CRM_Core_DAO $dao
577 * @param array $params
578 * @param bool $unique
579 * @param string $entity
581 * @throws API_Exception
584 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $entity) {
585 $entity = substr($dao->__table
, 8);
586 if (!empty($params[$entity . "_id"]) && empty($params['id'])) {
587 //if entity_id is set then treat it as ID (will be overridden by id if set)
588 $params['id'] = $params[$entity . "_id"];
590 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
591 $fields = array_intersect(array_keys($allfields), array_keys($params));
593 $options = _civicrm_api3_get_options_from_params($params);
594 //apply options like sort
595 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
597 //accept filters like filter.activity_date_time_high
598 // std is now 'filters' => ..
599 if (strstr(implode(',', array_keys($params)), 'filter')) {
600 if (isset($params['filters']) && is_array($params['filters'])) {
601 foreach ($params['filters'] as $paramkey => $paramvalue) {
602 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
606 foreach ($params as $paramkey => $paramvalue) {
607 if (strstr($paramkey, 'filter')) {
608 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
617 foreach ($fields as $field) {
618 if (is_array($params[$field])) {
619 //get the actual fieldname from db
620 $fieldName = $allfields[$field]['name'];
621 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
623 $dao->whereAdd($where);
628 $daoFieldName = $allfields[$field]['name'];
629 if (empty($daoFieldName)) {
630 throw new API_Exception("Failed to determine field name for \"$field\"");
632 $dao->{$daoFieldName} = $params[$field];
635 $dao->$field = $params[$field];
639 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
641 $options['return']['id'] = TRUE;// ensure 'id' is included
642 $allfields = _civicrm_api3_get_unique_name_array($dao);
643 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
644 foreach ($returnMatched as $returnValue) {
645 $dao->selectAdd($returnValue);
648 $unmatchedFields = array_diff(// not already matched on the field names
649 array_keys($options['return']),
653 $returnUniqueMatched = array_intersect(
655 array_flip($allfields)// but a match for the field keys
657 foreach ($returnUniqueMatched as $uniqueVal){
658 $dao->selectAdd($allfields[$uniqueVal]);
661 $dao->setApiFilter($params);
665 * Apply filters (e.g. high, low) to DAO object (prior to find)
666 * @param string $filterField
667 * Field name of filter.
668 * @param string $filterValue
669 * Field value of filter.
673 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
674 if (strstr($filterField, 'high')) {
675 $fieldName = substr($filterField, 0, -5);
676 $dao->whereAdd("($fieldName <= $filterValue )");
678 if (strstr($filterField, 'low')) {
679 $fieldName = substr($filterField, 0, -4);
680 $dao->whereAdd("($fieldName >= $filterValue )");
682 if($filterField == 'is_current' && $filterValue == 1){
683 $todayStart = date('Ymd000000', strtotime('now'));
684 $todayEnd = date('Ymd235959', strtotime('now'));
685 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
686 if(property_exists($dao, 'is_active')){
687 $dao->whereAdd('is_active = 1');
693 * Get sort, limit etc options from the params - supporting old & new formats.
694 * get returnproperties for legacy
696 * @param array $params
697 * Params array as passed into civicrm_api.
698 * @param bool $queryObject
699 * Is this supporting a queryobject api (e.g contact) - if so we support more options.
700 * for legacy report & return a unique fields array
702 * @param string $entity
703 * @param string $action
705 * @throws API_Exception
706 * @return array $options options extracted from params
708 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
710 $sort = CRM_Utils_Array
::value('sort', $params, 0);
711 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
712 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
714 $offset = CRM_Utils_Array
::value('offset', $params, 0);
715 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
716 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
717 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
719 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
720 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
721 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
723 if (is_array(CRM_Utils_Array
::value('options', $params))) {
724 // is count is set by generic getcount not user
725 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
726 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
727 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
728 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
731 $returnProperties = array();
732 // handle the format return =sort_name,display_name...
733 if (array_key_exists('return', $params)) {
734 if (is_array($params['return'])) {
735 $returnProperties = array_fill_keys($params['return'], 1);
738 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
739 $returnProperties = array_fill_keys($returnProperties, 1);
742 if ($entity && $action == 'get') {
743 if (!empty($returnProperties['id'])) {
744 $returnProperties[$entity . '_id'] = 1;
745 unset($returnProperties['id']);
747 switch (trim(strtolower($sort))){
751 $sort = str_replace('id', $entity . '_id', $sort);
756 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
757 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
758 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
759 'is_count' => $is_count,
760 'return' => !empty($returnProperties) ?
$returnProperties : array(),
763 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
764 throw new API_Exception('invalid string in sort options');
770 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
771 // if the queryobject is being used this should be used
772 $inputParams = array();
773 $legacyreturnProperties = array();
775 'sort', 'offset', 'rowCount', 'options', 'return',
777 foreach ($params as $n => $v) {
778 if (substr($n, 0, 7) == 'return.') {
779 $legacyreturnProperties[substr($n, 7)] = $v;
781 elseif ($n == 'id') {
782 $inputParams[$entity. '_id'] = $v;
784 elseif (in_array($n, $otherVars)) {
787 $inputParams[$n] = $v;
788 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
789 throw new API_Exception('invalid string');
793 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
794 $options['input_params'] = $inputParams;
799 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find)
801 * @param array $params
802 * Params array as passed into civicrm_api.
807 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
809 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
810 if(!$options['is_count']) {
811 if(!empty($options['limit'])) {
812 $dao->limit((int) $options['offset'], (int) $options['limit']);
814 if (!empty($options['sort'])) {
815 $dao->orderBy($options['sort']);
821 * build fields array. This is the array of fields as it relates to the given DAO
822 * returns unique fields as keys by default but if set but can return by DB fields
824 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
825 $fields = $bao->fields();
827 if (empty($fields['id'])){
828 $entity = _civicrm_api_get_entity_name_from_dao($bao);
829 $fields['id'] = $fields[$entity . '_id'];
830 unset($fields[$entity . '_id']);
835 foreach ($fields as $field) {
836 $dbFields[$field['name']] = $field;
842 * build fields array. This is the array of fields as it relates to the given DAO
843 * returns unique fields as keys by default but if set but can return by DB fields
844 * @param CRM_Core_BAO $bao
848 function _civicrm_api3_get_unique_name_array(&$bao) {
849 $fields = $bao->fields();
850 foreach ($fields as $field => $values) {
851 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
853 return $uniqueFields;
857 * Converts an DAO object to an array
859 * @param CRM_Core_DAO $dao
861 * @param array $params
862 * @param bool $uniqueFields
863 * @param string $entity
864 * @param bool $autoFind
871 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
873 if(isset($params['options']) && !empty($params['options']['is_count'])) {
874 return $dao->count();
879 if ($autoFind && !$dao->find()) {
883 if(isset($dao->count
)) {
887 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
889 while ($dao->fetch()) {
891 foreach ($fields as $key) {
892 if (array_key_exists($key, $dao)) {
893 // not sure on that one
894 if ($dao->$key !== NULL) {
895 $tmp[$key] = $dao->$key;
899 $result[$dao->id
] = $tmp;
901 if(_civicrm_api3_custom_fields_are_required($entity, $params)) {
902 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
910 * We currently retrieve all custom fields or none at this level so if we know the entity
911 * && 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
912 * @todo filter so only required fields are queried
914 * @param array $params
915 * @param string $entity
916 * Entity name in CamelCase.
920 function _civicrm_api3_custom_fields_are_required($entity, $params) {
921 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
924 $options = _civicrm_api3_get_options_from_params($params);
925 //we check for possibility of 'custom' => 1 as well as specific custom fields
926 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
927 if(stristr($returnString, 'custom')) {
932 * Converts an object to an array
935 * (reference) object to convert.
936 * @param array $values
938 * @param array|bool $uniqueFields
944 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
946 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
947 foreach ($fields as $key => $value) {
948 if (array_key_exists($key, $dao)) {
949 $values[$key] = $dao->$key;
955 * Wrapper for _civicrm_object_to_array when api supports unique fields
957 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
958 return _civicrm_api3_object_to_array($dao, $values, TRUE);
963 * @param array $params
964 * @param array $values
965 * @param string $extends
966 * Entity that this custom field extends (e.g. contribution, event, contact).
967 * @param string $entityId
968 * ID of entity per $extends.
970 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
971 $values['custom'] = array();
972 $checkCheckBoxField = FALSE;
974 if(in_array($extends, array('Household', 'Individual', 'Organization'))) {
978 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
979 if(!$fields['is_error']) {
980 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
981 $fields = $fields['values'];
982 $checkCheckBoxField = TRUE;
985 foreach ($params as $key => $value) {
986 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
987 if ($customFieldID && (!is_null($value))) {
988 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
989 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
992 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
993 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1000 * @param array $params
1003 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1004 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1006 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery
::$extendsMap, array_fill_keys($nonGenericEntities, 1));
1007 if(!array_key_exists($entity, $customFieldEntities)) {
1011 _civicrm_api3_custom_format_params($params, $values, $entity);
1012 $params = array_merge($params, $values);
1016 * we can't rely on downstream to add separators to checkboxes so we'll check here. We should look at pushing to BAO function
1017 * 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
1018 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1020 * 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
1021 * don't touch - lots of very cautious code in here
1023 * The resulting array should look like
1029 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1031 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1032 * be fixed in future
1034 * @param $checkboxFieldValue
1035 * @param $customFieldLabel
1039 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1041 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1042 // we can assume it's pre-formatted
1045 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1046 if (!empty($options['is_error'])) {
1047 //the check is precautionary - can probably be removed later
1051 $options = $options['values'];
1053 if (is_array($checkboxFieldValue)) {
1054 foreach ($checkboxFieldValue as $key => $value) {
1055 if (!array_key_exists($key, $options)) {
1056 $validValue = FALSE;
1060 // we have been passed an array that is already in the 'odd' custom field format
1065 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1066 // if the array only has one item we'll treat it like any other string
1067 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1068 $possibleValue = reset($checkboxFieldValue);
1070 if (is_string($checkboxFieldValue)) {
1071 $possibleValue = $checkboxFieldValue;
1073 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1074 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1077 elseif (is_array($checkboxFieldValue)) {
1078 // so this time around we are considering the values in the array
1079 $possibleValues = $checkboxFieldValue;
1080 $formatValue = TRUE;
1082 elseif (stristr($checkboxFieldValue, ',')) {
1083 $formatValue = TRUE;
1084 //lets see if we should separate it - we do this near the end so we
1085 // ensure we have already checked that the comma is not part of a legitimate match
1086 // and of course, we don't make any changes if we don't now have matches
1087 $possibleValues = explode(',', $checkboxFieldValue);
1090 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1094 foreach ($possibleValues as $index => $possibleValue) {
1095 if (array_key_exists($possibleValue, $options)) {
1096 // 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)
1098 elseif (array_key_exists(trim($possibleValue), $options)) {
1099 $possibleValues[$index] = trim($possibleValue);
1102 $formatValue = FALSE;
1106 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1112 * This function ensures that we have the right input parameters
1114 * This function is only called when $dao is passed into verify_mandatory.
1115 * The practice of passing $dao into verify_mandatory turned out to be
1116 * unsatisfactory as the required fields @ the dao level is so diffent to the abstract
1117 * api level. Hence the intention is to remove this function
1118 * & the associated param from viery_mandatory
1120 * @param array $params
1121 * Associative array of property name/value.
1122 * pairs to insert in new history.
1123 * @param string $daoName
1124 * @param bool $return
1126 * @daoName string DAO to check params agains
1128 * @return bool should the missing fields be returned as an array (core error created as default)
1130 * @return bool true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1133 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1134 //@deprecated - see notes
1135 if (isset($params['extends'])) {
1136 if (($params['extends'] == 'Activity' ||
1137 $params['extends'] == 'Phonecall' ||
1138 $params['extends'] == 'Meeting' ||
1139 $params['extends'] == 'Group' ||
1140 $params['extends'] == 'Contribution'
1142 ($params['style'] == 'Tab')
1144 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1148 $dao = new $daoName();
1149 $fields = $dao->fields();
1152 foreach ($fields as $k => $v) {
1153 if ($v['name'] == 'id') {
1157 if (!empty($v['required'])) {
1158 // 0 is a valid input for numbers, CRM-8122
1159 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1165 if (!empty($missing)) {
1166 if (!empty($return)) {
1170 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1178 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this
1180 * @param string $bao_name
1182 * @param array $params
1184 * @param bool $returnAsSuccess
1185 * Return in api success format.
1186 * @param string $entity
1190 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1191 $bao = new $bao_name();
1192 _civicrm_api3_dao_set_filter($bao, $params, TRUE, $entity);
1193 if ($returnAsSuccess) {
1194 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1197 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity, 'get');
1202 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this
1204 * @param string $bao_name
1205 * Name of BAO Class.
1206 * @param array $params
1207 * Parameters passed into the api call.
1208 * @param string $entity
1209 * Entity - pass in if entity is non-standard & required $ids array.
1211 * @throws API_Exception
1214 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1215 _civicrm_api3_format_params_for_create($params, $entity);
1216 $args = array(&$params);
1217 if (!empty($entity)) {
1218 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1222 if (method_exists($bao_name, 'create')) {
1224 $fct_name = $bao_name . '::' . $fct;
1225 $bao = call_user_func_array(array($bao_name, $fct), $args);
1227 elseif (method_exists($bao_name, 'add')) {
1229 $fct_name = $bao_name . '::' . $fct;
1230 $bao = call_user_func_array(array($bao_name, $fct), $args);
1233 $fct_name = '_civicrm_api3_basic_create_fallback';
1234 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1237 if (is_null($bao)) {
1238 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1240 elseif (is_a($bao, 'CRM_Core_Error')) {
1241 //some wierd circular thing means the error takes itself as an argument
1242 $msg = $bao->getMessages($bao);
1243 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1244 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1245 // so we need to reset the error object here to avoid getting concatenated errors
1246 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1247 CRM_Core_Error
::singleton()->reset();
1248 throw new API_Exception($msg);
1252 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1253 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1258 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1260 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1261 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1263 * @param string $bao_name
1264 * @param array $params
1266 * @throws API_Exception
1267 * @return CRM_Core_DAO|NULL an instance of the BAO
1269 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1270 $dao_name = get_parent_class($bao_name);
1271 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1272 $dao_name = $bao_name;
1274 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1275 if (empty($entityName)) {
1276 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1277 'class_name' => $bao_name,
1280 $hook = empty($params['id']) ?
'create' : 'edit';
1282 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1283 $instance = new $dao_name();
1284 $instance->copyValues($params);
1286 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1292 * Function to do a 'standard' api del - when the api is only doing a $bao::del then use this
1293 * if api::del doesn't exist it will try DAO delete method
1295 * @param string $bao_name
1296 * @param array $params
1298 * @return array API result array
1299 * @throws API_Exception
1301 function _civicrm_api3_basic_delete($bao_name, &$params) {
1303 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1304 $args = array(&$params['id']);
1305 if (method_exists($bao_name, 'del')) {
1306 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1307 if ($bao !== FALSE) {
1308 return civicrm_api3_create_success(TRUE);
1310 throw new API_Exception('Could not delete entity id ' . $params['id']);
1312 elseif (method_exists($bao_name, 'delete')) {
1313 $dao = new $bao_name();
1314 $dao->id
= $params['id'];
1316 while ($dao->fetch()) {
1318 return civicrm_api3_create_success();
1322 throw new API_Exception('Could not delete entity id ' . $params['id']);
1326 throw new API_Exception('no delete method found');
1330 * Get custom data for the given entity & Add it to the returnArray as 'custom_123' = 'custom string' AND 'custom_123_1' = 'custom string'
1331 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1333 * @param array $returnArray
1334 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1335 * @param string $entity
1336 * E.g membership, event.
1337 * @param int $entity_id
1338 * @param int $groupID
1339 * Per CRM_Core_BAO_CustomGroup::getTree.
1340 * @param int $subType
1341 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1342 * @param string $subName
1343 * Subtype of entity.
1345 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1346 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1347 CRM_Core_DAO
::$_nullObject,
1353 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1354 $customValues = array();
1355 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1356 $fieldInfo = array();
1357 foreach ($groupTree as $set) {
1358 $fieldInfo +
= $set['fields'];
1360 if (!empty($customValues)) {
1361 foreach ($customValues as $key => $val) {
1362 // per standard - return custom_fieldID
1363 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1364 $returnArray['custom_' . $id] = $val;
1366 //not standard - but some api did this so guess we should keep - cheap as chips
1367 $returnArray[$key] = $val;
1369 // Shim to restore legacy behavior of ContactReference custom fields
1370 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1371 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1372 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1379 * Validate fields being passed into API. This function relies on the getFields function working accurately
1380 * for the given API. If error mode is set to TRUE then it will also check
1383 * As of writing only date was implemented.
1384 * @param string $entity
1385 * @param string $action
1386 * @param array $params
1388 * @param array $fields
1389 * Response from getfields all variables are the same as per civicrm_api.
1390 * @param bool $errorMode
1391 * ErrorMode do intensive post fail checks?.
1394 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = FALSE) {
1395 $fields = array_intersect_key($fields, $params);
1396 foreach ($fields as $fieldName => $fieldInfo) {
1397 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1398 case CRM_Utils_Type
::T_INT
:
1399 //field is of type integer
1400 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1405 case CRM_Utils_Type
::T_TIMESTAMP
:
1406 //field is of type date or datetime
1407 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1411 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1414 case CRM_Utils_Type
::T_STRING
:
1415 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1418 case CRM_Utils_Type
::T_MONEY
:
1419 if (!CRM_Utils_Rule
::money($params[$fieldName]) && !empty($params[$fieldName])) {
1420 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1424 // intensive checks - usually only called after DB level fail
1425 if (!empty($errorMode) && strtolower($action) == 'create') {
1426 if (!empty($fieldInfo['FKClassName'])) {
1427 if (!empty($params[$fieldName])) {
1428 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1430 elseif (!empty($fieldInfo['required'])) {
1431 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1434 if (!empty($fieldInfo['api.unique'])) {
1435 $params['entity'] = $entity;
1436 _civicrm_api3_validate_uniquekey($params, $fieldName, $fieldInfo);
1443 * Validate date fields being passed into API.
1444 * It currently converts both unique fields and DB field names to a mysql date.
1445 * @todo - probably the unique field handling & the if exists handling is now done before this
1446 * function is reached in the wrapper - can reduce this code down to assume we
1447 * are only checking the passed in field
1449 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1450 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1452 * @param array $params
1453 * Params from civicrm_api.
1454 * @param string $fieldName
1455 * Uniquename of field being checked.
1456 * @param array $fieldInfo
1457 * Array of fields from getfields function.
1460 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1461 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1462 if (!empty($params[$fieldInfo['name']])) {
1463 $params[$fieldInfo['name']] = _civicrm_api3_getValidDate($params[$fieldInfo['name']], $fieldInfo['name'], $fieldInfo['type']);
1465 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($params[$fieldName])) {
1466 $params[$fieldName] = _civicrm_api3_getValidDate($params[$fieldName], $fieldName, $fieldInfo['type']);
1471 * convert date into BAO friendly date
1472 * we accept 'whatever strtotime accepts'
1474 * @param string $dateValue
1475 * @param string $fieldName
1481 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1482 if (is_array($dateValue)) {
1483 foreach ($dateValue as $key => $value) {
1484 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1488 if (strtotime($dateValue) === FALSE) {
1489 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1491 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1492 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1496 * Validate foreign constraint fields being passed into API.
1498 * @param array $params
1499 * Params from civicrm_api.
1500 * @param string $fieldName
1501 * Uniquename of field being checked.
1502 * @param array $fieldInfo
1503 * Array of fields from getfields function.
1506 function _civicrm_api3_validate_constraint(&$params, &$fieldName, &$fieldInfo) {
1507 $dao = new $fieldInfo['FKClassName'];
1508 $dao->id
= $params[$fieldName];
1510 $dao->selectAdd('id');
1511 if (!$dao->find()) {
1512 throw new Exception("$fieldName is not valid : " . $params[$fieldName]);
1517 * Validate foreign constraint fields being passed into API.
1519 * @param array $params
1520 * Params from civicrm_api.
1521 * @param string $fieldName
1522 * Uniquename of field being checked.
1524 * Array of fields from getfields function.
1527 function _civicrm_api3_validate_uniquekey(&$params, &$fieldName, &$fieldInfo) {
1528 $existing = civicrm_api($params['entity'], 'get', array(
1529 'version' => $params['version'],
1530 $fieldName => $params[$fieldName],
1532 // an entry already exists for this unique field
1533 if ($existing['count'] == 1) {
1534 // question - could this ever be a security issue?
1535 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1540 * Generic implementation of the "replace" action.
1542 * Replace the old set of entities (matching some given keys) with a new set of
1543 * entities (matching the same keys).
1545 * Note: This will verify that 'values' is present, but it does not directly verify
1546 * any other parameters.
1548 * @param string $entity
1550 * @param array $params
1551 * Params from civicrm_api, including:.
1552 * - 'values': an array of records to save
1553 * - all other items: keys which identify new/pre-existing records
1556 function _civicrm_api3_generic_replace($entity, $params) {
1558 $transaction = new CRM_Core_Transaction();
1560 if (!is_array($params['values'])) {
1561 throw new Exception("Mandatory key(s) missing from params array: values");
1564 // Extract the keys -- somewhat scary, don't think too hard about it
1565 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1567 // Lookup pre-existing records
1568 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1569 if (civicrm_error($preexisting)) {
1570 $transaction->rollback();
1571 return $preexisting;
1574 // Save the new/updated records
1576 foreach ($params['values'] as $replacement) {
1577 // Sugar: Don't force clients to duplicate the 'key' data
1578 $replacement = array_merge($baseParams, $replacement);
1579 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1580 $create = civicrm_api($entity, $action, $replacement);
1581 if (civicrm_error($create)) {
1582 $transaction->rollback();
1585 foreach ($create['values'] as $entity_id => $entity_value) {
1586 $creates[$entity_id] = $entity_value;
1590 // Remove stale records
1591 $staleIDs = array_diff(
1592 array_keys($preexisting['values']),
1593 array_keys($creates)
1595 foreach ($staleIDs as $staleID) {
1596 $delete = civicrm_api($entity, 'delete', array(
1597 'version' => $params['version'],
1600 if (civicrm_error($delete)) {
1601 $transaction->rollback();
1606 return civicrm_api3_create_success($creates, $params);
1608 catch(PEAR_Exception
$e) {
1609 $transaction->rollback();
1610 return civicrm_api3_create_error($e->getMessage());
1612 catch(Exception
$e) {
1613 $transaction->rollback();
1614 return civicrm_api3_create_error($e->getMessage());
1619 * @param array $params
1623 function _civicrm_api3_generic_replace_base_params($params) {
1624 $baseParams = $params;
1625 unset($baseParams['values']);
1626 unset($baseParams['sequential']);
1627 unset($baseParams['options']);
1632 * returns fields allowable by api
1635 * String Entity to query.
1636 * @param bool $unique
1637 * Index by unique fields?.
1638 * @param array $params
1642 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1643 $unsetIfEmpty = array('dataPattern', 'headerPattern', 'default', 'export', 'import');
1644 $dao = _civicrm_api3_get_DAO($entity);
1649 $fields = $d->fields();
1650 // replace uniqueNames by the normal names as the key
1651 if (empty($unique)) {
1652 foreach ($fields as $name => &$field) {
1653 //getting rid of unused attributes
1654 foreach ($unsetIfEmpty as $attr) {
1655 if (empty($field[$attr])) {
1656 unset($field[$attr]);
1659 if ($name == $field['name']) {
1662 if (array_key_exists($field['name'], $fields)) {
1663 $field['error'] = 'name conflict';
1664 // it should never happen, but better safe than sorry
1667 $fields[$field['name']] = $field;
1668 $fields[$field['name']]['uniqueName'] = $name;
1669 unset($fields[$name]);
1672 // Translate FKClassName to the corresponding api
1673 foreach ($fields as $name => &$field) {
1674 if (!empty($field['FKClassName'])) {
1675 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1677 $field['FKApiName'] = $FKApi;
1681 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1686 * Return an array of fields for a given entity - this is the same as the BAO function but
1687 * fields are prefixed with 'custom_' to represent api params
1689 function _civicrm_api_get_custom_fields($entity, &$params) {
1690 $entity = _civicrm_api_get_camel_name($entity);
1691 if ($entity == 'Contact') {
1692 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1693 $entity = CRM_Utils_Array
::value('contact_type', $params);
1695 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1698 // we could / should probably test for other subtypes here - e.g. activity_type_id
1699 CRM_Utils_Array
::value('contact_sub_type', $params),
1708 foreach ($customfields as $key => $value) {
1709 // Regular fields have a 'name' property
1710 $value['name'] = 'custom_' . $key;
1711 $value['title'] = $value['label'];
1712 $value['type'] = _getStandardTypeFromCustomDataType($value['data_type']);
1713 $ret['custom_' . $key] = $value;
1718 * Translate the custom field data_type attribute into a std 'type'
1720 function _getStandardTypeFromCustomDataType($dataType) {
1722 'String' => CRM_Utils_Type
::T_STRING
,
1723 'Int' => CRM_Utils_Type
::T_INT
,
1724 'Money' => CRM_Utils_Type
::T_MONEY
,
1725 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1726 'Float' => CRM_Utils_Type
::T_FLOAT
,
1727 'Date' => CRM_Utils_Type
::T_DATE
,
1728 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1729 'StateProvince' => CRM_Utils_Type
::T_INT
,
1730 'File' => CRM_Utils_Type
::T_STRING
,
1731 'Link' => CRM_Utils_Type
::T_STRING
,
1732 'ContactReference' => CRM_Utils_Type
::T_INT
,
1733 'Country' => CRM_Utils_Type
::T_INT
,
1735 return $mapping[$dataType];
1740 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't
1741 * If multiple aliases the last takes precedence
1743 * Function also swaps unique fields for non-unique fields & vice versa.
1745 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1746 foreach ($fields as $field => $values) {
1747 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1748 if (!empty($values['api.aliases'])) {
1749 // if aliased field is not set we try to use field alias
1750 if (!isset($apiRequest['params'][$field])) {
1751 foreach ($values['api.aliases'] as $alias) {
1752 if (isset($apiRequest['params'][$alias])) {
1753 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1755 //unset original field nb - need to be careful with this as it may bring inconsistencies
1756 // out of the woodwork but will be implementing only as _spec function extended
1757 unset($apiRequest['params'][$alias]);
1761 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
1762 && isset($apiRequest['params'][$values['name']])
1764 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1765 // note that it would make sense to unset the original field here but tests need to be in place first
1767 if (!isset($apiRequest['params'][$field])
1769 && $field != $uniqueName
1770 && array_key_exists($uniqueName, $apiRequest['params'])
1773 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1774 // note that it would make sense to unset the original field here but tests need to be in place first
1781 * Validate integer fields being passed into API.
1782 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user
1784 * @param array $params
1785 * Params from civicrm_api.
1786 * @param string $fieldName
1787 * Uniquename of field being checked.
1788 * @param array $fieldInfo
1789 * Array of fields from getfields function.
1790 * @param string $entity
1791 * @throws API_Exception
1793 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1794 if (!empty($params[$fieldName])) {
1795 // if value = 'user_contact_id' (or similar), replace value with contact id
1796 if (!is_numeric($params[$fieldName]) && is_scalar($params[$fieldName])) {
1797 $realContactId = _civicrm_api3_resolve_contactID($params[$fieldName]);
1798 if ('unknown-user' === $realContactId) {
1799 throw new API_Exception("\"$fieldName\" \"{$params[$fieldName]}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName, "type" => "integer"));
1800 } elseif (is_numeric($realContactId)) {
1801 $params[$fieldName] = $realContactId;
1804 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1805 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1808 // After swapping options, ensure we have an integer(s)
1809 foreach ((array) ($params[$fieldName]) as $value) {
1810 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1811 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1815 // Check our field length
1816 if(is_string($params[$fieldName]) && !empty($fieldInfo['maxlength']) && strlen($params[$fieldName]) > $fieldInfo['maxlength']
1818 throw new API_Exception( $params[$fieldName] . " is " . strlen($params[$fieldName]) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1819 2100, array('field' => $fieldName, "max_length" => $fieldInfo['maxlength'])
1826 * Determine a contact ID using a string expression
1828 * @param string $contactIdExpr
1829 * E.g. "user_contact_id" or "@user:username".
1830 * @return int|NULL|'unknown-user'
1832 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1833 //if value = 'user_contact_id' replace value with logged in user id
1834 if ($contactIdExpr == "user_contact_id") {
1835 return CRM_Core_Session
::getLoggedInContactID();
1837 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1838 $config = CRM_Core_Config
::singleton();
1840 $ufID = $config->userSystem
->getUfId($matches[1]);
1842 return 'unknown-user';
1845 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
1847 return 'unknown-user';
1856 * Validate html (check for scripting attack)
1857 * @param array $params
1858 * @param string $fieldName
1859 * @param array $fieldInfo
1861 * @throws API_Exception
1863 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
1864 if ($value = CRM_Utils_Array
::value($fieldName, $params)) {
1865 if (!CRM_Utils_Rule
::xssString($value)) {
1866 throw new API_Exception(ts('Illegal characters in input (potential scripting attack)'), array("field" => $fieldName, "error_code" => "xss"));
1872 * Validate string fields being passed into API.
1873 * @param array $params
1874 * Params from civicrm_api.
1875 * @param string $fieldName
1876 * Uniquename of field being checked.
1877 * @param array $fieldInfo
1878 * Array of fields from getfields function.
1879 * @param string $entity
1880 * @throws API_Exception
1883 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
1884 // If fieldname exists in params
1885 $value = CRM_Utils_Array
::value($fieldName, $params, '');
1886 if(!is_array($value)){
1887 $value = (string) $value;
1890 //@todo what do we do about passed in arrays. For many of these fields
1891 // the missing piece of functionality is separating them to a separated string
1892 // & many save incorrectly. But can we change them wholesale?
1895 if (!CRM_Utils_Rule
::xssString($value)) {
1896 throw new Exception(ts('Illegal characters in input (potential scripting attack)'));
1898 if ($fieldName == 'currency') {
1899 if (!CRM_Utils_Rule
::currencyCode($value)) {
1900 throw new Exception("Currency not a valid code: $value");
1903 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1904 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1906 // Check our field length
1907 elseif (is_string($value) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($value)) > $fieldInfo['maxlength']) {
1908 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
1909 2100, array('field' => $fieldName)
1916 * Validate & swap out any pseudoconstants / options
1918 * @param array $params: api parameters
1919 * @param string $entity: api entity name
1920 * @param string $fieldName: field name used in api call (not necessarily the canonical name)
1921 * @param array $fieldInfo: getfields meta-data
1923 function _civicrm_api3_api_match_pseudoconstant(&$params, $entity, $fieldName, $fieldInfo) {
1924 $options = CRM_Utils_Array
::value('options', $fieldInfo);
1926 if(strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
1927 // we need to get the options from the entity the field relates to
1928 $entity = $fieldInfo['entity'];
1930 $options = civicrm_api($entity, 'getoptions', array('version' => 3, 'field' => $fieldInfo['name'], 'context' => 'validate'));
1931 $options = CRM_Utils_Array
::value('values', $options, array());
1934 // If passed a value-separated string, explode to an array, then re-implode after matching values
1936 if (is_string($params[$fieldName]) && strpos($params[$fieldName], CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
1937 $params[$fieldName] = CRM_Utils_Array
::explodePadded($params[$fieldName]);
1940 // If passed multiple options, validate each
1941 if (is_array($params[$fieldName])) {
1942 foreach ($params[$fieldName] as &$value) {
1943 if (!is_array($value)) {
1944 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
1947 // TODO: unwrap the call to implodePadded from the conditional and do it always
1948 // need to verify that this is safe and doesn't break anything though.
1949 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
1951 CRM_Utils_Array
::implodePadded($params[$fieldName]);
1955 _civicrm_api3_api_match_pseudoconstant_value($params[$fieldName], $options, $fieldName);
1960 * Validate & swap a single option value for a field
1962 * @param string $value: field value
1963 * @param array $options: array of options for this field
1964 * @param string $fieldName: field name used in api call (not necessarily the canonical name)
1965 * @throws API_Exception
1967 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
1968 // If option is a key, no need to translate
1969 if (array_key_exists($value, $options)) {
1973 // Translate value into key
1974 $newValue = array_search($value, $options);
1975 if ($newValue !== FALSE) {
1979 // Case-insensitive matching
1980 $newValue = strtolower($value);
1981 $options = array_map("strtolower", $options);
1982 $newValue = array_search($newValue, $options);
1983 if ($newValue === FALSE) {
1984 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
1990 * Returns the canonical name of a field
1993 * : api entity name (string should already be standardized - no camelCase).
1995 * : any variation of a field's name (name, unique_name, api.alias).
1997 * @return bool|string (string|bool) fieldName or FALSE if the field does not exist
1999 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
2000 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2003 if ($fieldName == "{$entity}_id") {
2006 $result = civicrm_api($entity, 'getfields', array(
2008 'action' => 'create',
2010 $meta = $result['values'];
2011 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2012 $fieldName = $fieldName . '_id';
2014 if (isset($meta[$fieldName])) {
2015 return $meta[$fieldName]['name'];
2017 foreach ($meta as $info) {
2018 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2019 return $info['name'];
2021 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
2022 return $info['name'];
2029 * @param string $entity
2030 * @param array $result
2031 * @return string|array|null
2033 function _civicrm_api3_deprecation_check($entity, $result = array()) {
2035 $apiFile = 'api/v3/' . _civicrm_api_get_camel_name($entity) . '.php';
2036 if (CRM_Utils_File
::isIncludable($apiFile)) {
2037 require_once $apiFile;
2039 $entity = _civicrm_api_get_entity_name_from_camel($entity);
2040 $fnName = "_civicrm_api3_{$entity}_deprecation";
2041 if (function_exists($fnName)) {
2042 return $fnName($result);