3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * File for CiviCRM APIv3 utilitity functions
31 * @package CiviCRM_APIv3
32 * @subpackage API_utils
34 * @copyright CiviCRM LLC (c) 2004-2013
35 * @version $Id: utils.php 30879 2010-11-22 15:45:55Z shot $
40 * Initialize CiviCRM - should be run at the start of each API function
42 function _civicrm_api3_initialize() {
43 require_once 'CRM/Core/ClassLoader.php';
44 CRM_Core_ClassLoader
::singleton()->register();
45 CRM_Core_Config
::singleton();
49 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking
51 * @param array $params array of fields to check
52 * @param array $daoName string DAO to check for required fields (create functions only)
53 * @param array $keys list of required fields options. One of the options is required
54 * @return null or throws error if there the required fields not present
59 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = array(
61 $keys = array(array());
62 foreach ($keyoptions as $key) {
65 civicrm_api3_verify_mandatory($params, $daoName, $keys);
69 * Function to check mandatory fields are included
71 * @param array $params array of fields to check
72 * @param array $daoName string DAO to check for required fields (create functions only)
73 * @param array $keys list of required fields. A value can be an array denoting that either this or that is required.
74 * @param bool $verifyDAO
76 * @return null or throws error if there the required fields not present
78 * @todo see notes on _civicrm_api3_check_required_fields regarding removing $daoName param
80 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = array(
81 ), $verifyDAO = TRUE) {
84 if ($daoName != NULL && $verifyDAO && empty($params['id'])) {
85 $unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
86 if (!is_array($unmatched)) {
91 if (!empty($params['id'])) {
92 $keys = array('version');
95 if (!in_array('version', $keys)) {
96 // required from v3 onwards
100 foreach ($keys as $key) {
101 if (is_array($key)) {
103 $optionset = array();
104 foreach ($key as $subkey) {
105 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
106 $optionset[] = $subkey;
109 // as long as there is one match then we don't need to rtn anything
113 if (empty($match) && !empty($optionset)) {
114 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
118 if (!array_key_exists($key, $params) ||
empty($params[$key])) {
123 if (!empty($unmatched)) {
124 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched),"mandatory_missing",array("fields"=>$unmatched));
131 * @param <type> $data
132 * @param object $dao DAO / BAO object to be freed here
136 function civicrm_api3_create_error($msg, $data = array(), &$dao = NULL) {
137 //fix me - $dao should be param 4 & 3 should be $apiRequest
138 if (is_object($dao)) {
142 if (is_array($dao)) {
143 if ($msg == 'DB Error: constraint violation' ||
substr($msg, 0,9) == 'DB Error:' ||
$msg == 'DB Error: already exists') {
145 _civicrm_api3_validate_fields($dao['entity'], $dao['action'], $dao['params'], TRUE);
147 catch(Exception
$e) {
148 $msg = $e->getMessage();
152 $data['is_error'] = 1;
153 $data['error_message'] = $msg;
154 if (is_array($dao) && isset($dao['params']) && is_array($dao['params']) && CRM_Utils_Array
::value('api.has_parent', $dao['params'])) {
155 $errorCode = empty($data['error_code']) ?
'chained_api_failed' : $data['error_code'];
156 throw new API_Exception('Error in call to ' . $dao['entity'] . '_' . $dao['action'] . ' : ' . $msg, $errorCode, $data);
162 * Format array in result output styple
164 * @param array $values values generated by API operation (the result)
165 * @param array $params parameters passed into API call
166 * @param string $entity the entity being acted on
167 * @param string $action the action passed to the API
168 * @param object $dao DAO object to be freed here
169 * @param array $extraReturnValues additional values to be added to top level of result array(
170 * - this param is currently used for legacy behaviour support
172 * @return array $result
174 function civicrm_api3_create_success($values = 1, $params = array(
175 ), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
177 $result['is_error'] = 0;
178 //lets set the ['id'] field if it's not set & we know what the entity is
179 if (is_array($values) && !empty($entity)) {
180 foreach ($values as $key => $item) {
181 if (empty($item['id']) && !empty($item[$entity . "_id"])) {
182 $values[$key]['id'] = $item[$entity . "_id"];
184 if(!empty($item['financial_type_id'])){
185 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
190 if (is_array($params) && !empty($params['debug'])) {
191 if (is_string($action) && $action != 'getfields') {
192 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) +
$params);
194 elseif ($action != 'getfields') {
195 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
201 $allFields = array();
202 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
203 $allFields = array_keys($apiFields['values']);
205 $paramFields = array_keys($params);
206 $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'));
208 $result['undefined_fields'] = array_merge($undefined);
211 if (is_object($dao)) {
215 $result['version'] = 3;
216 if (is_array($values)) {
217 $result['count'] = count($values);
219 // Convert value-separated strings to array
220 _civicrm_api3_separate_values($values);
222 if ($result['count'] == 1) {
223 list($result['id']) = array_keys($values);
225 elseif (!empty($values['id']) && is_int($values['id'])) {
226 $result['id'] = $values['id'];
230 $result['count'] = !empty($values) ?
1 : 0;
233 if (is_array($values) && isset($params['sequential']) &&
234 $params['sequential'] == 1
236 $result['values'] = array_values($values);
239 $result['values'] = $values;
242 return array_merge($result, $extraReturnValues);
246 * Load the DAO of the entity
248 function _civicrm_api3_load_DAO($entity) {
249 $dao = _civicrm_api3_get_DAO($entity);
258 * Function to return the DAO of the function or Entity
259 * @param $name is either a function of the api (civicrm_{entity}_create or the entity name
260 * return the DAO name to manipulate this function
261 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
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 if (strtolower($name) == 'individual' ||
strtolower($name) == 'household' ||
strtolower($name) == 'organization') {
274 //hack to deal with incorrectly named BAO/DAO - see CRM-10859 -
275 // several of these have been removed but am not confident mailing_recipients is
276 // tests so have not tackled.
277 // correct approach for im is unclear
278 if($name == 'mailing_recipients' ||
$name == 'MailingRecipients'){
279 return 'CRM_Mailing_BAO_Recipients';
281 if(strtolower($name) == 'im'){
282 return 'CRM_Core_BAO_IM';
284 return CRM_Core_DAO_AllCoreTables
::getFullName(_civicrm_api_get_camel_name($name, 3));
288 * Function to return the DAO of the function or Entity
289 * @param $name is either a function of the api (civicrm_{entity}_create or the entity name
290 * return the DAO name to manipulate this function
291 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
293 function _civicrm_api3_get_BAO($name) {
294 $dao = _civicrm_api3_get_DAO($name);
295 $dao = str_replace("DAO", "BAO", $dao);
300 * Recursive function to explode value-separated strings into arrays
303 function _civicrm_api3_separate_values(&$values) {
304 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
305 foreach ($values as $key => & $value) {
306 if (is_array($value)) {
307 _civicrm_api3_separate_values($value);
309 elseif (is_string($value)) {
310 if($key == 'case_type_id'){// this is to honor the way case API was originally written
311 $value = trim(str_replace($sp, ',', $value), ',');
313 elseif (strpos($value, $sp) !== FALSE) {
314 $value = explode($sp, trim($value, $sp));
321 * This is a legacy wrapper for api_store_values which will check the suitable fields using getfields
322 * rather than DAO->fields
324 * Getfields has handling for how to deal with uniquenames which dao->fields doesn't
326 * Note this is used by BAO type create functions - eg. contribution
327 * @param string $entity
328 * @param array $params
329 * @param array $values
331 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values){
332 $fields = civicrm_api($entity,'getfields', array('version' => 3,'action' => 'create'));
333 $fields = $fields['values'];
334 _civicrm_api3_store_values($fields, $params, $values);
338 * @param array $fields
339 * @param array $params
340 * @param array $values
342 * @return Bool $valueFound
344 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
347 $keys = array_intersect_key($params, $fields);
348 foreach ($keys as $name => $value) {
349 if ($name !== 'id') {
350 $values[$name] = $value;
357 * The API supports 2 types of get requestion. The more complex uses the BAO query object.
358 * This is a generic function for those functions that call it
360 * At the moment only called by contact we should extend to contribution &
361 * others that use the query object. Note that this function passes permission information in.
364 * @param array $params as passed into api get or getcount function
365 * @param array $options array of options (so we can modify the filter)
366 * @param bool $getCount are we just after the count
368 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL){
370 // Convert id to e.g. contact_id
371 if (empty($params[$entity . '_id']) && isset($params['id'])) {
372 $params[$entity . '_id'] = $params['id'];
374 unset($params['id']);
376 $options = _civicrm_api3_get_options_from_params($params, TRUE);
378 $inputParams = array_merge(
379 CRM_Utils_Array
::value('input_params', $options, array()),
380 CRM_Utils_Array
::value('input_params', $additional_options, array())
382 $returnProperties = array_merge(
383 CRM_Utils_Array
::value('return', $options, array()),
384 CRM_Utils_Array
::value('return', $additional_options, array())
386 if(empty($returnProperties)){
387 $returnProperties = NULL;
389 if(!empty($params['check_permissions'])){
390 // we will filter query object against getfields
391 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
392 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
393 $fields['values'][$entity . '_id'] = array();
394 $varsToFilter = array('returnProperties', 'inputParams');
395 foreach ($varsToFilter as $varToFilter){
396 if(!is_array($
$varToFilter)){
399 //I was going to throw an exception rather than silently filter out - but
400 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
401 //so we are silently ignoring parts of their request
402 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
403 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
406 $options = array_merge($options,$additional_options);
407 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
408 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
409 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
410 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
414 $returnProperties = NULL;
417 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
418 $skipPermissions = CRM_Utils_Array
::value('check_permissions', $params)?
0 :1;
419 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
430 if ($getCount) { // only return the count of contacts
438 * Function transfers the filters being passed into the DAO onto the params object
440 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $entity) {
441 $entity = substr($dao->__table
, 8);
443 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
445 $fields = array_intersect(array_keys($allfields), array_keys($params));
446 if (isset($params[$entity . "_id"])) {
447 //if entity_id is set then treat it as ID (will be overridden by id if set)
448 $dao->id
= $params[$entity . "_id"];
451 $options = _civicrm_api3_get_options_from_params($params);
452 //apply options like sort
453 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
455 //accept filters like filter.activity_date_time_high
456 // std is now 'filters' => ..
457 if (strstr(implode(',', array_keys($params)), 'filter')) {
458 if (isset($params['filters']) && is_array($params['filters'])) {
459 foreach ($params['filters'] as $paramkey => $paramvalue) {
460 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
464 foreach ($params as $paramkey => $paramvalue) {
465 if (strstr($paramkey, 'filter')) {
466 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
471 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
472 // support for other syntaxes is discussed in ticket but being put off for now
473 $acceptedSQLOperators = array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN');
478 foreach ($fields as $field) {
479 if (is_array($params[$field])) {
480 //get the actual fieldname from db
481 $fieldName = $allfields[$field]['name'];
482 //array is the syntax for SQL clause
483 foreach ($params[$field] as $operator => $criteria) {
484 if (in_array($operator, $acceptedSQLOperators)) {
490 $dao->whereAdd(sprintf('%s %s', $fieldName, $operator));
497 if (empty($criteria[0]) ||
empty($criteria[1])) {
498 throw new exception("invalid criteria for $operator");
500 $dao->whereAdd(sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
507 if (empty($criteria)) {
508 throw new exception("invalid criteria for $operator");
510 $escapedCriteria = array_map(array('CRM_Core_DAO', 'escapeString'), $criteria);
511 $dao->whereAdd(sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
518 $dao->whereAdd(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
525 $daoFieldName = $allfields[$field]['name'];
526 if (empty($daoFieldName)) {
527 throw new API_Exception("Failed to determine field name for \"$field\"");
529 $dao->{$daoFieldName} = $params[$field];
532 $dao->$field = $params[$field];
536 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
538 $options['return']['id'] = TRUE;// ensure 'id' is included
539 $allfields = _civicrm_api3_get_unique_name_array($dao);
540 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
541 foreach ($returnMatched as $returnValue) {
542 $dao->selectAdd($returnValue);
545 $unmatchedFields = array_diff(// not already matched on the field names
546 array_keys($options['return']),
550 $returnUniqueMatched = array_intersect(
552 array_flip($allfields)// but a match for the field keys
554 foreach ($returnUniqueMatched as $uniqueVal){
555 $dao->selectAdd($allfields[$uniqueVal]);
561 * Apply filters (e.g. high, low) to DAO object (prior to find)
562 * @param string $filterField field name of filter
563 * @param string $filterValue field value of filter
564 * @param object $dao DAO object
566 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
567 if (strstr($filterField, 'high')) {
568 $fieldName = substr($filterField, 0, -5);
569 $dao->whereAdd("($fieldName <= $filterValue )");
571 if (strstr($filterField, 'low')) {
572 $fieldName = substr($filterField, 0, -4);
573 $dao->whereAdd("($fieldName >= $filterValue )");
575 if($filterField == 'is_current' && $filterValue == 1){
576 $todayStart = date('Ymd000000', strtotime('now'));
577 $todayEnd = date('Ymd235959', strtotime('now'));
578 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
579 if(property_exists($dao, 'is_active')){
580 $dao->whereAdd('is_active = 1');
586 * Get sort, limit etc options from the params - supporting old & new formats.
587 * get returnproperties for legacy
588 * @param array $params params array as passed into civicrm_api
589 * @param bool $queryObject - is this supporting a queryobject api (e.g contact) - if so we support more options
590 * for legacy report & return a unique fields array
591 * @return array $options options extracted from params
593 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
595 $sort = CRM_Utils_Array
::value('sort', $params, 0);
596 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
597 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
599 $offset = CRM_Utils_Array
::value('offset', $params, 0);
600 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
601 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
602 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
604 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
605 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
606 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
608 if (is_array(CRM_Utils_Array
::value('options', $params))) {
609 // is count is set by generic getcount not user
610 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
611 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
612 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
613 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
616 $returnProperties = array();
617 // handle the format return =sort_name,display_name...
618 if (array_key_exists('return', $params)) {
619 if (is_array($params['return'])) {
620 $returnProperties = array_fill_keys($params['return'], 1);
623 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
624 $returnProperties = array_fill_keys($returnProperties, 1);
627 if($entity && $action =='get' ){
628 if(CRM_Utils_Array
::value('id',$returnProperties)){
629 $returnProperties[$entity . '_id'] = 1;
630 unset($returnProperties['id']);
632 switch (trim(strtolower($sort))){
636 $sort = str_replace('id', $entity . '_id',$sort);
645 'is_count' => $is_count,
646 'return' => !empty($returnProperties) ?
$returnProperties : NULL,
652 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
653 // if the queryobject is being used this should be used
654 $inputParams = array();
655 $legacyreturnProperties = array();
657 'sort', 'offset', 'rowCount', 'options','return',
659 foreach ($params as $n => $v) {
660 if (substr($n, 0, 7) == 'return.') {
661 $legacyreturnProperties[substr($n, 7)] = $v;
664 $inputParams[$entity. '_id'] = $v;
666 elseif (in_array($n, $otherVars)) {}
668 $inputParams[$n] = $v;
671 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
672 $options['input_params'] = $inputParams;
677 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find)
678 * @param array $params params array as passed into civicrm_api
679 * @param object $dao DAO object
681 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
683 $options = _civicrm_api3_get_options_from_params($params,FALSE,$entity);
684 if(!$options['is_count']) {
685 $dao->limit((int)$options['offset'], (int)$options['limit']);
686 if (!empty($options['sort'])) {
687 $dao->orderBy($options['sort']);
693 * build fields array. This is the array of fields as it relates to the given DAO
694 * returns unique fields as keys by default but if set but can return by DB fields
696 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
697 $fields = $bao->fields();
699 if(!CRM_Utils_Array
::value('id', $fields)){
700 $entity = _civicrm_api_get_entity_name_from_dao($bao);
701 $fields['id'] = $fields[$entity . '_id'];
702 unset($fields[$entity . '_id']);
707 foreach ($fields as $field) {
708 $dbFields[$field['name']] = $field;
714 * build fields array. This is the array of fields as it relates to the given DAO
715 * returns unique fields as keys by default but if set but can return by DB fields
717 function _civicrm_api3_get_unique_name_array(&$bao) {
718 $fields = $bao->fields();
719 foreach ($fields as $field => $values) {
720 $uniqueFields[$field] = CRM_Utils_Array
::value('name',$values, $field);
722 return $uniqueFields;
726 * Converts an DAO object to an array
728 * @param object $dao (reference )object to convert
729 * @params array of arrays (key = id) of array of fields
733 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "") {
735 if(isset($params['options']) && CRM_Utils_Array
::value('is_count', $params['options'])) {
736 return $dao->count();
738 if (empty($dao) ||
!$dao->find()) {
742 if(isset($dao->count
)) {
745 //if custom fields are required we will endeavour to set them . NB passing $entity in might be a bit clunky / unrequired
746 if (!empty($entity) && CRM_Utils_Array
::value('return', $params) && is_array($params['return'])) {
747 foreach ($params['return'] as $return) {
748 if (substr($return, 0, 6) == 'custom') {
755 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
757 while ($dao->fetch()) {
759 foreach ($fields as $key) {
760 if (array_key_exists($key, $dao)) {
761 // not sure on that one
762 if ($dao->$key !== NULL) {
763 $tmp[$key] = $dao->$key;
767 $result[$dao->id
] = $tmp;
768 if (!empty($custom)) {
769 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
778 * Converts an object to an array
780 * @param object $dao (reference) object to convert
781 * @param array $values (reference) array
782 * @param array $uniqueFields
788 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
790 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
791 foreach ($fields as $key => $value) {
792 if (array_key_exists($key, $dao)) {
793 $values[$key] = $dao->$key;
799 * Wrapper for _civicrm_object_to_array when api supports unique fields
801 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
802 return _civicrm_api3_object_to_array($dao, $values, TRUE);
807 * @param array $params
808 * @param array $values
809 * @param string $extends entity that this custom field extends (e.g. contribution, event, contact)
810 * @param string $entityId ID of entity per $extends
812 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
813 $values['custom'] = array();
814 foreach ($params as $key => $value) {
815 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
816 if ($customFieldID && (!IS_NULL($value))) {
817 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
818 $value, $extends, $customValueID, $entityId, FALSE, FALSE
826 * This function ensures that we have the right input parameters
828 * This function is only called when $dao is passed into verify_mandatory.
829 * The practice of passing $dao into verify_mandatory turned out to be
830 * unsatisfactory as the required fields @ the dao level is so diffent to the abstract
831 * api level. Hence the intention is to remove this function
832 * & the associated param from viery_mandatory
834 * @param array $params Associative array of property name/value
835 * pairs to insert in new history.
836 * @daoName string DAO to check params agains
838 * @return bool should the missing fields be returned as an array (core error created as default)
840 * @return bool true if all fields present, depending on $result a core error is created of an array of missing fields is returned
843 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
844 //@deprecated - see notes
845 if (isset($params['extends'])) {
846 if (($params['extends'] == 'Activity' ||
847 $params['extends'] == 'Phonecall' ||
848 $params['extends'] == 'Meeting' ||
849 $params['extends'] == 'Group' ||
850 $params['extends'] == 'Contribution'
852 ($params['style'] == 'Tab')
854 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
858 $dao = new $daoName();
859 $fields = $dao->fields();
862 foreach ($fields as $k => $v) {
863 if ($v['name'] == 'id') {
867 if (CRM_Utils_Array
::value('required', $v)) {
868 // 0 is a valid input for numbers, CRM-8122
869 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
875 if (!empty($missing)) {
876 if (!empty($return)) {
880 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
888 * Check permissions for a given API call.
890 * @param $entity string API entity being accessed
891 * @param $action string API action being performed
892 * @param $params array params of the API call
893 * @param $throw bool whether to throw exception instead of returning false
895 * @return bool whether the current API user has the permission to make the call
897 function _civicrm_api3_api_check_permission($entity, $action, &$params, $throw = TRUE) {
898 // return early unless we’re told explicitly to do the permission check
899 if (empty($params['check_permissions']) or $params['check_permissions'] == FALSE) {
903 require_once 'CRM/Core/DAO/permissions.php';
904 $permissions = _civicrm_api3_permissions($entity, $action, $params);
906 // $params might’ve been reset by the alterAPIPermissions() hook
907 if (isset($params['check_permissions']) and $params['check_permissions'] == FALSE) {
911 foreach ($permissions as $perm) {
912 if (!CRM_Core_Permission
::check($perm)) {
914 throw new Exception("API permission check failed for $entity/$action call; missing permission: $perm.");
925 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this
927 * @param string $bao_name name of BAO
928 * @param array $params params from api
929 * @param bool $returnAsSuccess return in api success format
931 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
932 $bao = new $bao_name();
933 _civicrm_api3_dao_set_filter($bao, $params, TRUE,$entity);
934 if ($returnAsSuccess) {
935 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity);
938 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity);
943 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this
944 * @param string $bao_name Name of BAO Class
945 * @param array $params parameters passed into the api call
946 * @param string $entity Entity - pass in if entity is non-standard & required $ids array
948 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
950 $args = array(&$params);
951 if (!empty($entity)) {
952 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
956 if (method_exists($bao_name, 'create')) {
958 $fct_name = $bao_name . '::' . $fct;
959 $bao = call_user_func_array(array($bao_name, $fct), $args);
961 elseif (method_exists($bao_name, 'add')) {
963 $fct_name = $bao_name . '::' . $fct;
964 $bao = call_user_func_array(array($bao_name, $fct), $args);
967 $fct_name = '_civicrm_api3_basic_create_fallback';
968 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
972 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
976 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
977 return civicrm_api3_create_success($values, $params, NULL, 'create', $bao);
982 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
984 * FIXME There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
985 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
987 * @param string $bao_name
988 * @param array $params
989 * @return CRM_Core_DAO|NULL an instance of the BAO
991 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
992 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName(get_parent_class($bao_name));
993 if (empty($entityName)) {
994 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
995 'class_name' => $bao_name,
998 $hook = empty($params['id']) ?
'create' : 'edit';
1000 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1001 $instance = new $bao_name();
1002 $instance->copyValues($params);
1004 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1010 * Function to do a 'standard' api del - when the api is only doing a $bao::del then use this
1011 * if api::del doesn't exist it will try DAO delete method
1013 function _civicrm_api3_basic_delete($bao_name, &$params) {
1015 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1016 $args = array(&$params['id']);
1017 if (method_exists($bao_name, 'del')) {
1018 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1019 if ($bao !== FALSE) {
1020 return civicrm_api3_create_success(TRUE);
1022 return civicrm_api3_create_error('Could not delete entity id ' . $params['id']);
1024 elseif (method_exists($bao_name, 'delete')) {
1025 $dao = new $bao_name();
1026 $dao->id
= $params['id'];
1028 while ($dao->fetch()) {
1030 return civicrm_api3_create_success();
1034 return civicrm_api3_create_error('Could not delete entity id ' . $params['id']);
1038 return civicrm_api3_create_error('no delete method found');
1042 * Get custom data for the given entity & Add it to the returnArray as 'custom_123' = 'custom string' AND 'custom_123_1' = 'custom string'
1043 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1045 * @param array $returnArray - array to append custom data too - generally $result[4] where 4 is the entity id.
1046 * @param string $entity e.g membership, event
1047 * @param int $groupID - per CRM_Core_BAO_CustomGroup::getTree
1048 * @param int $subType e.g. membership_type_id where custom data doesn't apply to all membership types
1049 * @param string $subName - Subtype of entity
1052 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1053 $groupTree = &CRM_Core_BAO_CustomGroup
::getTree($entity,
1054 CRM_Core_DAO
::$_nullObject,
1060 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1061 $customValues = array();
1062 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1063 if (!empty($customValues)) {
1064 foreach ($customValues as $key => $val) {
1065 if (strstr($key, '_id')) {
1066 $idkey = substr($key, 0, -3);
1067 $returnArray['custom_' . (CRM_Core_BAO_CustomField
::getKeyID($idkey) . "_id")] = $val;
1068 $returnArray[$key] = $val;
1071 // per standard - return custom_fieldID
1072 $returnArray['custom_' . (CRM_Core_BAO_CustomField
::getKeyID($key))] = $val;
1074 //not standard - but some api did this so guess we should keep - cheap as chips
1075 $returnArray[$key] = $val;
1082 * Validate fields being passed into API. This function relies on the getFields function working accurately
1083 * for the given API. If error mode is set to TRUE then it will also check
1086 * As of writing only date was implemented.
1087 * @param string $entity
1088 * @param string $action
1089 * @param array $params -
1090 * all variables are the same as per civicrm_api
1092 function _civicrm_api3_validate_fields($entity, $action, &$params, $errorMode = NULL) {
1093 //skip any entities without working getfields functions
1094 $skippedEntities = array('entity', 'mailinggroup', 'customvalue', 'custom_value', 'mailing_group');
1095 if (in_array(strtolower($entity), $skippedEntities) ||
strtolower($action) == 'getfields') {
1098 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action));
1099 $fields = array_intersect_key($fields['values'], $params);
1100 foreach ($fields as $fieldName => $fieldInfo) {
1101 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1102 case CRM_Utils_Type
::T_INT
:
1103 //field is of type integer
1104 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1109 //field is of type date or datetime
1110 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1114 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1117 case CRM_Utils_Type
::T_STRING
:
1118 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1121 case CRM_Utils_Type
::T_MONEY
:
1122 if (!CRM_Utils_Rule
::money($params[$fieldName])) {
1123 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1127 // intensive checks - usually only called after DB level fail
1128 if (!empty($errorMode) && strtolower($action) == 'create') {
1129 if (CRM_Utils_Array
::value('FKClassName', $fieldInfo)) {
1130 if (CRM_Utils_Array
::value($fieldName, $params)) {
1131 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1133 elseif (CRM_Utils_Array
::value('required', $fieldInfo)) {
1134 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1137 if (CRM_Utils_Array
::value('api.unique', $fieldInfo)) {
1138 $params['entity'] = $entity;
1139 _civicrm_api3_validate_uniquekey($params, $fieldName, $fieldInfo);
1146 * Validate date fields being passed into API.
1147 * It currently converts both unique fields and DB field names to a mysql date.
1148 * @todo - probably the unique field handling & the if exists handling is now done before this
1149 * function is reached in the wrapper - can reduce this code down to assume we
1150 * are only checking the passed in field
1152 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1153 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1155 * @param array $params params from civicrm_api
1156 * @param string $fieldName uniquename of field being checked
1157 * @param array $fieldinfo array of fields from getfields function
1159 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1160 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1161 if (CRM_Utils_Array
::value($fieldInfo['name'], $params)) {
1162 //accept 'whatever strtotime accepts
1163 if (strtotime($params[$fieldInfo['name']]) === FALSE) {
1164 throw new Exception($fieldInfo['name'] . " is not a valid date: " . $params[$fieldInfo['name']]);
1166 $params[$fieldInfo['name']] = CRM_Utils_Date
::processDate($params[$fieldInfo['name']]);
1168 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && CRM_Utils_Array
::value($fieldName, $params)) {
1169 //If the unique field name differs from the db name & is set handle it here
1170 if (strtotime($params[$fieldName]) === FALSE) {
1171 throw new Exception($fieldName . " is not a valid date: " . $params[$fieldName]);
1173 $params[$fieldName] = CRM_Utils_Date
::processDate($params[$fieldName]);
1178 * Validate foreign constraint fields being passed into API.
1180 * @param array $params params from civicrm_api
1181 * @param string $fieldName uniquename of field being checked
1182 * @param array $fieldinfo array of fields from getfields function
1184 function _civicrm_api3_validate_constraint(&$params, &$fieldName, &$fieldInfo) {
1185 $dao = new $fieldInfo['FKClassName'];
1186 $dao->id
= $params[$fieldName];
1188 $dao->selectAdd('id');
1189 if (!$dao->find()) {
1190 throw new Exception("$fieldName is not valid : " . $params[$fieldName]);
1195 * Validate foreign constraint fields being passed into API.
1197 * @param array $params params from civicrm_api
1198 * @param string $fieldName uniquename of field being checked
1199 * @param array $fieldinfo array of fields from getfields function
1201 function _civicrm_api3_validate_uniquekey(&$params, &$fieldName, &$fieldInfo) {
1202 $existing = civicrm_api($params['entity'], 'get', array(
1203 'version' => $params['version'],
1204 $fieldName => $params[$fieldName],
1206 // an entry already exists for this unique field
1207 if ($existing['count'] == 1) {
1208 // question - could this ever be a security issue?
1209 throw new Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1214 * Generic implementation of the "replace" action.
1216 * Replace the old set of entities (matching some given keys) with a new set of
1217 * entities (matching the same keys).
1219 * Note: This will verify that 'values' is present, but it does not directly verify
1220 * any other parameters.
1222 * @param string $entity entity name
1223 * @param array $params params from civicrm_api, including:
1224 * - 'values': an array of records to save
1225 * - all other items: keys which identify new/pre-existing records
1227 function _civicrm_api3_generic_replace($entity, $params) {
1229 $transaction = new CRM_Core_Transaction();
1231 if (!is_array($params['values'])) {
1232 throw new Exception("Mandatory key(s) missing from params array: values");
1235 // Extract the keys -- somewhat scary, don't think too hard about it
1236 $baseParams = $params;
1237 unset($baseParams['values']);
1238 unset($baseParams['sequential']);
1240 // Lookup pre-existing records
1241 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1242 if (civicrm_error($preexisting)) {
1243 $transaction->rollback();
1244 return $preexisting;
1247 // Save the new/updated records
1249 foreach ($params['values'] as $replacement) {
1250 // Sugar: Don't force clients to duplicate the 'key' data
1251 $replacement = array_merge($baseParams, $replacement);
1252 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1253 $create = civicrm_api($entity, $action, $replacement);
1254 if (civicrm_error($create)) {
1255 $transaction->rollback();
1258 foreach ($create['values'] as $entity_id => $entity_value) {
1259 $creates[$entity_id] = $entity_value;
1263 // Remove stale records
1264 $staleIDs = array_diff(
1265 array_keys($preexisting['values']),
1266 array_keys($creates)
1268 foreach ($staleIDs as $staleID) {
1269 $delete = civicrm_api($entity, 'delete', array(
1270 'version' => $params['version'],
1273 if (civicrm_error($delete)) {
1274 $transaction->rollback();
1279 return civicrm_api3_create_success($creates, $params);
1281 catch(PEAR_Exception
$e) {
1282 $transaction->rollback();
1283 return civicrm_api3_create_error($e->getMessage());
1285 catch(Exception
$e) {
1286 $transaction->rollback();
1287 return civicrm_api3_create_error($e->getMessage());
1292 * returns fields allowable by api
1293 * @param $entity string Entity to query
1294 * @param bool $unique index by unique fields?
1296 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array(
1298 $unsetIfEmpty = array('dataPattern', 'headerPattern', 'default', 'export', 'import');
1299 $dao = _civicrm_api3_get_DAO($entity);
1304 $fields = $d->fields();
1305 // replace uniqueNames by the normal names as the key
1306 if (empty($unique)) {
1307 foreach ($fields as $name => & $field) {
1308 //getting rid of unused attributes
1309 foreach ($unsetIfEmpty as $attr) {
1310 if (empty($field[$attr])) {
1311 unset($field[$attr]);
1314 if ($name == $field['name']) {
1317 if (array_key_exists($field['name'], $fields)) {
1318 $field['error'] = 'name conflict';
1319 // it should never happen, but better safe than sorry
1322 $fields[$field['name']] = $field;
1323 $fields[$field['name']]['uniqueName'] = $name;
1324 unset($fields[$name]);
1327 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1332 * Return an array of fields for a given entity - this is the same as the BAO function but
1333 * fields are prefixed with 'custom_' to represent api params
1335 function _civicrm_api_get_custom_fields($entity, &$params) {
1336 $customfields = array();
1337 $entity = _civicrm_api_get_camel_name($entity);
1338 if (strtolower($entity) == 'contact') {
1339 $entity = CRM_Utils_Array
::value('contact_type', $params);
1341 $retrieveOnlyParent = FALSE;
1342 // we could / should probably test for other subtypes here - e.g. activity_type_id
1343 if($entity == 'Contact'){
1344 empty($params['contact_sub_type']);
1346 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1349 CRM_Utils_Array
::value('contact_sub_type', $params, FALSE),
1351 $retrieveOnlyParent,
1355 // find out if we have any requests to resolve options
1356 $getoptions = CRM_Utils_Array
::value('get_options', CRM_Utils_Array
::value('options',$params));
1357 if(!is_array($getoptions)){
1358 $getoptions = array($getoptions);
1361 foreach ($customfields as $key => $value) {
1362 // Regular fields have a 'name' property
1363 $value['name'] = 'custom_' . $key;
1364 $customfields['custom_' . $key] = $value;
1365 if (in_array('custom_' . $key, $getoptions)) {
1366 $customfields['custom_' . $key]['options'] = CRM_Core_BAO_CustomOption
::valuesByID($key);
1368 unset($customfields[$key]);
1370 return $customfields;
1374 * Return array of defaults for the given API (function is a wrapper on getfields)
1376 function _civicrm_api3_getdefaults($apiRequest) {
1377 $defaults = array();
1379 $result = civicrm_api($apiRequest['entity'],
1383 'action' => $apiRequest['action'],
1387 foreach ($result['values'] as $field => $values) {
1388 if (isset($values['api.default'])) {
1389 $defaults[$field] = $values['api.default'];
1396 * Return array of defaults for the given API (function is a wrapper on getfields)
1398 function _civicrm_api3_getrequired($apiRequest) {
1399 $required = array('version');
1401 $result = civicrm_api($apiRequest['entity'],
1405 'action' => $apiRequest['action'],
1408 foreach ($result['values'] as $field => $values) {
1409 if (CRM_Utils_Array
::value('api.required', $values)) {
1410 $required[] = $field;
1417 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't
1418 * If multiple aliases the last takes precedence
1420 * Function also swaps unique fields for non-unique fields & vice versa.
1422 function _civicrm_api3_swap_out_aliases(&$apiRequest) {
1423 if (strtolower($apiRequest['action'] == 'getfields')) {
1424 if (CRM_Utils_Array
::value('api_action', $apiRequest['params'])) {
1425 $apiRequest['params']['action'] = $apiRequest['params']['api_action'];
1426 unset($apiRequest['params']['api_action']);
1430 $result = civicrm_api($apiRequest['entity'],
1434 'action' => $apiRequest['action'],
1438 foreach ($result['values'] as $field => $values) {
1439 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1440 if (CRM_Utils_Array
::value('api.aliases', $values)) {
1441 // if aliased field is not set we try to use field alias
1442 if (!isset($apiRequest['params'][$field])) {
1443 foreach ($values['api.aliases'] as $alias) {
1444 if (isset($apiRequest['params'][$alias])) {
1445 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1447 //unset original field nb - need to be careful with this as it may bring inconsistencies
1448 // out of the woodwork but will be implementing only as _spec function extended
1449 unset($apiRequest['params'][$alias]);
1453 if (!isset($apiRequest['params'][$field])
1454 && CRM_Utils_Array
::value('name', $values)
1455 && $field != $values['name']
1456 && isset($apiRequest['params'][$values['name']])
1458 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1459 // note that it would make sense to unset the original field here but tests need to be in place first
1461 if (!isset($apiRequest['params'][$field])
1463 && $field != $uniqueName
1464 && array_key_exists($uniqueName, $apiRequest['params'])
1467 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1468 // note that it would make sense to unset the original field here but tests need to be in place first
1475 * Validate integer fields being passed into API.
1476 * It currently converts the incoming value 'user_contact_id' into the id of the currenty logged in user
1478 * @param array $params params from civicrm_api
1479 * @param string $fieldName uniquename of field being checked
1480 * @param array $fieldinfo array of fields from getfields function
1482 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1483 //if fieldname exists in params
1484 if (CRM_Utils_Array
::value($fieldName, $params)) {
1485 // if value = 'user_contact_id' (or similar), replace value with contact id
1486 if (!is_numeric($params[$fieldName]) && is_scalar($params[$fieldName])) {
1487 $realContactId = _civicrm_api3_resolve_contactID($params[$fieldName]);
1488 if ('unknown-user' === $realContactId) {
1489 throw new API_Exception("\"$fieldName\" \"{$params[$fieldName]}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName,"type"=>"integer"));
1490 } elseif (is_numeric($realContactId)) {
1491 $params[$fieldName] = $realContactId;
1494 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1495 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1498 // After swapping options, ensure we have an integer(s)
1499 foreach ((array) ($params[$fieldName]) as $value) {
1500 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1501 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1505 // Check our field length
1506 if(is_string($params[$fieldName]) &&
1507 CRM_Utils_Array
::value('maxlength',$fieldInfo)
1508 && strlen($params[$fieldName]) > $fieldInfo['maxlength']
1510 throw new API_Exception( $params[$fieldName] . " is " . strlen($params[$fieldName]) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1511 2100, array('field' => $fieldName, "max_length"=>$fieldInfo['maxlength'])
1518 * Determine a contact ID using a string expression
1520 * @param string $contactIdExpr e.g. "user_contact_id" or "@user:username"
1521 * @return int|NULL|'unknown-user'
1523 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1524 //if value = 'user_contact_id' replace value with logged in user id
1525 if ($contactIdExpr == "user_contact_id") {
1526 $session = &CRM_Core_Session
::singleton();
1527 if (!is_numeric($session->get('userID'))) {
1530 return $session->get('userID');
1531 } elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1532 $config = CRM_Core_Config
::singleton();
1534 $ufID = $config->userSystem
->getUfId($matches[1]);
1536 return 'unknown-user';
1539 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
1541 return 'unknown-user';
1549 function _civicrm_api3_validate_html(&$params, &$fieldName, &$fieldInfo) {
1550 if ($value = CRM_Utils_Array
::value($fieldName, $params)) {
1551 if (!CRM_Utils_Rule
::xssString($value)) {
1552 throw new API_Exception('Illegal characters in input (potential scripting attack)',array("field"=>$fieldName,"error_code"=>"xss"));
1558 * Validate string fields being passed into API.
1559 * @param array $params params from civicrm_api
1560 * @param string $fieldName uniquename of field being checked
1561 * @param array $fieldinfo array of fields from getfields function
1563 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
1564 // If fieldname exists in params
1565 $value = CRM_Utils_Array
::value($fieldName, $params, '');
1566 if(!is_array($value)){
1567 $value = (string) $value;
1570 //@todo what do we do about passed in arrays. For many of these fields
1571 // the missing piece of functionality is separating them to a separated string
1572 // & many save incorrectly. But can we change them wholesale?
1575 if (!CRM_Utils_Rule
::xssString($value)) {
1576 throw new Exception('Illegal characters in input (potential scripting attack)');
1578 if ($fieldName == 'currency') {
1579 if (!CRM_Utils_Rule
::currencyCode($value)) {
1580 throw new Exception("Currency not a valid code: $value");
1583 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options']) ||
!empty($fieldInfo['enumValues'])) {
1584 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1586 // Check our field length
1587 elseif (is_string($value) && !empty($fieldInfo['maxlength']) && strlen($value) > $fieldInfo['maxlength']) {
1588 throw new API_Exception("Value for $fieldName is " . strlen($value) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
1589 2100, array('field' => $fieldName)
1596 * Validate & swap out any pseudoconstants / options
1598 * @param $params: api parameters
1599 * @param $entity: api entity name
1600 * @param $fieldName: field name used in api call (not necessarily the canonical name)
1601 * @param $fieldInfo: getfields meta-data
1603 function _civicrm_api3_api_match_pseudoconstant(&$params, $entity, $fieldName, $fieldInfo) {
1604 $options = CRM_Utils_Array
::value('options', $fieldInfo);
1606 $options = civicrm_api($entity, 'getoptions', array('version' => 3, 'field' => $fieldInfo['name'], 'context' => 'validate'));
1607 $options = CRM_Utils_Array
::value('values', $options, array());
1610 // If passed a value-seperated string, explode to an array, then re-implode after matching values
1612 if (is_string($params[$fieldName]) && strpos($params[$fieldName], CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
1613 $params[$fieldName] = CRM_Utils_Array
::explodePadded($params[$fieldName]);
1616 // If passed multiple options, validate each
1617 if (is_array($params[$fieldName])) {
1618 foreach ($params[$fieldName] as &$value) {
1619 if (!is_array($value)) {
1620 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
1623 // TODO: unwrap the call to implodePadded from the conditional and do it always
1624 // need to verify that this is safe and doesn't break anything though.
1625 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
1627 CRM_Utils_Array
::implodePadded($params[$fieldName]);
1631 _civicrm_api3_api_match_pseudoconstant_value($params[$fieldName], $options, $fieldName);
1636 * Validate & swap a single option value for a field
1638 * @param $value: field value
1639 * @param $options: array of options for this field
1640 * @param $fieldName: field name used in api call (not necessarily the canonical name)
1642 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
1643 // If option is a key, no need to translate
1644 if (array_key_exists($value, $options)) {
1648 // Translate value into key
1649 $newValue = array_search($value, $options);
1650 if ($newValue !== FALSE) {
1654 // Case-insensitive matching
1655 $newValue = strtolower($value);
1656 $options = array_map("strtolower", $options);
1657 $newValue = array_search($newValue, $options);
1658 if ($newValue === FALSE) {
1659 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
1665 * Returns the canonical name of a field
1666 * @param $entity: api entity name (string should already be standardized - no camelCase)
1667 * @param $fieldName: any variation of a field's name (name, unique_name, api.alias)
1669 * @return (string|bool) fieldName or FALSE if the field does not exist
1671 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
1672 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
1675 if ($fieldName == "{$entity}_id") {
1678 $result = civicrm_api($entity, 'getfields', array(
1680 'action' => 'create',
1682 $meta = $result['values'];
1683 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
1684 $fieldName = $fieldName . '_id';
1686 if (isset($meta[$fieldName])) {
1687 return $meta[$fieldName]['name'];
1689 foreach ($meta as $info) {
1690 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
1691 return $info['name'];
1693 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
1694 return $info['name'];