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 * CiviCRM APIv3 utility functions.
31 * @package CiviCRM_APIv3
35 * Initialize CiviCRM - should be run at the start of each API function.
37 function _civicrm_api3_initialize() {
38 require_once 'CRM/Core/ClassLoader.php';
39 CRM_Core_ClassLoader
::singleton()->register();
40 CRM_Core_Config
::singleton();
44 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking.
46 * @param array $params
47 * Array of fields to check.
48 * @param array $daoName
49 * String DAO to check for required fields (create functions only).
50 * @param array $keyoptions
51 * List of required fields options. One of the options is required.
53 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = array()) {
54 $keys = array(array());
55 foreach ($keyoptions as $key) {
58 civicrm_api3_verify_mandatory($params, $daoName, $keys);
62 * Check mandatory fields are included.
64 * @param array $params
65 * Array of fields to check.
66 * @param array $daoName
67 * String DAO to check for required fields (create functions only).
69 * List of required fields. A value can be an array denoting that either this or that is required.
70 * @param bool $verifyDAO
72 * @throws \API_Exception
74 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = array(), $verifyDAO = TRUE) {
77 if ($daoName != NULL && $verifyDAO && empty($params['id'])) {
78 $unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
79 if (!is_array($unmatched)) {
84 if (!empty($params['id'])) {
85 $keys = array('version');
88 if (!in_array('version', $keys)) {
89 // required from v3 onwards
93 foreach ($keys as $key) {
97 foreach ($key as $subkey) {
98 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
99 $optionset[] = $subkey;
102 // as long as there is one match then we don't need to rtn anything
106 if (empty($match) && !empty($optionset)) {
107 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
111 // Disallow empty values except for the number zero.
112 // TODO: create a utility for this since it's needed in many places
113 if (!array_key_exists($key, $params) ||
(empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
118 if (!empty($unmatched)) {
119 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched), "mandatory_missing", array("fields" => $unmatched));
124 * Create error array.
131 function civicrm_api3_create_error($msg, $data = array()) {
132 $data['is_error'] = 1;
133 $data['error_message'] = $msg;
134 // we will show sql to privileged user only (not sure of a specific
135 // security hole here but seems sensible - perhaps should apply to the trace as well?)
136 if (isset($data['sql']) && CRM_Core_Permission
::check('Administer CiviCRM')) {
137 // Isn't this redundant?
138 $data['debug_information'] = $data['sql'];
147 * Format array in result output style.
149 * @param array|int $values values generated by API operation (the result)
150 * @param array $params
151 * Parameters passed into API call.
152 * @param string $entity
153 * The entity being acted on.
154 * @param string $action
155 * The action passed to the API.
157 * DAO object to be freed here.
158 * @param array $extraReturnValues
159 * Additional values to be added to top level of result array(.
160 * - this param is currently used for legacy behaviour support
164 function civicrm_api3_create_success($values = 1, $params = array(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
166 $result['is_error'] = 0;
167 //lets set the ['id'] field if it's not set & we know what the entity is
168 if (is_array($values) && !empty($entity) && $action != 'getfields') {
169 foreach ($values as $key => $item) {
170 if (empty($item['id']) && !empty($item[$entity . "_id"])) {
171 $values[$key]['id'] = $item[$entity . "_id"];
173 if (!empty($item['financial_type_id'])) {
174 //4.3 legacy handling
175 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
177 if (!empty($item['next_sched_contribution_date'])) {
178 // 4.4 legacy handling
179 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
184 if (is_array($params) && !empty($params['debug'])) {
185 if (is_string($action) && $action != 'getfields') {
186 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) +
$params);
188 elseif ($action != 'getfields') {
189 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
195 $allFields = array();
196 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
197 $allFields = array_keys($apiFields['values']);
199 $paramFields = array_keys($params);
200 $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), array(
219 $result['undefined_fields'] = array_merge($undefined);
222 if (is_object($dao)) {
226 $result['version'] = 3;
227 if (is_array($values)) {
228 $result['count'] = (int) count($values);
230 // Convert value-separated strings to array
231 _civicrm_api3_separate_values($values);
233 if ($result['count'] == 1) {
234 list($result['id']) = array_keys($values);
236 elseif (!empty($values['id']) && is_int($values['id'])) {
237 $result['id'] = $values['id'];
241 $result['count'] = !empty($values) ?
1 : 0;
244 if (is_array($values) && isset($params['sequential']) &&
245 $params['sequential'] == 1
247 $result['values'] = array_values($values);
250 $result['values'] = $values;
252 if (!empty($params['options']['metadata'])) {
253 // We've made metadata an array but only supporting 'fields' atm.
254 if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
255 $fields = civicrm_api3($entity, 'getfields', array(
256 'action' => substr($action, 0, 3) == 'get' ?
'get' : 'create',
258 $result['metadata']['fields'] = $fields['values'];
261 // Report deprecations.
262 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
263 // Always report "update" action as deprecated.
264 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'update')) {
265 $deprecated = ((array) $deprecated) +
array('update' => 'The "update" action is deprecated. Use "create" with an id instead.');
268 // Metadata-level deprecations or wholesale entity deprecations.
269 if ($entity == 'entity' ||
$action == 'getactions' ||
is_string($deprecated)) {
270 $result['deprecated'] = $deprecated;
272 // Action-specific deprecations
273 elseif (!empty($deprecated[$action])) {
274 $result['deprecated'] = $deprecated[$action];
277 return array_merge($result, $extraReturnValues);
281 * Load the DAO of the entity.
287 function _civicrm_api3_load_DAO($entity) {
288 $dao = _civicrm_api3_get_DAO($entity);
297 * Return the DAO of the function or Entity.
299 * @param string $name
300 * Either a function of the api (civicrm_{entity}_create or the entity name.
301 * return the DAO name to manipulate this function
302 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
304 * @return mixed|string
306 function _civicrm_api3_get_DAO($name) {
307 if (strpos($name, 'civicrm_api3') !== FALSE) {
308 $last = strrpos($name, '_');
309 // len ('civicrm_api3_') == 13
310 $name = substr($name, 13, $last - 13);
313 $name = _civicrm_api_get_camel_name($name, 3);
315 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
319 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
321 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
322 if ($name == 'MailingEventQueue') {
323 return 'CRM_Mailing_Event_DAO_Queue';
325 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
326 // but am not confident mailing_recipients is tested so have not tackled.
327 if ($name == 'MailingRecipients') {
328 return 'CRM_Mailing_DAO_Recipients';
330 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
331 if ($name == 'MailingComponent') {
332 return 'CRM_Mailing_DAO_Component';
334 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
335 if ($name == 'AclRole') {
336 return 'CRM_ACL_DAO_EntityRole';
338 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
339 // But this would impact SMS extensions so need to coordinate
340 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
341 if ($name == 'SmsProvider') {
342 return 'CRM_SMS_DAO_Provider';
344 // FIXME: DAO names should follow CamelCase convention
345 if ($name == 'Im' ||
$name == 'Acl') {
346 $name = strtoupper($name);
348 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
349 if ($dao ||
!$name) {
353 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
354 if (file_exists("api/v3/$name.php")) {
355 include_once "api/v3/$name.php";
358 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
359 if (function_exists($daoFn)) {
367 * Return the DAO of the function or Entity.
369 * @param string $name
370 * Is either a function of the api (civicrm_{entity}_create or the entity name.
371 * return the DAO name to manipulate this function
372 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
376 function _civicrm_api3_get_BAO($name) {
377 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
378 if ($name == 'PrintLabel') {
379 return 'CRM_Badge_BAO_Layout';
381 $dao = _civicrm_api3_get_DAO($name);
385 $bao = str_replace("DAO", "BAO", $dao);
386 $file = strtr($bao, '_', '/') . '.php';
387 // Check if this entity actually has a BAO. Fall back on the DAO if not.
388 return stream_resolve_include_path($file) ?
$bao : $dao;
392 * Recursive function to explode value-separated strings into arrays.
396 function _civicrm_api3_separate_values(&$values) {
397 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
398 foreach ($values as $key => & $value) {
399 if (is_array($value)) {
400 _civicrm_api3_separate_values($value);
402 elseif (is_string($value)) {
403 // This is to honor the way case API was originally written.
404 if ($key == 'case_type_id') {
405 $value = trim(str_replace($sp, ',', $value), ',');
407 elseif (strpos($value, $sp) !== FALSE) {
408 $value = explode($sp, trim($value, $sp));
415 * This is a legacy wrapper for api_store_values.
417 * It checks suitable fields using getfields rather than DAO->fields.
419 * Getfields has handling for how to deal with unique names which dao->fields doesn't
421 * Note this is used by BAO type create functions - eg. contribution
423 * @param string $entity
424 * @param array $params
425 * @param array $values
427 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
428 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
429 $fields = $fields['values'];
430 _civicrm_api3_store_values($fields, $params, $values);
435 * @param array $fields
436 * @param array $params
437 * @param array $values
441 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
444 $keys = array_intersect_key($params, $fields);
445 foreach ($keys as $name => $value) {
446 if ($name !== 'id') {
447 $values[$name] = $value;
455 * Get function for query object api.
457 * The API supports 2 types of get request. The more complex uses the BAO query object.
458 * This is a generic function for those functions that call it
460 * At the moment only called by contact we should extend to contribution &
461 * others that use the query object. Note that this function passes permission information in.
464 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
468 * @param array $params
469 * As passed into api get or getcount function.
470 * @param array $additional_options
471 * Array of options (so we can modify the filter).
472 * @param bool $getCount
473 * Are we just after the count.
477 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL) {
479 // Convert id to e.g. contact_id
480 if (empty($params[$entity . '_id']) && isset($params['id'])) {
481 $params[$entity . '_id'] = $params['id'];
483 unset($params['id']);
485 $options = _civicrm_api3_get_options_from_params($params, TRUE);
487 $inputParams = array_merge(
488 CRM_Utils_Array
::value('input_params', $options, array()),
489 CRM_Utils_Array
::value('input_params', $additional_options, array())
491 $returnProperties = array_merge(
492 CRM_Utils_Array
::value('return', $options, array()),
493 CRM_Utils_Array
::value('return', $additional_options, array())
495 if (empty($returnProperties)) {
496 $returnProperties = NULL;
498 if (!empty($params['check_permissions'])) {
499 // we will filter query object against getfields
500 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
501 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
502 $fields['values'][$entity . '_id'] = array();
503 $varsToFilter = array('returnProperties', 'inputParams');
504 foreach ($varsToFilter as $varToFilter) {
505 if (!is_array($
$varToFilter)) {
508 //I was going to throw an exception rather than silently filter out - but
509 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
510 //so we are silently ignoring parts of their request
511 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
512 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
515 $options = array_merge($options, $additional_options);
516 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
517 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
518 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
519 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
523 $returnProperties = NULL;
526 if (substr($sort, 0, 2) == 'id') {
527 $sort = $entity . "_" . $sort;
530 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
531 foreach ($newParams as &$newParam) {
532 if ($newParam[1] == '=' && is_array($newParam[2])) {
533 // we may be looking at an attempt to use the 'IN' style syntax
534 // @todo at time of writing only 'IN' & 'NOT IN' are supported for the array style syntax
535 $sqlFilter = CRM_Core_DAO
::createSqlFilter($newParam[0], $params[$newParam[0]], 'String', NULL, TRUE);
537 $newParam[1] = key($newParam[2]);
538 $newParam[2] = $sqlFilter;
543 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
545 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
557 // only return the count of contacts
565 * Get dao query object based on input params.
567 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
570 * @param array $params
571 * @param string $mode
572 * @param string $entity
575 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
577 function _civicrm_api3_get_query_object($params, $mode, $entity) {
578 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
579 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
580 $offset = CRM_Utils_Array
::value('offset', $options);
581 $rowCount = CRM_Utils_Array
::value('limit', $options);
582 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
583 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
584 if (empty($returnProperties)) {
585 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
588 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
589 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
591 empty($params['check_permissions'])
593 list($select, $from, $where, $having) = $query->query();
595 $sql = "$select $from $where $having";
598 $sql .= " ORDER BY $sort ";
600 if (!empty($rowCount)) {
601 $sql .= " LIMIT $offset, $rowCount ";
603 $dao = CRM_Core_DAO
::executeQuery($sql);
604 return array($dao, $query);
608 * Function transfers the filters being passed into the DAO onto the params object.
610 * @param CRM_Core_DAO $dao
611 * @param array $params
612 * @param bool $unique
613 * @param string $entity
615 * @throws API_Exception
618 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $entity) {
619 $entity = substr($dao->__table
, 8);
620 if (!empty($params[$entity . "_id"]) && empty($params['id'])) {
621 //if entity_id is set then treat it as ID (will be overridden by id if set)
622 $params['id'] = $params[$entity . "_id"];
624 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
625 $fields = array_intersect(array_keys($allfields), array_keys($params));
627 $options = _civicrm_api3_get_options_from_params($params);
628 //apply options like sort
629 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
631 //accept filters like filter.activity_date_time_high
632 // std is now 'filters' => ..
633 if (strstr(implode(',', array_keys($params)), 'filter')) {
634 if (isset($params['filters']) && is_array($params['filters'])) {
635 foreach ($params['filters'] as $paramkey => $paramvalue) {
636 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
640 foreach ($params as $paramkey => $paramvalue) {
641 if (strstr($paramkey, 'filter')) {
642 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
651 foreach ($fields as $field) {
652 if (is_array($params[$field])) {
653 //get the actual fieldname from db
654 $fieldName = $allfields[$field]['name'];
655 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
656 if (!empty($where)) {
657 $dao->whereAdd($where);
662 $daoFieldName = $allfields[$field]['name'];
663 if (empty($daoFieldName)) {
664 throw new API_Exception("Failed to determine field name for \"$field\"");
666 $dao->{$daoFieldName} = $params[$field];
669 $dao->$field = $params[$field];
673 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
675 // Ensure 'id' is included.
676 $options['return']['id'] = TRUE;
677 $allfields = _civicrm_api3_get_unique_name_array($dao);
678 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
679 foreach ($returnMatched as $returnValue) {
680 $dao->selectAdd($returnValue);
683 // Not already matched on the field names.
684 $unmatchedFields = array_diff(
685 array_keys($options['return']),
689 $returnUniqueMatched = array_intersect(
691 // But a match for the field keys.
692 array_flip($allfields)
694 foreach ($returnUniqueMatched as $uniqueVal) {
695 $dao->selectAdd($allfields[$uniqueVal]);
698 $dao->setApiFilter($params);
702 * Apply filters (e.g. high, low) to DAO object (prior to find).
704 * @param string $filterField
705 * Field name of filter.
706 * @param string $filterValue
707 * Field value of filter.
711 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
712 if (strstr($filterField, 'high')) {
713 $fieldName = substr($filterField, 0, -5);
714 $dao->whereAdd("($fieldName <= $filterValue )");
716 if (strstr($filterField, 'low')) {
717 $fieldName = substr($filterField, 0, -4);
718 $dao->whereAdd("($fieldName >= $filterValue )");
720 if ($filterField == 'is_current' && $filterValue == 1) {
721 $todayStart = date('Ymd000000', strtotime('now'));
722 $todayEnd = date('Ymd235959', strtotime('now'));
723 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
724 if (property_exists($dao, 'is_active')) {
725 $dao->whereAdd('is_active = 1');
731 * Get sort, limit etc options from the params - supporting old & new formats.
733 * Get returnProperties for legacy
735 * @param array $params
736 * Params array as passed into civicrm_api.
737 * @param bool $queryObject
738 * Is this supporting a queryObject api (e.g contact) - if so we support more options.
739 * for legacy report & return a unique fields array
741 * @param string $entity
742 * @param string $action
744 * @throws API_Exception
746 * options extracted from params
748 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
750 $sort = CRM_Utils_Array
::value('sort', $params, 0);
751 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
752 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
754 $offset = CRM_Utils_Array
::value('offset', $params, 0);
755 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
756 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
757 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
759 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
760 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
761 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
763 if (is_array(CRM_Utils_Array
::value('options', $params))) {
764 // is count is set by generic getcount not user
765 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
766 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
767 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
768 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
771 $returnProperties = array();
772 // handle the format return =sort_name,display_name...
773 if (array_key_exists('return', $params)) {
774 if (is_array($params['return'])) {
775 $returnProperties = array_fill_keys($params['return'], 1);
778 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
779 $returnProperties = array_fill_keys($returnProperties, 1);
782 if ($entity && $action == 'get') {
783 if (!empty($returnProperties['id'])) {
784 $returnProperties[$entity . '_id'] = 1;
785 unset($returnProperties['id']);
787 switch (trim(strtolower($sort))) {
791 $sort = str_replace('id', $entity . '_id', $sort);
796 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
797 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
798 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
799 'is_count' => $is_count,
800 'return' => !empty($returnProperties) ?
$returnProperties : array(),
803 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
804 throw new API_Exception('invalid string in sort options');
810 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
811 // if the queryobject is being used this should be used
812 $inputParams = array();
813 $legacyreturnProperties = array();
815 'sort', 'offset', 'rowCount', 'options', 'return',
817 foreach ($params as $n => $v) {
818 if (substr($n, 0, 7) == 'return.') {
819 $legacyreturnProperties[substr($n, 7)] = $v;
821 elseif ($n == 'id') {
822 $inputParams[$entity . '_id'] = $v;
824 elseif (in_array($n, $otherVars)) {
827 $inputParams[$n] = $v;
828 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
829 throw new API_Exception('invalid string');
833 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
834 $options['input_params'] = $inputParams;
839 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
841 * @param array $params
842 * Params array as passed into civicrm_api.
847 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
849 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
850 if (!$options['is_count']) {
851 if (!empty($options['limit'])) {
852 $dao->limit((int) $options['offset'], (int) $options['limit']);
854 if (!empty($options['sort'])) {
855 $dao->orderBy($options['sort']);
861 * Build fields array.
863 * This is the array of fields as it relates to the given DAO
864 * returns unique fields as keys by default but if set but can return by DB fields
866 * @param CRM_Core_DAO $bao
867 * @param bool $unique
871 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
872 $fields = $bao->fields();
874 if (empty($fields['id'])) {
875 $entity = _civicrm_api_get_entity_name_from_dao($bao);
876 $fields['id'] = $fields[$entity . '_id'];
877 unset($fields[$entity . '_id']);
882 foreach ($fields as $field) {
883 $dbFields[$field['name']] = $field;
889 * Build fields array.
891 * This is the array of fields as it relates to the given DAO
892 * returns unique fields as keys by default but if set but can return by DB fields
894 * @param CRM_Core_DAO $bao
898 function _civicrm_api3_get_unique_name_array(&$bao) {
899 $fields = $bao->fields();
900 foreach ($fields as $field => $values) {
901 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
903 return $uniqueFields;
907 * Converts an DAO object to an array.
909 * @param CRM_Core_DAO $dao
911 * @param array $params
912 * @param bool $uniqueFields
913 * @param string $entity
914 * @param bool $autoFind
918 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
920 if (isset($params['options']) && !empty($params['options']['is_count'])) {
921 return $dao->count();
926 if ($autoFind && !$dao->find()) {
930 if (isset($dao->count
)) {
934 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
936 while ($dao->fetch()) {
938 foreach ($fields as $key) {
939 if (array_key_exists($key, $dao)) {
940 // not sure on that one
941 if ($dao->$key !== NULL) {
942 $tmp[$key] = $dao->$key;
946 $result[$dao->id
] = $tmp;
948 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
949 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
957 * Determine if custom fields need to be retrieved.
959 * We currently retrieve all custom fields or none at this level so if we know the entity
960 * && 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
961 * @todo filter so only required fields are queried
963 * @param string $entity
964 * Entity name in CamelCase.
965 * @param array $params
969 function _civicrm_api3_custom_fields_are_required($entity, $params) {
970 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
973 $options = _civicrm_api3_get_options_from_params($params);
974 // We check for possibility of 'custom' => 1 as well as specific custom fields.
975 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
976 if (stristr($returnString, 'custom')) {
981 * Converts an object to an array.
984 * (reference) object to convert.
985 * @param array $values
987 * @param array|bool $uniqueFields
989 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
991 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
992 foreach ($fields as $key => $value) {
993 if (array_key_exists($key, $dao)) {
994 $values[$key] = $dao->$key;
1000 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1007 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1008 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1012 * Format custom parameters.
1014 * @param array $params
1015 * @param array $values
1016 * @param string $extends
1017 * Entity that this custom field extends (e.g. contribution, event, contact).
1018 * @param string $entityId
1019 * ID of entity per $extends.
1021 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1022 $values['custom'] = array();
1023 $checkCheckBoxField = FALSE;
1025 if (in_array($extends, array('Household', 'Individual', 'Organization'))) {
1026 $entity = 'Contact';
1029 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
1030 if (!$fields['is_error']) {
1031 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1032 $fields = $fields['values'];
1033 $checkCheckBoxField = TRUE;
1036 foreach ($params as $key => $value) {
1037 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
1038 if ($customFieldID && (!is_null($value))) {
1039 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1040 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1043 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1044 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1051 * Format parameters for create action.
1053 * @param array $params
1056 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1057 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1059 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery
::$extendsMap, array_fill_keys($nonGenericEntities, 1));
1060 if (!array_key_exists($entity, $customFieldEntities)) {
1064 _civicrm_api3_custom_format_params($params, $values, $entity);
1065 $params = array_merge($params, $values);
1069 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1071 * We should look at pushing to BAO function
1072 * 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
1073 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1075 * 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
1076 * don't touch - lots of very cautious code in here
1078 * The resulting array should look like
1084 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1086 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1087 * be fixed in future
1089 * @param mixed $checkboxFieldValue
1090 * @param string $customFieldLabel
1091 * @param string $entity
1093 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1095 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1096 // We can assume it's pre-formatted.
1099 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1100 if (!empty($options['is_error'])) {
1101 // The check is precautionary - can probably be removed later.
1105 $options = $options['values'];
1107 if (is_array($checkboxFieldValue)) {
1108 foreach ($checkboxFieldValue as $key => $value) {
1109 if (!array_key_exists($key, $options)) {
1110 $validValue = FALSE;
1114 // we have been passed an array that is already in the 'odd' custom field format
1119 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1120 // if the array only has one item we'll treat it like any other string
1121 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1122 $possibleValue = reset($checkboxFieldValue);
1124 if (is_string($checkboxFieldValue)) {
1125 $possibleValue = $checkboxFieldValue;
1127 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1128 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1131 elseif (is_array($checkboxFieldValue)) {
1132 // so this time around we are considering the values in the array
1133 $possibleValues = $checkboxFieldValue;
1134 $formatValue = TRUE;
1136 elseif (stristr($checkboxFieldValue, ',')) {
1137 $formatValue = TRUE;
1138 //lets see if we should separate it - we do this near the end so we
1139 // ensure we have already checked that the comma is not part of a legitimate match
1140 // and of course, we don't make any changes if we don't now have matches
1141 $possibleValues = explode(',', $checkboxFieldValue);
1144 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1148 foreach ($possibleValues as $index => $possibleValue) {
1149 if (array_key_exists($possibleValue, $options)) {
1150 // 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)
1152 elseif (array_key_exists(trim($possibleValue), $options)) {
1153 $possibleValues[$index] = trim($possibleValue);
1156 $formatValue = FALSE;
1160 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1165 * This function ensures that we have the right input parameters.
1169 * This function is only called when $dao is passed into verify_mandatory.
1170 * The practice of passing $dao into verify_mandatory turned out to be
1171 * unsatisfactory as the required fields @ the dao level is so different to the abstract
1172 * api level. Hence the intention is to remove this function
1173 * & the associated param from verify_mandatory
1175 * @param array $params
1176 * Associative array of property name/value.
1177 * pairs to insert in new history.
1178 * @param string $daoName
1179 * @param bool $return
1181 * @daoName string DAO to check params agains
1184 * Should the missing fields be returned as an array (core error created as default)
1185 * true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1187 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1188 //@deprecated - see notes
1189 if (isset($params['extends'])) {
1190 if (($params['extends'] == 'Activity' ||
1191 $params['extends'] == 'Phonecall' ||
1192 $params['extends'] == 'Meeting' ||
1193 $params['extends'] == 'Group' ||
1194 $params['extends'] == 'Contribution'
1196 ($params['style'] == 'Tab')
1198 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1202 $dao = new $daoName();
1203 $fields = $dao->fields();
1206 foreach ($fields as $k => $v) {
1207 if ($v['name'] == 'id') {
1211 if (!empty($v['required'])) {
1212 // 0 is a valid input for numbers, CRM-8122
1213 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1219 if (!empty($missing)) {
1220 if (!empty($return)) {
1224 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1232 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1234 * @param string $bao_name
1236 * @param array $params
1238 * @param bool $returnAsSuccess
1239 * Return in api success format.
1240 * @param string $entity
1244 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1245 $bao = new $bao_name();
1246 _civicrm_api3_dao_set_filter($bao, $params, TRUE, $entity);
1247 if ($returnAsSuccess) {
1248 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1251 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity, 'get');
1256 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1258 * @param string $bao_name
1259 * Name of BAO Class.
1260 * @param array $params
1261 * Parameters passed into the api call.
1262 * @param string $entity
1263 * Entity - pass in if entity is non-standard & required $ids array.
1265 * @throws API_Exception
1268 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1269 _civicrm_api3_format_params_for_create($params, $entity);
1270 $args = array(&$params);
1271 if (!empty($entity)) {
1272 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1276 if (method_exists($bao_name, 'create')) {
1278 $fct_name = $bao_name . '::' . $fct;
1279 $bao = call_user_func_array(array($bao_name, $fct), $args);
1281 elseif (method_exists($bao_name, 'add')) {
1283 $fct_name = $bao_name . '::' . $fct;
1284 $bao = call_user_func_array(array($bao_name, $fct), $args);
1287 $fct_name = '_civicrm_api3_basic_create_fallback';
1288 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1291 if (is_null($bao)) {
1292 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1294 elseif (is_a($bao, 'CRM_Core_Error')) {
1295 //some wierd circular thing means the error takes itself as an argument
1296 $msg = $bao->getMessages($bao);
1297 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1298 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1299 // so we need to reset the error object here to avoid getting concatenated errors
1300 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1301 CRM_Core_Error
::singleton()->reset();
1302 throw new API_Exception($msg);
1306 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1307 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1312 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1314 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1315 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1317 * @param string $bao_name
1318 * @param array $params
1320 * @throws API_Exception
1322 * @return CRM_Core_DAO|NULL
1323 * An instance of the BAO
1325 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1326 $dao_name = get_parent_class($bao_name);
1327 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1328 $dao_name = $bao_name;
1330 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1331 if (empty($entityName)) {
1332 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1333 'class_name' => $bao_name,
1336 $hook = empty($params['id']) ?
'create' : 'edit';
1338 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1339 $instance = new $dao_name();
1340 $instance->copyValues($params);
1342 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1348 * Function to do a 'standard' api del.
1350 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1352 * @param string $bao_name
1353 * @param array $params
1357 * @throws API_Exception
1359 function _civicrm_api3_basic_delete($bao_name, &$params) {
1361 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1362 $args = array(&$params['id']);
1363 if (method_exists($bao_name, 'del')) {
1364 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1365 if ($bao !== FALSE) {
1366 return civicrm_api3_create_success(TRUE);
1368 throw new API_Exception('Could not delete entity id ' . $params['id']);
1370 elseif (method_exists($bao_name, 'delete')) {
1371 $dao = new $bao_name();
1372 $dao->id
= $params['id'];
1374 while ($dao->fetch()) {
1376 return civicrm_api3_create_success();
1380 throw new API_Exception('Could not delete entity id ' . $params['id']);
1384 throw new API_Exception('no delete method found');
1388 * Get custom data for the given entity & Add it to the returnArray.
1390 * This looks like 'custom_123' = 'custom string' AND
1391 * 'custom_123_1' = 'custom string'
1392 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1394 * @param array $returnArray
1395 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1396 * @param string $entity
1397 * E.g membership, event.
1398 * @param int $entity_id
1399 * @param int $groupID
1400 * Per CRM_Core_BAO_CustomGroup::getTree.
1401 * @param int $subType
1402 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1403 * @param string $subName
1404 * Subtype of entity.
1406 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1407 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1408 CRM_Core_DAO
::$_nullObject,
1414 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1415 $customValues = array();
1416 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1417 $fieldInfo = array();
1418 foreach ($groupTree as $set) {
1419 $fieldInfo +
= $set['fields'];
1421 if (!empty($customValues)) {
1422 foreach ($customValues as $key => $val) {
1423 // per standard - return custom_fieldID
1424 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1425 $returnArray['custom_' . $id] = $val;
1427 //not standard - but some api did this so guess we should keep - cheap as chips
1428 $returnArray[$key] = $val;
1430 // Shim to restore legacy behavior of ContactReference custom fields
1431 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1432 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1433 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1440 * Validate fields being passed into API.
1442 * This function relies on the getFields function working accurately
1443 * for the given API. If error mode is set to TRUE then it will also check
1446 * As of writing only date was implemented.
1448 * @param string $entity
1449 * @param string $action
1450 * @param array $params
1452 * @param array $fields
1453 * Response from getfields all variables are the same as per civicrm_api.
1454 * @param bool $errorMode
1455 * ErrorMode do intensive post fail checks?.
1459 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = FALSE) {
1460 $fields = array_intersect_key($fields, $params);
1461 foreach ($fields as $fieldName => $fieldInfo) {
1462 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1463 case CRM_Utils_Type
::T_INT
:
1464 //field is of type integer
1465 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1470 case CRM_Utils_Type
::T_TIMESTAMP
:
1471 //field is of type date or datetime
1472 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1477 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1480 case CRM_Utils_Type
::T_STRING
:
1481 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1484 case CRM_Utils_Type
::T_MONEY
:
1485 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1486 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1489 foreach ((array) $fieldValue as $fieldvalue) {
1490 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1491 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1497 // intensive checks - usually only called after DB level fail
1498 if (!empty($errorMode) && strtolower($action) == 'create') {
1499 if (!empty($fieldInfo['FKClassName'])) {
1500 if (!empty($fieldValue)) {
1501 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1503 elseif (!empty($fieldInfo['required'])) {
1504 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1507 if (!empty($fieldInfo['api.unique'])) {
1508 $params['entity'] = $entity;
1509 _civicrm_api3_validate_unique_key($params, $fieldName);
1516 * Validate date fields being passed into API.
1518 * It currently converts both unique fields and DB field names to a mysql date.
1519 * @todo - probably the unique field handling & the if exists handling is now done before this
1520 * function is reached in the wrapper - can reduce this code down to assume we
1521 * are only checking the passed in field
1523 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1524 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1526 * @param array $params
1527 * Params from civicrm_api.
1528 * @param string $fieldName
1529 * Uniquename of field being checked.
1530 * @param array $fieldInfo
1531 * Array of fields from getfields function.
1535 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1536 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1537 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1540 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1541 if (!empty($params[$fieldInfo['name']])) {
1542 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1544 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1545 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1549 $params[$fieldName][$op] = $fieldValue;
1552 $params[$fieldName] = $fieldValue;
1557 * Convert date into BAO friendly date.
1559 * We accept 'whatever strtotime accepts'
1561 * @param string $dateValue
1562 * @param string $fieldName
1568 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1569 if (is_array($dateValue)) {
1570 foreach ($dateValue as $key => $value) {
1571 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1575 if (strtotime($dateValue) === FALSE) {
1576 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1578 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1579 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1583 * Validate foreign constraint fields being passed into API.
1585 * @param mixed $fieldValue
1586 * @param string $fieldName
1587 * Uniquename of field being checked.
1588 * @param array $fieldInfo
1589 * Array of fields from getfields function.
1591 * @throws \API_Exception
1593 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1594 $daoName = $fieldInfo['FKClassName'];
1595 $dao = new $daoName();
1596 $dao->id
= $fieldValue;
1598 $dao->selectAdd('id');
1599 if (!$dao->find()) {
1600 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1605 * Validate foreign constraint fields being passed into API.
1607 * @param array $params
1608 * Params from civicrm_api.
1609 * @param string $fieldName
1610 * Uniquename of field being checked.
1614 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1615 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1616 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1619 $existing = civicrm_api($params['entity'], 'get', array(
1620 'version' => $params['version'],
1621 $fieldName => $fieldValue,
1623 // an entry already exists for this unique field
1624 if ($existing['count'] == 1) {
1625 // question - could this ever be a security issue?
1626 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1631 * Generic implementation of the "replace" action.
1633 * Replace the old set of entities (matching some given keys) with a new set of
1634 * entities (matching the same keys).
1636 * @note This will verify that 'values' is present, but it does not directly verify
1637 * any other parameters.
1639 * @param string $entity
1641 * @param array $params
1642 * Params from civicrm_api, including:.
1643 * - 'values': an array of records to save
1644 * - all other items: keys which identify new/pre-existing records.
1648 function _civicrm_api3_generic_replace($entity, $params) {
1650 $transaction = new CRM_Core_Transaction();
1652 if (!is_array($params['values'])) {
1653 throw new Exception("Mandatory key(s) missing from params array: values");
1656 // Extract the keys -- somewhat scary, don't think too hard about it
1657 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1659 // Lookup pre-existing records
1660 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1661 if (civicrm_error($preexisting)) {
1662 $transaction->rollback();
1663 return $preexisting;
1666 // Save the new/updated records
1668 foreach ($params['values'] as $replacement) {
1669 // Sugar: Don't force clients to duplicate the 'key' data
1670 $replacement = array_merge($baseParams, $replacement);
1671 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1672 $create = civicrm_api($entity, $action, $replacement);
1673 if (civicrm_error($create)) {
1674 $transaction->rollback();
1677 foreach ($create['values'] as $entity_id => $entity_value) {
1678 $creates[$entity_id] = $entity_value;
1682 // Remove stale records
1683 $staleIDs = array_diff(
1684 array_keys($preexisting['values']),
1685 array_keys($creates)
1687 foreach ($staleIDs as $staleID) {
1688 $delete = civicrm_api($entity, 'delete', array(
1689 'version' => $params['version'],
1692 if (civicrm_error($delete)) {
1693 $transaction->rollback();
1698 return civicrm_api3_create_success($creates, $params);
1700 catch(PEAR_Exception
$e) {
1701 $transaction->rollback();
1702 return civicrm_api3_create_error($e->getMessage());
1704 catch(Exception
$e) {
1705 $transaction->rollback();
1706 return civicrm_api3_create_error($e->getMessage());
1711 * Replace base parameters.
1713 * @param array $params
1717 function _civicrm_api3_generic_replace_base_params($params) {
1718 $baseParams = $params;
1719 unset($baseParams['values']);
1720 unset($baseParams['sequential']);
1721 unset($baseParams['options']);
1726 * Returns fields allowable by api.
1729 * String Entity to query.
1730 * @param bool $unique
1731 * Index by unique fields?.
1732 * @param array $params
1736 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1737 $unsetIfEmpty = array(
1744 $dao = _civicrm_api3_get_DAO($entity);
1749 $fields = $d->fields();
1750 // replace uniqueNames by the normal names as the key
1751 if (empty($unique)) {
1752 foreach ($fields as $name => &$field) {
1753 //getting rid of unused attributes
1754 foreach ($unsetIfEmpty as $attr) {
1755 if (empty($field[$attr])) {
1756 unset($field[$attr]);
1759 if ($name == $field['name']) {
1762 if (array_key_exists($field['name'], $fields)) {
1763 $field['error'] = 'name conflict';
1764 // it should never happen, but better safe than sorry
1767 $fields[$field['name']] = $field;
1768 $fields[$field['name']]['uniqueName'] = $name;
1769 unset($fields[$name]);
1772 // Translate FKClassName to the corresponding api
1773 foreach ($fields as $name => &$field) {
1774 if (!empty($field['FKClassName'])) {
1775 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1777 $field['FKApiName'] = $FKApi;
1781 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1786 * Return an array of fields for a given entity.
1788 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1791 * @param array $params
1795 function _civicrm_api_get_custom_fields($entity, &$params) {
1796 $entity = _civicrm_api_get_camel_name($entity);
1797 if ($entity == 'Contact') {
1798 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1799 $entity = CRM_Utils_Array
::value('contact_type', $params);
1801 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1804 // we could / should probably test for other subtypes here - e.g. activity_type_id
1805 CRM_Utils_Array
::value('contact_sub_type', $params),
1814 foreach ($customfields as $key => $value) {
1815 // Regular fields have a 'name' property
1816 $value['name'] = 'custom_' . $key;
1817 $value['title'] = $value['label'];
1818 $value['type'] = _getStandardTypeFromCustomDataType($value['data_type']);
1819 $ret['custom_' . $key] = $value;
1825 * Translate the custom field data_type attribute into a std 'type'.
1831 function _getStandardTypeFromCustomDataType($dataType) {
1833 'String' => CRM_Utils_Type
::T_STRING
,
1834 'Int' => CRM_Utils_Type
::T_INT
,
1835 'Money' => CRM_Utils_Type
::T_MONEY
,
1836 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1837 'Float' => CRM_Utils_Type
::T_FLOAT
,
1838 'Date' => CRM_Utils_Type
::T_DATE
,
1839 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1840 'StateProvince' => CRM_Utils_Type
::T_INT
,
1841 'File' => CRM_Utils_Type
::T_STRING
,
1842 'Link' => CRM_Utils_Type
::T_STRING
,
1843 'ContactReference' => CRM_Utils_Type
::T_INT
,
1844 'Country' => CRM_Utils_Type
::T_INT
,
1846 return $mapping[$dataType];
1851 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
1853 * If multiple aliases the last takes precedence
1855 * Function also swaps unique fields for non-unique fields & vice versa.
1857 * @param $apiRequest
1860 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1861 foreach ($fields as $field => $values) {
1862 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1863 if (!empty($values['api.aliases'])) {
1864 // if aliased field is not set we try to use field alias
1865 if (!isset($apiRequest['params'][$field])) {
1866 foreach ($values['api.aliases'] as $alias) {
1867 if (isset($apiRequest['params'][$alias])) {
1868 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1870 //unset original field nb - need to be careful with this as it may bring inconsistencies
1871 // out of the woodwork but will be implementing only as _spec function extended
1872 unset($apiRequest['params'][$alias]);
1876 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
1877 && isset($apiRequest['params'][$values['name']])
1879 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1880 // note that it would make sense to unset the original field here but tests need to be in place first
1882 if (!isset($apiRequest['params'][$field])
1884 && $field != $uniqueName
1885 && array_key_exists($uniqueName, $apiRequest['params'])
1887 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1888 // note that it would make sense to unset the original field here but tests need to be in place first
1895 * Validate integer fields being passed into API.
1897 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
1899 * @param array $params
1900 * Params from civicrm_api.
1901 * @param string $fieldName
1902 * Uniquename of field being checked.
1903 * @param array $fieldInfo
1904 * Array of fields from getfields function.
1905 * @param string $entity
1907 * @throws API_Exception
1909 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1910 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1911 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1915 if (!empty($fieldValue)) {
1916 // if value = 'user_contact_id' (or similar), replace value with contact id
1917 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
1918 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
1919 if ('unknown-user' === $realContactId) {
1920 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName, "type" => "integer"));
1922 elseif (is_numeric($realContactId)) {
1923 $fieldValue = $realContactId;
1926 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1927 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
1930 // After swapping options, ensure we have an integer(s)
1931 foreach ((array) ($fieldValue) as $value) {
1932 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1933 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1937 // Check our field length
1938 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
1940 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1941 2100, array('field' => $fieldName, "max_length" => $fieldInfo['maxlength'])
1947 $params[$fieldName][$op] = $fieldValue;
1950 $params[$fieldName] = $fieldValue;
1955 * Determine a contact ID using a string expression.
1957 * @param string $contactIdExpr
1958 * E.g. "user_contact_id" or "@user:username".
1960 * @return int|NULL|'unknown-user'
1962 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1963 // If value = 'user_contact_id' replace value with logged in user id.
1964 if ($contactIdExpr == "user_contact_id") {
1965 return CRM_Core_Session
::getLoggedInContactID();
1967 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1968 $config = CRM_Core_Config
::singleton();
1970 $ufID = $config->userSystem
->getUfId($matches[1]);
1972 return 'unknown-user';
1975 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
1977 return 'unknown-user';
1986 * Validate html (check for scripting attack).
1988 * @param array $params
1989 * @param string $fieldName
1990 * @param array $fieldInfo
1992 * @throws API_Exception
1994 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
1995 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1996 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
2000 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2001 throw new API_Exception('Illegal characters in input (potential scripting attack)', array("field" => $fieldName, "error_code" => "xss"));
2007 * Validate string fields being passed into API.
2009 * @param array $params
2010 * Params from civicrm_api.
2011 * @param string $fieldName
2012 * Uniquename of field being checked.
2013 * @param array $fieldInfo
2014 * Array of fields from getfields function.
2015 * @param string $entity
2017 * @throws API_Exception
2020 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2021 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2022 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
2026 if (!is_array($fieldValue)) {
2027 $fieldValue = (string) $fieldValue;
2030 //@todo what do we do about passed in arrays. For many of these fields
2031 // the missing piece of functionality is separating them to a separated string
2032 // & many save incorrectly. But can we change them wholesale?
2035 foreach ((array) $fieldValue as $value) {
2036 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2037 throw new Exception('Illegal characters in input (potential scripting attack)');
2039 if ($fieldName == 'currency') {
2040 //When using IN operator $fieldValue is a array of currency codes
2041 if (!CRM_Utils_Rule
::currencyCode($value)) {
2042 throw new Exception("Currency not a valid code: $currency");
2047 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2048 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
2050 // Check our field length
2051 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2052 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2053 2100, array('field' => $fieldName)
2058 $params[$fieldName][$op] = $fieldValue;
2061 $params[$fieldName] = $fieldValue;
2066 * Validate & swap out any pseudoconstants / options.
2068 * @param mixed $fieldValue
2069 * @param string $entity : api entity name
2070 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2071 * @param array $fieldInfo : getfields meta-data
2073 * @throws \API_Exception
2075 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo) {
2076 $options = CRM_Utils_Array
::value('options', $fieldInfo);
2079 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2080 // We need to get the options from the entity the field relates to.
2081 $entity = $fieldInfo['entity'];
2083 $options = civicrm_api($entity, 'getoptions', array(
2085 'field' => $fieldInfo['name'],
2086 'context' => 'validate',
2088 $options = CRM_Utils_Array
::value('values', $options, array());
2091 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2093 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2094 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
2097 // If passed multiple options, validate each.
2098 if (is_array($fieldValue)) {
2099 foreach ($fieldValue as &$value) {
2100 if (!is_array($value)) {
2101 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
2104 // TODO: unwrap the call to implodePadded from the conditional and do it always
2105 // need to verify that this is safe and doesn't break anything though.
2106 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2108 CRM_Utils_Array
::implodePadded($fieldValue);
2112 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName);
2117 * Validate & swap a single option value for a field.
2119 * @param string $value field value
2120 * @param array $options array of options for this field
2121 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2123 * @throws API_Exception
2125 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
2126 // If option is a key, no need to translate
2127 // or if no options are avaiable for pseudoconstant 'table' property
2128 if (array_key_exists($value, $options) ||
!$options) {
2132 // Translate value into key
2133 $newValue = array_search($value, $options);
2134 if ($newValue !== FALSE) {
2138 // Case-insensitive matching
2139 $newValue = strtolower($value);
2140 $options = array_map("strtolower", $options);
2141 $newValue = array_search($newValue, $options);
2142 if ($newValue === FALSE) {
2143 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
2149 * Returns the canonical name of a field.
2152 * api entity name (string should already be standardized - no camelCase).
2154 * any variation of a field's name (name, unique_name, api.alias).
2156 * @return bool|string
2157 * fieldName or FALSE if the field does not exist
2159 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
2160 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2163 if ($fieldName == "{$entity}_id") {
2166 $result = civicrm_api($entity, 'getfields', array(
2168 'action' => 'create',
2170 $meta = $result['values'];
2171 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2172 $fieldName = $fieldName . '_id';
2174 if (isset($meta[$fieldName])) {
2175 return $meta[$fieldName]['name'];
2177 foreach ($meta as $info) {
2178 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2179 return $info['name'];
2181 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
2182 return $info['name'];
2189 * Check if the function is deprecated.
2191 * @param string $entity
2192 * @param array $result
2194 * @return string|array|null
2196 function _civicrm_api3_deprecation_check($entity, $result = array()) {
2198 $apiFile = 'api/v3/' . _civicrm_api_get_camel_name($entity) . '.php';
2199 if (CRM_Utils_File
::isIncludable($apiFile)) {
2200 require_once $apiFile;
2202 $entity = _civicrm_api_get_entity_name_from_camel($entity);
2203 $fnName = "_civicrm_api3_{$entity}_deprecation";
2204 if (function_exists($fnName)) {
2205 return $fnName($result);
2211 * Get the actual field value.
2213 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2214 * So this function returns the actual field value
2216 * @param array $params
2217 * @param string $fieldName
2221 function _civicrm_api3_field_value_check(&$params, $fieldName) {
2222 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2225 if (!empty($fieldValue) && is_array($fieldValue) && array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators())) {
2226 $op = key($fieldValue);
2227 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2229 return array($fieldValue, $op);