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?
157 * Format array in result output styple
159 * @param array|int $values values generated by API operation (the result)
160 * @param array $params
161 * Parameters passed into API call.
162 * @param string $entity
163 * The entity being acted on.
164 * @param string $action
165 * The action passed to the API.
167 * DAO object to be freed here.
168 * @param array $extraReturnValues
169 * 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(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
176 $result['is_error'] = 0;
177 //lets set the ['id'] field if it's not set & we know what the entity is
178 if (is_array($values) && !empty($entity) && $action != 'getfields') {
179 foreach ($values as $key => $item) {
180 if (empty($item['id']) && !empty($item[$entity . "_id"])) {
181 $values[$key]['id'] = $item[$entity . "_id"];
183 if (!empty($item['financial_type_id'])) {
184 //4.3 legacy handling
185 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
187 if (!empty($item['next_sched_contribution_date'])) {
188 // 4.4 legacy handling
189 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
194 if (is_array($params) && !empty($params['debug'])) {
195 if (is_string($action) && $action != 'getfields') {
196 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) +
$params);
198 elseif ($action != 'getfields') {
199 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
205 $allFields = array();
206 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
207 $allFields = array_keys($apiFields['values']);
209 $paramFields = array_keys($params);
210 $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'));
212 $result['undefined_fields'] = array_merge($undefined);
215 if (is_object($dao)) {
219 $result['version'] = 3;
220 if (is_array($values)) {
221 $result['count'] = (int) count($values);
223 // Convert value-separated strings to array
224 _civicrm_api3_separate_values($values);
226 if ($result['count'] == 1) {
227 list($result['id']) = array_keys($values);
229 elseif (!empty($values['id']) && is_int($values['id'])) {
230 $result['id'] = $values['id'];
234 $result['count'] = !empty($values) ?
1 : 0;
237 if (is_array($values) && isset($params['sequential']) &&
238 $params['sequential'] == 1
240 $result['values'] = array_values($values);
243 $result['values'] = $values;
245 if (!empty($params['options']['metadata'])) {
246 // we've made metadata an array but only supporting 'fields' atm
247 if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
248 $fields = civicrm_api3($entity, 'getfields', array('action' => substr($action, 0, 3) == 'get' ?
'get' : 'create'));
249 $result['metadata']['fields'] = $fields['values'];
252 // Report deprecations
253 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
254 // Always report "update" action as deprecated
255 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'update')) {
256 $deprecated = ((array) $deprecated) +
array('update' => 'The "update" action is deprecated. Use "create" with an id instead.');
259 // Metadata-level deprecations or wholesale entity deprecations
260 if ($entity == 'entity' ||
$action == 'getactions' ||
is_string($deprecated)) {
261 $result['deprecated'] = $deprecated;
263 // Action-specific deprecations
264 elseif (!empty($deprecated[$action])) {
265 $result['deprecated'] = $deprecated[$action];
268 return array_merge($result, $extraReturnValues);
272 * Load the DAO of the entity
274 function _civicrm_api3_load_DAO($entity) {
275 $dao = _civicrm_api3_get_DAO($entity);
284 * return the DAO of the function or Entity
285 * @param string $name
286 * Either a function of the api (civicrm_{entity}_create or the entity name.
287 * return the DAO name to manipulate this function
288 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
289 * @return mixed|string
291 function _civicrm_api3_get_DAO($name) {
292 if (strpos($name, 'civicrm_api3') !== FALSE) {
293 $last = strrpos($name, '_');
294 // len ('civicrm_api3_') == 13
295 $name = substr($name, 13, $last - 13);
298 $name = _civicrm_api_get_camel_name($name, 3);
300 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
304 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
306 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
307 if ($name == 'MailingEventQueue') {
308 return 'CRM_Mailing_Event_DAO_Queue';
310 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
311 // but am not confident mailing_recipients is tested so have not tackled.
312 if ($name == 'MailingRecipients') {
313 return 'CRM_Mailing_DAO_Recipients';
315 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
316 if ($name == 'MailingComponent') {
317 return 'CRM_Mailing_DAO_Component';
319 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
320 if ($name == 'AclRole') {
321 return 'CRM_ACL_DAO_EntityRole';
323 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
324 // But this would impact SMS extensions so need to coordinate
325 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
326 if ($name == 'SmsProvider') {
327 return 'CRM_SMS_DAO_Provider';
329 // FIXME: DAO names should follow CamelCase convention
330 if ($name == 'Im' ||
$name == 'Acl') {
331 $name = strtoupper($name);
333 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
334 if ($dao ||
!$name) {
338 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
339 if (file_exists("api/v3/$name.php")) {
340 include_once "api/v3/$name.php";
343 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
344 if (function_exists($daoFn)) {
352 * return the DAO of the function or Entity
353 * @param string $name
354 * Is either a function of the api (civicrm_{entity}_create or the entity name.
355 * return the DAO name to manipulate this function
356 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
359 function _civicrm_api3_get_BAO($name) {
360 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
361 if ($name == 'PrintLabel') {
362 return 'CRM_Badge_BAO_Layout';
364 $dao = _civicrm_api3_get_DAO($name);
368 $bao = str_replace("DAO", "BAO", $dao);
369 $file = strtr($bao, '_', '/') . '.php';
370 // Check if this entity actually has a BAO. Fall back on the DAO if not.
371 return stream_resolve_include_path($file) ?
$bao : $dao;
375 * Recursive function to explode value-separated strings into arrays
378 function _civicrm_api3_separate_values(&$values) {
379 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
380 foreach ($values as $key => & $value) {
381 if (is_array($value)) {
382 _civicrm_api3_separate_values($value);
384 elseif (is_string($value)) {
385 if ($key == 'case_type_id'){// this is to honor the way case API was originally written
386 $value = trim(str_replace($sp, ',', $value), ',');
388 elseif (strpos($value, $sp) !== FALSE) {
389 $value = explode($sp, trim($value, $sp));
396 * This is a legacy wrapper for api_store_values which will check the suitable fields using getfields
397 * rather than DAO->fields
399 * Getfields has handling for how to deal with uniquenames which dao->fields doesn't
401 * Note this is used by BAO type create functions - eg. contribution
402 * @param string $entity
403 * @param array $params
404 * @param array $values
406 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
407 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
408 $fields = $fields['values'];
409 _civicrm_api3_store_values($fields, $params, $values);
413 * @param array $fields
414 * @param array $params
415 * @param array $values
417 * @return Bool $valueFound
419 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
422 $keys = array_intersect_key($params, $fields);
423 foreach ($keys as $name => $value) {
424 if ($name !== 'id') {
425 $values[$name] = $value;
433 * The API supports 2 types of get requestion. The more complex uses the BAO query object.
434 * This is a generic function for those functions that call it
436 * At the moment only called by contact we should extend to contribution &
437 * others that use the query object. Note that this function passes permission information in.
440 * * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
443 * @param array $params
444 * As passed into api get or getcount function.
445 * @param array $additional_options
446 * Array of options (so we can modify the filter).
447 * @param bool $getCount
448 * Are we just after the count.
452 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL) {
454 // Convert id to e.g. contact_id
455 if (empty($params[$entity . '_id']) && isset($params['id'])) {
456 $params[$entity . '_id'] = $params['id'];
458 unset($params['id']);
460 $options = _civicrm_api3_get_options_from_params($params, TRUE);
462 $inputParams = array_merge(
463 CRM_Utils_Array
::value('input_params', $options, array()),
464 CRM_Utils_Array
::value('input_params', $additional_options, array())
466 $returnProperties = array_merge(
467 CRM_Utils_Array
::value('return', $options, array()),
468 CRM_Utils_Array
::value('return', $additional_options, array())
470 if (empty($returnProperties)) {
471 $returnProperties = NULL;
473 if (!empty($params['check_permissions'])) {
474 // we will filter query object against getfields
475 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
476 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
477 $fields['values'][$entity . '_id'] = array();
478 $varsToFilter = array('returnProperties', 'inputParams');
479 foreach ($varsToFilter as $varToFilter) {
480 if (!is_array($
$varToFilter)) {
483 //I was going to throw an exception rather than silently filter out - but
484 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
485 //so we are silently ignoring parts of their request
486 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
487 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
490 $options = array_merge($options, $additional_options);
491 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
492 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
493 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
494 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
498 $returnProperties = NULL;
501 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
502 foreach ($newParams as &$newParam) {
503 if ($newParam[1] == '=' && is_array($newParam[2])) {
504 // we may be looking at an attempt to use the 'IN' style syntax
505 // @todo at time of writing only 'IN' & 'NOT IN' are supported for the array style syntax
506 $sqlFilter = CRM_Core_DAO
::createSqlFilter($newParam[0], $params[$newParam[0]], 'String', NULL, TRUE);
508 $newParam[1] = key($newParam[2]);
509 $newParam[2] = $sqlFilter;
515 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
517 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
528 if ($getCount) { // only return the count of contacts
536 * get dao query object based on input params
537 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
540 * @param array $params
541 * @param string $mode
542 * @param string $entity
543 * @return CRM_Core_DAO query object
545 function _civicrm_api3_get_query_object($params, $mode, $entity) {
546 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
547 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
548 $offset = CRM_Utils_Array
::value('offset', $options);
549 $rowCount = CRM_Utils_Array
::value('limit', $options);
550 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
551 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
552 if (empty($returnProperties)) {
553 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
556 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
557 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
559 empty($params['check_permissions'])
561 list($select, $from, $where, $having) = $query->query();
563 $sql = "$select $from $where $having";
566 $sql .= " ORDER BY $sort ";
568 if (!empty($rowCount)) {
569 $sql .= " LIMIT $offset, $rowCount ";
571 $dao = CRM_Core_DAO
::executeQuery($sql);
572 return array($dao, $query);
576 * Function transfers the filters being passed into the DAO onto the params object
577 * @param CRM_Core_DAO $dao
578 * @param array $params
579 * @param bool $unique
580 * @param string $entity
582 * @throws API_Exception
585 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $entity) {
586 $entity = substr($dao->__table
, 8);
587 if (!empty($params[$entity . "_id"]) && empty($params['id'])) {
588 //if entity_id is set then treat it as ID (will be overridden by id if set)
589 $params['id'] = $params[$entity . "_id"];
591 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
592 $fields = array_intersect(array_keys($allfields), array_keys($params));
594 $options = _civicrm_api3_get_options_from_params($params);
595 //apply options like sort
596 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
598 //accept filters like filter.activity_date_time_high
599 // std is now 'filters' => ..
600 if (strstr(implode(',', array_keys($params)), 'filter')) {
601 if (isset($params['filters']) && is_array($params['filters'])) {
602 foreach ($params['filters'] as $paramkey => $paramvalue) {
603 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
607 foreach ($params as $paramkey => $paramvalue) {
608 if (strstr($paramkey, 'filter')) {
609 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
618 foreach ($fields as $field) {
619 if (is_array($params[$field])) {
620 //get the actual fieldname from db
621 $fieldName = $allfields[$field]['name'];
622 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
623 if (!empty($where)) {
624 $dao->whereAdd($where);
629 $daoFieldName = $allfields[$field]['name'];
630 if (empty($daoFieldName)) {
631 throw new API_Exception("Failed to determine field name for \"$field\"");
633 $dao->{$daoFieldName} = $params[$field];
636 $dao->$field = $params[$field];
640 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
642 $options['return']['id'] = TRUE;// ensure 'id' is included
643 $allfields = _civicrm_api3_get_unique_name_array($dao);
644 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
645 foreach ($returnMatched as $returnValue) {
646 $dao->selectAdd($returnValue);
649 $unmatchedFields = array_diff(// not already matched on the field names
650 array_keys($options['return']),
654 $returnUniqueMatched = array_intersect(
656 array_flip($allfields)// but a match for the field keys
658 foreach ($returnUniqueMatched as $uniqueVal) {
659 $dao->selectAdd($allfields[$uniqueVal]);
662 $dao->setApiFilter($params);
666 * Apply filters (e.g. high, low) to DAO object (prior to find)
667 * @param string $filterField
668 * Field name of filter.
669 * @param string $filterValue
670 * Field value of filter.
674 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
675 if (strstr($filterField, 'high')) {
676 $fieldName = substr($filterField, 0, -5);
677 $dao->whereAdd("($fieldName <= $filterValue )");
679 if (strstr($filterField, 'low')) {
680 $fieldName = substr($filterField, 0, -4);
681 $dao->whereAdd("($fieldName >= $filterValue )");
683 if ($filterField == 'is_current' && $filterValue == 1) {
684 $todayStart = date('Ymd000000', strtotime('now'));
685 $todayEnd = date('Ymd235959', strtotime('now'));
686 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
687 if (property_exists($dao, 'is_active')) {
688 $dao->whereAdd('is_active = 1');
694 * Get sort, limit etc options from the params - supporting old & new formats.
695 * get returnproperties for legacy
697 * @param array $params
698 * Params array as passed into civicrm_api.
699 * @param bool $queryObject
700 * Is this supporting a queryobject api (e.g contact) - if so we support more options.
701 * for legacy report & return a unique fields array
703 * @param string $entity
704 * @param string $action
706 * @throws API_Exception
707 * @return array $options options extracted from params
709 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
711 $sort = CRM_Utils_Array
::value('sort', $params, 0);
712 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
713 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
715 $offset = CRM_Utils_Array
::value('offset', $params, 0);
716 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
717 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
718 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
720 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
721 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
722 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
724 if (is_array(CRM_Utils_Array
::value('options', $params))) {
725 // is count is set by generic getcount not user
726 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
727 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
728 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
729 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
732 $returnProperties = array();
733 // handle the format return =sort_name,display_name...
734 if (array_key_exists('return', $params)) {
735 if (is_array($params['return'])) {
736 $returnProperties = array_fill_keys($params['return'], 1);
739 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
740 $returnProperties = array_fill_keys($returnProperties, 1);
743 if ($entity && $action == 'get') {
744 if (!empty($returnProperties['id'])) {
745 $returnProperties[$entity . '_id'] = 1;
746 unset($returnProperties['id']);
748 switch (trim(strtolower($sort))) {
752 $sort = str_replace('id', $entity . '_id', $sort);
757 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
758 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
759 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
760 'is_count' => $is_count,
761 'return' => !empty($returnProperties) ?
$returnProperties : array(),
764 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
765 throw new API_Exception('invalid string in sort options');
771 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
772 // if the queryobject is being used this should be used
773 $inputParams = array();
774 $legacyreturnProperties = array();
776 'sort', 'offset', 'rowCount', 'options', 'return',
778 foreach ($params as $n => $v) {
779 if (substr($n, 0, 7) == 'return.') {
780 $legacyreturnProperties[substr($n, 7)] = $v;
782 elseif ($n == 'id') {
783 $inputParams[$entity . '_id'] = $v;
785 elseif (in_array($n, $otherVars)) {
788 $inputParams[$n] = $v;
789 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
790 throw new API_Exception('invalid string');
794 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
795 $options['input_params'] = $inputParams;
800 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find)
802 * @param array $params
803 * Params array as passed into civicrm_api.
808 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
810 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
811 if (!$options['is_count']) {
812 if (!empty($options['limit'])) {
813 $dao->limit((int) $options['offset'], (int) $options['limit']);
815 if (!empty($options['sort'])) {
816 $dao->orderBy($options['sort']);
822 * build fields array. This is the array of fields as it relates to the given DAO
823 * returns unique fields as keys by default but if set but can return by DB fields
825 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
826 $fields = $bao->fields();
828 if (empty($fields['id'])) {
829 $entity = _civicrm_api_get_entity_name_from_dao($bao);
830 $fields['id'] = $fields[$entity . '_id'];
831 unset($fields[$entity . '_id']);
836 foreach ($fields as $field) {
837 $dbFields[$field['name']] = $field;
843 * build fields array. This is the array of fields as it relates to the given DAO
844 * returns unique fields as keys by default but if set but can return by DB fields
845 * @param CRM_Core_BAO $bao
849 function _civicrm_api3_get_unique_name_array(&$bao) {
850 $fields = $bao->fields();
851 foreach ($fields as $field => $values) {
852 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
854 return $uniqueFields;
858 * Converts an DAO object to an array
860 * @param CRM_Core_DAO $dao
862 * @param array $params
863 * @param bool $uniqueFields
864 * @param string $entity
865 * @param bool $autoFind
872 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
874 if (isset($params['options']) && !empty($params['options']['is_count'])) {
875 return $dao->count();
880 if ($autoFind && !$dao->find()) {
884 if (isset($dao->count
)) {
888 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
890 while ($dao->fetch()) {
892 foreach ($fields as $key) {
893 if (array_key_exists($key, $dao)) {
894 // not sure on that one
895 if ($dao->$key !== NULL) {
896 $tmp[$key] = $dao->$key;
900 $result[$dao->id
] = $tmp;
902 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
903 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
911 * We currently retrieve all custom fields or none at this level so if we know the entity
912 * && 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
913 * @todo filter so only required fields are queried
915 * @param array $params
916 * @param string $entity
917 * Entity name in CamelCase.
921 function _civicrm_api3_custom_fields_are_required($entity, $params) {
922 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
925 $options = _civicrm_api3_get_options_from_params($params);
926 //we check for possibility of 'custom' => 1 as well as specific custom fields
927 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
928 if (stristr($returnString, 'custom')) {
933 * Converts an object to an array
936 * (reference) object to convert.
937 * @param array $values
939 * @param array|bool $uniqueFields
945 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
947 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
948 foreach ($fields as $key => $value) {
949 if (array_key_exists($key, $dao)) {
950 $values[$key] = $dao->$key;
956 * Wrapper for _civicrm_object_to_array when api supports unique fields
958 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
959 return _civicrm_api3_object_to_array($dao, $values, TRUE);
964 * @param array $params
965 * @param array $values
966 * @param string $extends
967 * Entity that this custom field extends (e.g. contribution, event, contact).
968 * @param string $entityId
969 * ID of entity per $extends.
971 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
972 $values['custom'] = array();
973 $checkCheckBoxField = FALSE;
975 if (in_array($extends, array('Household', 'Individual', 'Organization'))) {
979 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
980 if (!$fields['is_error']) {
981 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
982 $fields = $fields['values'];
983 $checkCheckBoxField = TRUE;
986 foreach ($params as $key => $value) {
987 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
988 if ($customFieldID && (!is_null($value))) {
989 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
990 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
993 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
994 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1001 * @param array $params
1004 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1005 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1007 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery
::$extendsMap, array_fill_keys($nonGenericEntities, 1));
1008 if (!array_key_exists($entity, $customFieldEntities)) {
1012 _civicrm_api3_custom_format_params($params, $values, $entity);
1013 $params = array_merge($params, $values);
1017 * we can't rely on downstream to add separators to checkboxes so we'll check here. We should look at pushing to BAO function
1018 * 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
1019 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1021 * 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
1022 * don't touch - lots of very cautious code in here
1024 * The resulting array should look like
1030 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1032 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1033 * be fixed in future
1035 * @param $checkboxFieldValue
1036 * @param $customFieldLabel
1040 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1042 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1043 // we can assume it's pre-formatted
1046 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1047 if (!empty($options['is_error'])) {
1048 //the check is precautionary - can probably be removed later
1052 $options = $options['values'];
1054 if (is_array($checkboxFieldValue)) {
1055 foreach ($checkboxFieldValue as $key => $value) {
1056 if (!array_key_exists($key, $options)) {
1057 $validValue = FALSE;
1061 // we have been passed an array that is already in the 'odd' custom field format
1066 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1067 // if the array only has one item we'll treat it like any other string
1068 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1069 $possibleValue = reset($checkboxFieldValue);
1071 if (is_string($checkboxFieldValue)) {
1072 $possibleValue = $checkboxFieldValue;
1074 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1075 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1078 elseif (is_array($checkboxFieldValue)) {
1079 // so this time around we are considering the values in the array
1080 $possibleValues = $checkboxFieldValue;
1081 $formatValue = TRUE;
1083 elseif (stristr($checkboxFieldValue, ',')) {
1084 $formatValue = TRUE;
1085 //lets see if we should separate it - we do this near the end so we
1086 // ensure we have already checked that the comma is not part of a legitimate match
1087 // and of course, we don't make any changes if we don't now have matches
1088 $possibleValues = explode(',', $checkboxFieldValue);
1091 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1095 foreach ($possibleValues as $index => $possibleValue) {
1096 if (array_key_exists($possibleValue, $options)) {
1097 // 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)
1099 elseif (array_key_exists(trim($possibleValue), $options)) {
1100 $possibleValues[$index] = trim($possibleValue);
1103 $formatValue = FALSE;
1107 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1113 * This function ensures that we have the right input parameters
1115 * This function is only called when $dao is passed into verify_mandatory.
1116 * The practice of passing $dao into verify_mandatory turned out to be
1117 * unsatisfactory as the required fields @ the dao level is so diffent to the abstract
1118 * api level. Hence the intention is to remove this function
1119 * & the associated param from viery_mandatory
1121 * @param array $params
1122 * Associative array of property name/value.
1123 * pairs to insert in new history.
1124 * @param string $daoName
1125 * @param bool $return
1127 * @daoName string DAO to check params agains
1129 * @return bool should the missing fields be returned as an array (core error created as default)
1131 * @return bool true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1134 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1135 //@deprecated - see notes
1136 if (isset($params['extends'])) {
1137 if (($params['extends'] == 'Activity' ||
1138 $params['extends'] == 'Phonecall' ||
1139 $params['extends'] == 'Meeting' ||
1140 $params['extends'] == 'Group' ||
1141 $params['extends'] == 'Contribution'
1143 ($params['style'] == 'Tab')
1145 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1149 $dao = new $daoName();
1150 $fields = $dao->fields();
1153 foreach ($fields as $k => $v) {
1154 if ($v['name'] == 'id') {
1158 if (!empty($v['required'])) {
1159 // 0 is a valid input for numbers, CRM-8122
1160 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1166 if (!empty($missing)) {
1167 if (!empty($return)) {
1171 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1179 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this
1181 * @param string $bao_name
1183 * @param array $params
1185 * @param bool $returnAsSuccess
1186 * Return in api success format.
1187 * @param string $entity
1191 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1192 $bao = new $bao_name();
1193 _civicrm_api3_dao_set_filter($bao, $params, TRUE, $entity);
1194 if ($returnAsSuccess) {
1195 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1198 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity, 'get');
1203 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this
1205 * @param string $bao_name
1206 * Name of BAO Class.
1207 * @param array $params
1208 * Parameters passed into the api call.
1209 * @param string $entity
1210 * Entity - pass in if entity is non-standard & required $ids array.
1212 * @throws API_Exception
1215 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1216 _civicrm_api3_format_params_for_create($params, $entity);
1217 $args = array(&$params);
1218 if (!empty($entity)) {
1219 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1223 if (method_exists($bao_name, 'create')) {
1225 $fct_name = $bao_name . '::' . $fct;
1226 $bao = call_user_func_array(array($bao_name, $fct), $args);
1228 elseif (method_exists($bao_name, 'add')) {
1230 $fct_name = $bao_name . '::' . $fct;
1231 $bao = call_user_func_array(array($bao_name, $fct), $args);
1234 $fct_name = '_civicrm_api3_basic_create_fallback';
1235 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1238 if (is_null($bao)) {
1239 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1241 elseif (is_a($bao, 'CRM_Core_Error')) {
1242 //some wierd circular thing means the error takes itself as an argument
1243 $msg = $bao->getMessages($bao);
1244 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1245 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1246 // so we need to reset the error object here to avoid getting concatenated errors
1247 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1248 CRM_Core_Error
::singleton()->reset();
1249 throw new API_Exception($msg);
1253 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1254 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1259 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1261 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1262 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1264 * @param string $bao_name
1265 * @param array $params
1267 * @throws API_Exception
1268 * @return CRM_Core_DAO|NULL an instance of the BAO
1270 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1271 $dao_name = get_parent_class($bao_name);
1272 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1273 $dao_name = $bao_name;
1275 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1276 if (empty($entityName)) {
1277 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1278 'class_name' => $bao_name,
1281 $hook = empty($params['id']) ?
'create' : 'edit';
1283 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1284 $instance = new $dao_name();
1285 $instance->copyValues($params);
1287 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1293 * Function to do a 'standard' api del - when the api is only doing a $bao::del then use this
1294 * if api::del doesn't exist it will try DAO delete method
1296 * @param string $bao_name
1297 * @param array $params
1299 * @return array API result array
1300 * @throws API_Exception
1302 function _civicrm_api3_basic_delete($bao_name, &$params) {
1304 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1305 $args = array(&$params['id']);
1306 if (method_exists($bao_name, 'del')) {
1307 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1308 if ($bao !== FALSE) {
1309 return civicrm_api3_create_success(TRUE);
1311 throw new API_Exception('Could not delete entity id ' . $params['id']);
1313 elseif (method_exists($bao_name, 'delete')) {
1314 $dao = new $bao_name();
1315 $dao->id
= $params['id'];
1317 while ($dao->fetch()) {
1319 return civicrm_api3_create_success();
1323 throw new API_Exception('Could not delete entity id ' . $params['id']);
1327 throw new API_Exception('no delete method found');
1331 * Get custom data for the given entity & Add it to the returnArray as 'custom_123' = 'custom string' AND 'custom_123_1' = 'custom string'
1332 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1334 * @param array $returnArray
1335 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1336 * @param string $entity
1337 * E.g membership, event.
1338 * @param int $entity_id
1339 * @param int $groupID
1340 * Per CRM_Core_BAO_CustomGroup::getTree.
1341 * @param int $subType
1342 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1343 * @param string $subName
1344 * Subtype of entity.
1346 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1347 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1348 CRM_Core_DAO
::$_nullObject,
1354 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1355 $customValues = array();
1356 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1357 $fieldInfo = array();
1358 foreach ($groupTree as $set) {
1359 $fieldInfo +
= $set['fields'];
1361 if (!empty($customValues)) {
1362 foreach ($customValues as $key => $val) {
1363 // per standard - return custom_fieldID
1364 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1365 $returnArray['custom_' . $id] = $val;
1367 //not standard - but some api did this so guess we should keep - cheap as chips
1368 $returnArray[$key] = $val;
1370 // Shim to restore legacy behavior of ContactReference custom fields
1371 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1372 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1373 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1380 * Validate fields being passed into API. This function relies on the getFields function working accurately
1381 * for the given API. If error mode is set to TRUE then it will also check
1384 * As of writing only date was implemented.
1385 * @param string $entity
1386 * @param string $action
1387 * @param array $params
1389 * @param array $fields
1390 * Response from getfields all variables are the same as per civicrm_api.
1391 * @param bool $errorMode
1392 * ErrorMode do intensive post fail checks?.
1395 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = FALSE) {
1396 $fields = array_intersect_key($fields, $params);
1397 foreach ($fields as $fieldName => $fieldInfo) {
1398 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1399 case CRM_Utils_Type
::T_INT
:
1400 //field is of type integer
1401 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1406 case CRM_Utils_Type
::T_TIMESTAMP
:
1407 //field is of type date or datetime
1408 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1412 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1415 case CRM_Utils_Type
::T_STRING
:
1416 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1419 case CRM_Utils_Type
::T_MONEY
:
1420 if (!CRM_Utils_Rule
::money($params[$fieldName]) && !empty($params[$fieldName])) {
1421 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1425 // intensive checks - usually only called after DB level fail
1426 if (!empty($errorMode) && strtolower($action) == 'create') {
1427 if (!empty($fieldInfo['FKClassName'])) {
1428 if (!empty($params[$fieldName])) {
1429 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1431 elseif (!empty($fieldInfo['required'])) {
1432 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1435 if (!empty($fieldInfo['api.unique'])) {
1436 $params['entity'] = $entity;
1437 _civicrm_api3_validate_uniquekey($params, $fieldName, $fieldInfo);
1444 * Validate date fields being passed into API.
1445 * It currently converts both unique fields and DB field names to a mysql date.
1446 * @todo - probably the unique field handling & the if exists handling is now done before this
1447 * function is reached in the wrapper - can reduce this code down to assume we
1448 * are only checking the passed in field
1450 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1451 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1453 * @param array $params
1454 * Params from civicrm_api.
1455 * @param string $fieldName
1456 * Uniquename of field being checked.
1457 * @param array $fieldInfo
1458 * Array of fields from getfields function.
1461 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1462 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1463 if (!empty($params[$fieldInfo['name']])) {
1464 $params[$fieldInfo['name']] = _civicrm_api3_getValidDate($params[$fieldInfo['name']], $fieldInfo['name'], $fieldInfo['type']);
1466 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($params[$fieldName])) {
1467 $params[$fieldName] = _civicrm_api3_getValidDate($params[$fieldName], $fieldName, $fieldInfo['type']);
1472 * convert date into BAO friendly date
1473 * we accept 'whatever strtotime accepts'
1475 * @param string $dateValue
1476 * @param string $fieldName
1482 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1483 if (is_array($dateValue)) {
1484 foreach ($dateValue as $key => $value) {
1485 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1489 if (strtotime($dateValue) === FALSE) {
1490 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1492 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1493 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1497 * Validate foreign constraint fields being passed into API.
1499 * @param array $params
1500 * Params from civicrm_api.
1501 * @param string $fieldName
1502 * Uniquename of field being checked.
1503 * @param array $fieldInfo
1504 * Array of fields from getfields function.
1507 function _civicrm_api3_validate_constraint(&$params, &$fieldName, &$fieldInfo) {
1508 $dao = new $fieldInfo['FKClassName'];
1509 $dao->id
= $params[$fieldName];
1511 $dao->selectAdd('id');
1512 if (!$dao->find()) {
1513 throw new Exception("$fieldName is not valid : " . $params[$fieldName]);
1518 * Validate foreign constraint fields being passed into API.
1520 * @param array $params
1521 * Params from civicrm_api.
1522 * @param string $fieldName
1523 * Uniquename of field being checked.
1525 * Array of fields from getfields function.
1528 function _civicrm_api3_validate_uniquekey(&$params, &$fieldName, &$fieldInfo) {
1529 $existing = civicrm_api($params['entity'], 'get', array(
1530 'version' => $params['version'],
1531 $fieldName => $params[$fieldName],
1533 // an entry already exists for this unique field
1534 if ($existing['count'] == 1) {
1535 // question - could this ever be a security issue?
1536 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1541 * Generic implementation of the "replace" action.
1543 * Replace the old set of entities (matching some given keys) with a new set of
1544 * entities (matching the same keys).
1546 * Note: This will verify that 'values' is present, but it does not directly verify
1547 * any other parameters.
1549 * @param string $entity
1551 * @param array $params
1552 * Params from civicrm_api, including:.
1553 * - 'values': an array of records to save
1554 * - all other items: keys which identify new/pre-existing records
1557 function _civicrm_api3_generic_replace($entity, $params) {
1559 $transaction = new CRM_Core_Transaction();
1561 if (!is_array($params['values'])) {
1562 throw new Exception("Mandatory key(s) missing from params array: values");
1565 // Extract the keys -- somewhat scary, don't think too hard about it
1566 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1568 // Lookup pre-existing records
1569 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1570 if (civicrm_error($preexisting)) {
1571 $transaction->rollback();
1572 return $preexisting;
1575 // Save the new/updated records
1577 foreach ($params['values'] as $replacement) {
1578 // Sugar: Don't force clients to duplicate the 'key' data
1579 $replacement = array_merge($baseParams, $replacement);
1580 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1581 $create = civicrm_api($entity, $action, $replacement);
1582 if (civicrm_error($create)) {
1583 $transaction->rollback();
1586 foreach ($create['values'] as $entity_id => $entity_value) {
1587 $creates[$entity_id] = $entity_value;
1591 // Remove stale records
1592 $staleIDs = array_diff(
1593 array_keys($preexisting['values']),
1594 array_keys($creates)
1596 foreach ($staleIDs as $staleID) {
1597 $delete = civicrm_api($entity, 'delete', array(
1598 'version' => $params['version'],
1601 if (civicrm_error($delete)) {
1602 $transaction->rollback();
1607 return civicrm_api3_create_success($creates, $params);
1609 catch(PEAR_Exception
$e) {
1610 $transaction->rollback();
1611 return civicrm_api3_create_error($e->getMessage());
1613 catch(Exception
$e) {
1614 $transaction->rollback();
1615 return civicrm_api3_create_error($e->getMessage());
1620 * @param array $params
1624 function _civicrm_api3_generic_replace_base_params($params) {
1625 $baseParams = $params;
1626 unset($baseParams['values']);
1627 unset($baseParams['sequential']);
1628 unset($baseParams['options']);
1633 * returns fields allowable by api
1636 * String Entity to query.
1637 * @param bool $unique
1638 * Index by unique fields?.
1639 * @param array $params
1643 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1644 $unsetIfEmpty = array('dataPattern', 'headerPattern', 'default', 'export', 'import');
1645 $dao = _civicrm_api3_get_DAO($entity);
1650 $fields = $d->fields();
1651 // replace uniqueNames by the normal names as the key
1652 if (empty($unique)) {
1653 foreach ($fields as $name => &$field) {
1654 //getting rid of unused attributes
1655 foreach ($unsetIfEmpty as $attr) {
1656 if (empty($field[$attr])) {
1657 unset($field[$attr]);
1660 if ($name == $field['name']) {
1663 if (array_key_exists($field['name'], $fields)) {
1664 $field['error'] = 'name conflict';
1665 // it should never happen, but better safe than sorry
1668 $fields[$field['name']] = $field;
1669 $fields[$field['name']]['uniqueName'] = $name;
1670 unset($fields[$name]);
1673 // Translate FKClassName to the corresponding api
1674 foreach ($fields as $name => &$field) {
1675 if (!empty($field['FKClassName'])) {
1676 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1678 $field['FKApiName'] = $FKApi;
1682 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1687 * Return an array of fields for a given entity - this is the same as the BAO function but
1688 * fields are prefixed with 'custom_' to represent api params
1690 function _civicrm_api_get_custom_fields($entity, &$params) {
1691 $entity = _civicrm_api_get_camel_name($entity);
1692 if ($entity == 'Contact') {
1693 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1694 $entity = CRM_Utils_Array
::value('contact_type', $params);
1696 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1699 // we could / should probably test for other subtypes here - e.g. activity_type_id
1700 CRM_Utils_Array
::value('contact_sub_type', $params),
1709 foreach ($customfields as $key => $value) {
1710 // Regular fields have a 'name' property
1711 $value['name'] = 'custom_' . $key;
1712 $value['title'] = $value['label'];
1713 $value['type'] = _getStandardTypeFromCustomDataType($value['data_type']);
1714 $ret['custom_' . $key] = $value;
1719 * Translate the custom field data_type attribute into a std 'type'
1721 function _getStandardTypeFromCustomDataType($dataType) {
1723 'String' => CRM_Utils_Type
::T_STRING
,
1724 'Int' => CRM_Utils_Type
::T_INT
,
1725 'Money' => CRM_Utils_Type
::T_MONEY
,
1726 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1727 'Float' => CRM_Utils_Type
::T_FLOAT
,
1728 'Date' => CRM_Utils_Type
::T_DATE
,
1729 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1730 'StateProvince' => CRM_Utils_Type
::T_INT
,
1731 'File' => CRM_Utils_Type
::T_STRING
,
1732 'Link' => CRM_Utils_Type
::T_STRING
,
1733 'ContactReference' => CRM_Utils_Type
::T_INT
,
1734 'Country' => CRM_Utils_Type
::T_INT
,
1736 return $mapping[$dataType];
1741 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't
1742 * If multiple aliases the last takes precedence
1744 * Function also swaps unique fields for non-unique fields & vice versa.
1746 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1747 foreach ($fields as $field => $values) {
1748 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1749 if (!empty($values['api.aliases'])) {
1750 // if aliased field is not set we try to use field alias
1751 if (!isset($apiRequest['params'][$field])) {
1752 foreach ($values['api.aliases'] as $alias) {
1753 if (isset($apiRequest['params'][$alias])) {
1754 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1756 //unset original field nb - need to be careful with this as it may bring inconsistencies
1757 // out of the woodwork but will be implementing only as _spec function extended
1758 unset($apiRequest['params'][$alias]);
1762 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
1763 && isset($apiRequest['params'][$values['name']])
1765 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1766 // note that it would make sense to unset the original field here but tests need to be in place first
1768 if (!isset($apiRequest['params'][$field])
1770 && $field != $uniqueName
1771 && array_key_exists($uniqueName, $apiRequest['params'])
1774 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1775 // note that it would make sense to unset the original field here but tests need to be in place first
1782 * Validate integer fields being passed into API.
1783 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user
1785 * @param array $params
1786 * Params from civicrm_api.
1787 * @param string $fieldName
1788 * Uniquename of field being checked.
1789 * @param array $fieldInfo
1790 * Array of fields from getfields function.
1791 * @param string $entity
1792 * @throws API_Exception
1794 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1795 if (!empty($params[$fieldName])) {
1796 // if value = 'user_contact_id' (or similar), replace value with contact id
1797 if (!is_numeric($params[$fieldName]) && is_scalar($params[$fieldName])) {
1798 $realContactId = _civicrm_api3_resolve_contactID($params[$fieldName]);
1799 if ('unknown-user' === $realContactId) {
1800 throw new API_Exception("\"$fieldName\" \"{$params[$fieldName]}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName, "type" => "integer"));
1802 elseif (is_numeric($realContactId)) {
1803 $params[$fieldName] = $realContactId;
1806 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1807 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1810 // After swapping options, ensure we have an integer(s)
1811 foreach ((array) ($params[$fieldName]) as $value) {
1812 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1813 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1817 // Check our field length
1818 if (is_string($params[$fieldName]) && !empty($fieldInfo['maxlength']) && strlen($params[$fieldName]) > $fieldInfo['maxlength']
1820 throw new API_Exception($params[$fieldName] . " is " . strlen($params[$fieldName]) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1821 2100, array('field' => $fieldName, "max_length" => $fieldInfo['maxlength'])
1828 * Determine a contact ID using a string expression
1830 * @param string $contactIdExpr
1831 * E.g. "user_contact_id" or "@user:username".
1832 * @return int|NULL|'unknown-user'
1834 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1835 //if value = 'user_contact_id' replace value with logged in user id
1836 if ($contactIdExpr == "user_contact_id") {
1837 return CRM_Core_Session
::getLoggedInContactID();
1839 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1840 $config = CRM_Core_Config
::singleton();
1842 $ufID = $config->userSystem
->getUfId($matches[1]);
1844 return 'unknown-user';
1847 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
1849 return 'unknown-user';
1858 * Validate html (check for scripting attack)
1859 * @param array $params
1860 * @param string $fieldName
1861 * @param array $fieldInfo
1863 * @throws API_Exception
1865 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
1866 if ($value = CRM_Utils_Array
::value($fieldName, $params)) {
1867 if (!CRM_Utils_Rule
::xssString($value)) {
1868 throw new API_Exception(ts('Illegal characters in input (potential scripting attack)'), array("field" => $fieldName, "error_code" => "xss"));
1874 * Validate string fields being passed into API.
1875 * @param array $params
1876 * Params from civicrm_api.
1877 * @param string $fieldName
1878 * Uniquename of field being checked.
1879 * @param array $fieldInfo
1880 * Array of fields from getfields function.
1881 * @param string $entity
1882 * @throws API_Exception
1885 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
1886 // If fieldname exists in params
1887 $value = CRM_Utils_Array
::value($fieldName, $params, '');
1888 if (!is_array($value)) {
1889 $value = (string) $value;
1892 //@todo what do we do about passed in arrays. For many of these fields
1893 // the missing piece of functionality is separating them to a separated string
1894 // & many save incorrectly. But can we change them wholesale?
1897 if (!CRM_Utils_Rule
::xssString($value)) {
1898 throw new Exception(ts('Illegal characters in input (potential scripting attack)'));
1900 if ($fieldName == 'currency') {
1901 if (!CRM_Utils_Rule
::currencyCode($value)) {
1902 throw new Exception("Currency not a valid code: $value");
1905 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1906 _civicrm_api3_api_match_pseudoconstant($params, $entity, $fieldName, $fieldInfo);
1908 // Check our field length
1909 elseif (is_string($value) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($value)) > $fieldInfo['maxlength']) {
1910 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
1911 2100, array('field' => $fieldName)
1918 * Validate & swap out any pseudoconstants / options
1920 * @param array $params: api parameters
1921 * @param string $entity: api entity name
1922 * @param string $fieldName: field name used in api call (not necessarily the canonical name)
1923 * @param array $fieldInfo: getfields meta-data
1925 function _civicrm_api3_api_match_pseudoconstant(&$params, $entity, $fieldName, $fieldInfo) {
1926 $options = CRM_Utils_Array
::value('options', $fieldInfo);
1928 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
1929 // we need to get the options from the entity the field relates to
1930 $entity = $fieldInfo['entity'];
1932 $options = civicrm_api($entity, 'getoptions', array('version' => 3, 'field' => $fieldInfo['name'], 'context' => 'validate'));
1933 $options = CRM_Utils_Array
::value('values', $options, array());
1936 // If passed a value-separated string, explode to an array, then re-implode after matching values
1938 if (is_string($params[$fieldName]) && strpos($params[$fieldName], CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
1939 $params[$fieldName] = CRM_Utils_Array
::explodePadded($params[$fieldName]);
1942 // If passed multiple options, validate each
1943 if (is_array($params[$fieldName])) {
1944 foreach ($params[$fieldName] as &$value) {
1945 if (!is_array($value)) {
1946 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
1949 // TODO: unwrap the call to implodePadded from the conditional and do it always
1950 // need to verify that this is safe and doesn't break anything though.
1951 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
1953 CRM_Utils_Array
::implodePadded($params[$fieldName]);
1957 _civicrm_api3_api_match_pseudoconstant_value($params[$fieldName], $options, $fieldName);
1962 * Validate & swap a single option value for a field
1964 * @param string $value: field value
1965 * @param array $options: array of options for this field
1966 * @param string $fieldName: field name used in api call (not necessarily the canonical name)
1967 * @throws API_Exception
1969 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
1970 // If option is a key, no need to translate
1971 if (array_key_exists($value, $options)) {
1975 // Translate value into key
1976 $newValue = array_search($value, $options);
1977 if ($newValue !== FALSE) {
1981 // Case-insensitive matching
1982 $newValue = strtolower($value);
1983 $options = array_map("strtolower", $options);
1984 $newValue = array_search($newValue, $options);
1985 if ($newValue === FALSE) {
1986 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
1992 * Returns the canonical name of a field
1995 * : api entity name (string should already be standardized - no camelCase).
1997 * : any variation of a field's name (name, unique_name, api.alias).
1999 * @return bool|string (string|bool) fieldName or FALSE if the field does not exist
2001 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
2002 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2005 if ($fieldName == "{$entity}_id") {
2008 $result = civicrm_api($entity, 'getfields', array(
2010 'action' => 'create',
2012 $meta = $result['values'];
2013 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2014 $fieldName = $fieldName . '_id';
2016 if (isset($meta[$fieldName])) {
2017 return $meta[$fieldName]['name'];
2019 foreach ($meta as $info) {
2020 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2021 return $info['name'];
2023 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
2024 return $info['name'];
2031 * @param string $entity
2032 * @param array $result
2033 * @return string|array|null
2035 function _civicrm_api3_deprecation_check($entity, $result = array()) {
2037 $apiFile = 'api/v3/' . _civicrm_api_get_camel_name($entity) . '.php';
2038 if (CRM_Utils_File
::isIncludable($apiFile)) {
2039 require_once $apiFile;
2041 $entity = _civicrm_api_get_entity_name_from_camel($entity);
2042 $fnName = "_civicrm_api3_{$entity}_deprecation";
2043 if (function_exists($fnName)) {
2044 return $fnName($result);