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);
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 = '') {
749 // Entity should be l-case so it can be concatenated into field names
750 $entity = _civicrm_api_get_entity_name_from_camel($entity);
752 $sort = CRM_Utils_Array
::value('sort', $params, 0);
753 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
754 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
756 $offset = CRM_Utils_Array
::value('offset', $params, 0);
757 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
758 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
759 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
761 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
762 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
763 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
765 if (is_array(CRM_Utils_Array
::value('options', $params))) {
766 // is count is set by generic getcount not user
767 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
768 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
769 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
770 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
773 $returnProperties = array();
774 // handle the format return =sort_name,display_name...
775 if (array_key_exists('return', $params)) {
776 if (is_array($params['return'])) {
777 $returnProperties = array_fill_keys($params['return'], 1);
780 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
781 $returnProperties = array_fill_keys($returnProperties, 1);
784 if ($entity && $action == 'get') {
785 if (!empty($returnProperties['id'])) {
786 $returnProperties[$entity . '_id'] = 1;
787 unset($returnProperties['id']);
789 switch (trim(strtolower($sort))) {
793 $sort = str_replace('id', $entity . '_id', $sort);
798 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
799 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
800 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
801 'is_count' => $is_count,
802 'return' => !empty($returnProperties) ?
$returnProperties : array(),
805 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
806 throw new API_Exception('invalid string in sort options');
812 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
813 // if the queryobject is being used this should be used
814 $inputParams = array();
815 $legacyreturnProperties = array();
817 'sort', 'offset', 'rowCount', 'options', 'return',
819 foreach ($params as $n => $v) {
820 if (substr($n, 0, 7) == 'return.') {
821 $legacyreturnProperties[substr($n, 7)] = $v;
823 elseif ($n == 'id') {
824 $inputParams[$entity . '_id'] = $v;
826 elseif (in_array($n, $otherVars)) {
829 $inputParams[$n] = $v;
830 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
831 throw new API_Exception('invalid string');
835 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
836 $options['input_params'] = $inputParams;
841 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
843 * @param array $params
844 * Params array as passed into civicrm_api.
849 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
851 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
852 if (!$options['is_count']) {
853 if (!empty($options['limit'])) {
854 $dao->limit((int) $options['offset'], (int) $options['limit']);
856 if (!empty($options['sort'])) {
857 $dao->orderBy($options['sort']);
863 * Build fields array.
865 * This is the array of fields as it relates to the given DAO
866 * returns unique fields as keys by default but if set but can return by DB fields
868 * @param CRM_Core_DAO $bao
869 * @param bool $unique
873 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
874 $fields = $bao->fields();
876 if (empty($fields['id'])) {
877 $entity = _civicrm_api_get_entity_name_from_dao($bao);
878 $fields['id'] = $fields[$entity . '_id'];
879 unset($fields[$entity . '_id']);
884 foreach ($fields as $field) {
885 $dbFields[$field['name']] = $field;
891 * Build fields array.
893 * This is the array of fields as it relates to the given DAO
894 * returns unique fields as keys by default but if set but can return by DB fields
896 * @param CRM_Core_DAO $bao
900 function _civicrm_api3_get_unique_name_array(&$bao) {
901 $fields = $bao->fields();
902 foreach ($fields as $field => $values) {
903 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
905 return $uniqueFields;
909 * Converts an DAO object to an array.
911 * @param CRM_Core_DAO $dao
913 * @param array $params
914 * @param bool $uniqueFields
915 * @param string $entity
916 * @param bool $autoFind
920 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
922 if (isset($params['options']) && !empty($params['options']['is_count'])) {
923 return $dao->count();
928 if ($autoFind && !$dao->find()) {
932 if (isset($dao->count
)) {
936 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
938 while ($dao->fetch()) {
940 foreach ($fields as $key) {
941 if (array_key_exists($key, $dao)) {
942 // not sure on that one
943 if ($dao->$key !== NULL) {
944 $tmp[$key] = $dao->$key;
948 $result[$dao->id
] = $tmp;
950 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
951 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
959 * Determine if custom fields need to be retrieved.
961 * We currently retrieve all custom fields or none at this level so if we know the entity
962 * && 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
963 * @todo filter so only required fields are queried
965 * @param string $entity
966 * Entity name in CamelCase.
967 * @param array $params
971 function _civicrm_api3_custom_fields_are_required($entity, $params) {
972 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
975 $options = _civicrm_api3_get_options_from_params($params);
976 // We check for possibility of 'custom' => 1 as well as specific custom fields.
977 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
978 if (stristr($returnString, 'custom')) {
983 * Converts an object to an array.
986 * (reference) object to convert.
987 * @param array $values
989 * @param array|bool $uniqueFields
991 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
993 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
994 foreach ($fields as $key => $value) {
995 if (array_key_exists($key, $dao)) {
996 $values[$key] = $dao->$key;
1002 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1009 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1010 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1014 * Format custom parameters.
1016 * @param array $params
1017 * @param array $values
1018 * @param string $extends
1019 * Entity that this custom field extends (e.g. contribution, event, contact).
1020 * @param string $entityId
1021 * ID of entity per $extends.
1023 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1024 $values['custom'] = array();
1025 $checkCheckBoxField = FALSE;
1027 if (in_array($extends, array('Household', 'Individual', 'Organization'))) {
1028 $entity = 'Contact';
1031 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
1032 if (!$fields['is_error']) {
1033 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1034 $fields = $fields['values'];
1035 $checkCheckBoxField = TRUE;
1038 foreach ($params as $key => $value) {
1039 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
1040 if ($customFieldID && (!is_null($value))) {
1041 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1042 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1045 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1046 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1053 * Format parameters for create action.
1055 * @param array $params
1058 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1059 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1061 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery
::$extendsMap, array_fill_keys($nonGenericEntities, 1));
1062 if (!array_key_exists($entity, $customFieldEntities)) {
1066 _civicrm_api3_custom_format_params($params, $values, $entity);
1067 $params = array_merge($params, $values);
1071 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1073 * We should look at pushing to BAO function
1074 * 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
1075 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1077 * 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
1078 * don't touch - lots of very cautious code in here
1080 * The resulting array should look like
1086 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1088 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1089 * be fixed in future
1091 * @param mixed $checkboxFieldValue
1092 * @param string $customFieldLabel
1093 * @param string $entity
1095 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1097 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1098 // We can assume it's pre-formatted.
1101 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1102 if (!empty($options['is_error'])) {
1103 // The check is precautionary - can probably be removed later.
1107 $options = $options['values'];
1109 if (is_array($checkboxFieldValue)) {
1110 foreach ($checkboxFieldValue as $key => $value) {
1111 if (!array_key_exists($key, $options)) {
1112 $validValue = FALSE;
1116 // we have been passed an array that is already in the 'odd' custom field format
1121 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1122 // if the array only has one item we'll treat it like any other string
1123 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1124 $possibleValue = reset($checkboxFieldValue);
1126 if (is_string($checkboxFieldValue)) {
1127 $possibleValue = $checkboxFieldValue;
1129 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1130 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1133 elseif (is_array($checkboxFieldValue)) {
1134 // so this time around we are considering the values in the array
1135 $possibleValues = $checkboxFieldValue;
1136 $formatValue = TRUE;
1138 elseif (stristr($checkboxFieldValue, ',')) {
1139 $formatValue = TRUE;
1140 //lets see if we should separate it - we do this near the end so we
1141 // ensure we have already checked that the comma is not part of a legitimate match
1142 // and of course, we don't make any changes if we don't now have matches
1143 $possibleValues = explode(',', $checkboxFieldValue);
1146 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1150 foreach ($possibleValues as $index => $possibleValue) {
1151 if (array_key_exists($possibleValue, $options)) {
1152 // 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)
1154 elseif (array_key_exists(trim($possibleValue), $options)) {
1155 $possibleValues[$index] = trim($possibleValue);
1158 $formatValue = FALSE;
1162 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1167 * This function ensures that we have the right input parameters.
1171 * This function is only called when $dao is passed into verify_mandatory.
1172 * The practice of passing $dao into verify_mandatory turned out to be
1173 * unsatisfactory as the required fields @ the dao level is so different to the abstract
1174 * api level. Hence the intention is to remove this function
1175 * & the associated param from verify_mandatory
1177 * @param array $params
1178 * Associative array of property name/value.
1179 * pairs to insert in new history.
1180 * @param string $daoName
1181 * @param bool $return
1183 * @daoName string DAO to check params agains
1186 * Should the missing fields be returned as an array (core error created as default)
1187 * true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1189 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1190 //@deprecated - see notes
1191 if (isset($params['extends'])) {
1192 if (($params['extends'] == 'Activity' ||
1193 $params['extends'] == 'Phonecall' ||
1194 $params['extends'] == 'Meeting' ||
1195 $params['extends'] == 'Group' ||
1196 $params['extends'] == 'Contribution'
1198 ($params['style'] == 'Tab')
1200 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1204 $dao = new $daoName();
1205 $fields = $dao->fields();
1208 foreach ($fields as $k => $v) {
1209 if ($v['name'] == 'id') {
1213 if (!empty($v['required'])) {
1214 // 0 is a valid input for numbers, CRM-8122
1215 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1221 if (!empty($missing)) {
1222 if (!empty($return)) {
1226 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1234 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1236 * @param string $bao_name
1238 * @param array $params
1240 * @param bool $returnAsSuccess
1241 * Return in api success format.
1242 * @param string $entity
1246 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1247 $bao = new $bao_name();
1248 _civicrm_api3_dao_set_filter($bao, $params, TRUE, $entity);
1249 if ($returnAsSuccess) {
1250 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1253 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity, 'get');
1258 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1260 * @param string $bao_name
1261 * Name of BAO Class.
1262 * @param array $params
1263 * Parameters passed into the api call.
1264 * @param string $entity
1265 * Entity - pass in if entity is non-standard & required $ids array.
1267 * @throws API_Exception
1270 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1271 _civicrm_api3_format_params_for_create($params, $entity);
1272 $args = array(&$params);
1273 if (!empty($entity)) {
1274 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1278 if (method_exists($bao_name, 'create')) {
1280 $fct_name = $bao_name . '::' . $fct;
1281 $bao = call_user_func_array(array($bao_name, $fct), $args);
1283 elseif (method_exists($bao_name, 'add')) {
1285 $fct_name = $bao_name . '::' . $fct;
1286 $bao = call_user_func_array(array($bao_name, $fct), $args);
1289 $fct_name = '_civicrm_api3_basic_create_fallback';
1290 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1293 if (is_null($bao)) {
1294 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1296 elseif (is_a($bao, 'CRM_Core_Error')) {
1297 //some wierd circular thing means the error takes itself as an argument
1298 $msg = $bao->getMessages($bao);
1299 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1300 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1301 // so we need to reset the error object here to avoid getting concatenated errors
1302 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1303 CRM_Core_Error
::singleton()->reset();
1304 throw new API_Exception($msg);
1308 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1309 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1314 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1316 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1317 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1319 * @param string $bao_name
1320 * @param array $params
1322 * @throws API_Exception
1324 * @return CRM_Core_DAO|NULL
1325 * An instance of the BAO
1327 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1328 $dao_name = get_parent_class($bao_name);
1329 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1330 $dao_name = $bao_name;
1332 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1333 if (empty($entityName)) {
1334 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1335 'class_name' => $bao_name,
1338 $hook = empty($params['id']) ?
'create' : 'edit';
1340 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1341 $instance = new $dao_name();
1342 $instance->copyValues($params);
1344 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1350 * Function to do a 'standard' api del.
1352 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1354 * @param string $bao_name
1355 * @param array $params
1359 * @throws API_Exception
1361 function _civicrm_api3_basic_delete($bao_name, &$params) {
1363 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1364 $args = array(&$params['id']);
1365 if (method_exists($bao_name, 'del')) {
1366 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1367 if ($bao !== FALSE) {
1368 return civicrm_api3_create_success(TRUE);
1370 throw new API_Exception('Could not delete entity id ' . $params['id']);
1372 elseif (method_exists($bao_name, 'delete')) {
1373 $dao = new $bao_name();
1374 $dao->id
= $params['id'];
1376 while ($dao->fetch()) {
1378 return civicrm_api3_create_success();
1382 throw new API_Exception('Could not delete entity id ' . $params['id']);
1386 throw new API_Exception('no delete method found');
1390 * Get custom data for the given entity & Add it to the returnArray.
1392 * This looks like 'custom_123' = 'custom string' AND
1393 * 'custom_123_1' = 'custom string'
1394 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1396 * @param array $returnArray
1397 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1398 * @param string $entity
1399 * E.g membership, event.
1400 * @param int $entity_id
1401 * @param int $groupID
1402 * Per CRM_Core_BAO_CustomGroup::getTree.
1403 * @param int $subType
1404 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1405 * @param string $subName
1406 * Subtype of entity.
1408 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1409 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1410 CRM_Core_DAO
::$_nullObject,
1416 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1417 $customValues = array();
1418 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1419 $fieldInfo = array();
1420 foreach ($groupTree as $set) {
1421 $fieldInfo +
= $set['fields'];
1423 if (!empty($customValues)) {
1424 foreach ($customValues as $key => $val) {
1425 // per standard - return custom_fieldID
1426 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1427 $returnArray['custom_' . $id] = $val;
1429 //not standard - but some api did this so guess we should keep - cheap as chips
1430 $returnArray[$key] = $val;
1432 // Shim to restore legacy behavior of ContactReference custom fields
1433 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1434 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1435 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1442 * Validate fields being passed into API.
1444 * This function relies on the getFields function working accurately
1445 * for the given API. If error mode is set to TRUE then it will also check
1448 * As of writing only date was implemented.
1450 * @param string $entity
1451 * @param string $action
1452 * @param array $params
1454 * @param array $fields
1455 * Response from getfields all variables are the same as per civicrm_api.
1456 * @param bool $errorMode
1457 * ErrorMode do intensive post fail checks?.
1461 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = FALSE) {
1462 $fields = array_intersect_key($fields, $params);
1463 foreach ($fields as $fieldName => $fieldInfo) {
1464 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1465 case CRM_Utils_Type
::T_INT
:
1466 //field is of type integer
1467 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1472 case CRM_Utils_Type
::T_TIMESTAMP
:
1473 //field is of type date or datetime
1474 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1479 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1482 case CRM_Utils_Type
::T_STRING
:
1483 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1486 case CRM_Utils_Type
::T_MONEY
:
1487 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1488 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1491 foreach ((array) $fieldValue as $fieldvalue) {
1492 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1493 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1499 // intensive checks - usually only called after DB level fail
1500 if (!empty($errorMode) && strtolower($action) == 'create') {
1501 if (!empty($fieldInfo['FKClassName'])) {
1502 if (!empty($fieldValue)) {
1503 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1505 elseif (!empty($fieldInfo['required'])) {
1506 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1509 if (!empty($fieldInfo['api.unique'])) {
1510 $params['entity'] = $entity;
1511 _civicrm_api3_validate_unique_key($params, $fieldName);
1518 * Validate date fields being passed into API.
1520 * It currently converts both unique fields and DB field names to a mysql date.
1521 * @todo - probably the unique field handling & the if exists handling is now done before this
1522 * function is reached in the wrapper - can reduce this code down to assume we
1523 * are only checking the passed in field
1525 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1526 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1528 * @param array $params
1529 * Params from civicrm_api.
1530 * @param string $fieldName
1531 * Uniquename of field being checked.
1532 * @param array $fieldInfo
1533 * Array of fields from getfields function.
1537 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1538 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1539 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1542 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1543 if (!empty($params[$fieldInfo['name']])) {
1544 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1546 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1547 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1551 $params[$fieldName][$op] = $fieldValue;
1554 $params[$fieldName] = $fieldValue;
1559 * Convert date into BAO friendly date.
1561 * We accept 'whatever strtotime accepts'
1563 * @param string $dateValue
1564 * @param string $fieldName
1570 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1571 if (is_array($dateValue)) {
1572 foreach ($dateValue as $key => $value) {
1573 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1577 if (strtotime($dateValue) === FALSE) {
1578 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1580 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1581 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1585 * Validate foreign constraint fields being passed into API.
1587 * @param mixed $fieldValue
1588 * @param string $fieldName
1589 * Uniquename of field being checked.
1590 * @param array $fieldInfo
1591 * Array of fields from getfields function.
1593 * @throws \API_Exception
1595 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1596 $daoName = $fieldInfo['FKClassName'];
1597 $dao = new $daoName();
1598 $dao->id
= $fieldValue;
1600 $dao->selectAdd('id');
1601 if (!$dao->find()) {
1602 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1607 * Validate foreign constraint fields being passed into API.
1609 * @param array $params
1610 * Params from civicrm_api.
1611 * @param string $fieldName
1612 * Uniquename of field being checked.
1616 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1617 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1618 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1621 $existing = civicrm_api($params['entity'], 'get', array(
1622 'version' => $params['version'],
1623 $fieldName => $fieldValue,
1625 // an entry already exists for this unique field
1626 if ($existing['count'] == 1) {
1627 // question - could this ever be a security issue?
1628 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1633 * Generic implementation of the "replace" action.
1635 * Replace the old set of entities (matching some given keys) with a new set of
1636 * entities (matching the same keys).
1638 * @note This will verify that 'values' is present, but it does not directly verify
1639 * any other parameters.
1641 * @param string $entity
1643 * @param array $params
1644 * Params from civicrm_api, including:.
1645 * - 'values': an array of records to save
1646 * - all other items: keys which identify new/pre-existing records.
1650 function _civicrm_api3_generic_replace($entity, $params) {
1652 $transaction = new CRM_Core_Transaction();
1654 if (!is_array($params['values'])) {
1655 throw new Exception("Mandatory key(s) missing from params array: values");
1658 // Extract the keys -- somewhat scary, don't think too hard about it
1659 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1661 // Lookup pre-existing records
1662 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1663 if (civicrm_error($preexisting)) {
1664 $transaction->rollback();
1665 return $preexisting;
1668 // Save the new/updated records
1670 foreach ($params['values'] as $replacement) {
1671 // Sugar: Don't force clients to duplicate the 'key' data
1672 $replacement = array_merge($baseParams, $replacement);
1673 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1674 $create = civicrm_api($entity, $action, $replacement);
1675 if (civicrm_error($create)) {
1676 $transaction->rollback();
1679 foreach ($create['values'] as $entity_id => $entity_value) {
1680 $creates[$entity_id] = $entity_value;
1684 // Remove stale records
1685 $staleIDs = array_diff(
1686 array_keys($preexisting['values']),
1687 array_keys($creates)
1689 foreach ($staleIDs as $staleID) {
1690 $delete = civicrm_api($entity, 'delete', array(
1691 'version' => $params['version'],
1694 if (civicrm_error($delete)) {
1695 $transaction->rollback();
1700 return civicrm_api3_create_success($creates, $params);
1702 catch(PEAR_Exception
$e) {
1703 $transaction->rollback();
1704 return civicrm_api3_create_error($e->getMessage());
1706 catch(Exception
$e) {
1707 $transaction->rollback();
1708 return civicrm_api3_create_error($e->getMessage());
1713 * Replace base parameters.
1715 * @param array $params
1719 function _civicrm_api3_generic_replace_base_params($params) {
1720 $baseParams = $params;
1721 unset($baseParams['values']);
1722 unset($baseParams['sequential']);
1723 unset($baseParams['options']);
1728 * Returns fields allowable by api.
1731 * String Entity to query.
1732 * @param bool $unique
1733 * Index by unique fields?.
1734 * @param array $params
1738 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1739 $unsetIfEmpty = array(
1746 $dao = _civicrm_api3_get_DAO($entity);
1751 $fields = $d->fields();
1752 // replace uniqueNames by the normal names as the key
1753 if (empty($unique)) {
1754 foreach ($fields as $name => &$field) {
1755 //getting rid of unused attributes
1756 foreach ($unsetIfEmpty as $attr) {
1757 if (empty($field[$attr])) {
1758 unset($field[$attr]);
1761 if ($name == $field['name']) {
1764 if (array_key_exists($field['name'], $fields)) {
1765 $field['error'] = 'name conflict';
1766 // it should never happen, but better safe than sorry
1769 $fields[$field['name']] = $field;
1770 $fields[$field['name']]['uniqueName'] = $name;
1771 unset($fields[$name]);
1774 // Translate FKClassName to the corresponding api
1775 foreach ($fields as $name => &$field) {
1776 if (!empty($field['FKClassName'])) {
1777 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1779 $field['FKApiName'] = $FKApi;
1783 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1788 * Return an array of fields for a given entity.
1790 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1793 * @param array $params
1797 function _civicrm_api_get_custom_fields($entity, &$params) {
1798 $entity = _civicrm_api_get_camel_name($entity);
1799 if ($entity == 'Contact') {
1800 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1801 $entity = CRM_Utils_Array
::value('contact_type', $params);
1803 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1806 // we could / should probably test for other subtypes here - e.g. activity_type_id
1807 CRM_Utils_Array
::value('contact_sub_type', $params),
1816 foreach ($customfields as $key => $value) {
1817 // Regular fields have a 'name' property
1818 $value['name'] = 'custom_' . $key;
1819 $value['title'] = $value['label'];
1820 $value['type'] = _getStandardTypeFromCustomDataType($value['data_type']);
1821 $ret['custom_' . $key] = $value;
1827 * Translate the custom field data_type attribute into a std 'type'.
1833 function _getStandardTypeFromCustomDataType($dataType) {
1835 'String' => CRM_Utils_Type
::T_STRING
,
1836 'Int' => CRM_Utils_Type
::T_INT
,
1837 'Money' => CRM_Utils_Type
::T_MONEY
,
1838 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1839 'Float' => CRM_Utils_Type
::T_FLOAT
,
1840 'Date' => CRM_Utils_Type
::T_DATE
,
1841 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1842 'StateProvince' => CRM_Utils_Type
::T_INT
,
1843 'File' => CRM_Utils_Type
::T_STRING
,
1844 'Link' => CRM_Utils_Type
::T_STRING
,
1845 'ContactReference' => CRM_Utils_Type
::T_INT
,
1846 'Country' => CRM_Utils_Type
::T_INT
,
1848 return $mapping[$dataType];
1853 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
1855 * If multiple aliases the last takes precedence
1857 * Function also swaps unique fields for non-unique fields & vice versa.
1859 * @param $apiRequest
1862 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1863 foreach ($fields as $field => $values) {
1864 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1865 if (!empty($values['api.aliases'])) {
1866 // if aliased field is not set we try to use field alias
1867 if (!isset($apiRequest['params'][$field])) {
1868 foreach ($values['api.aliases'] as $alias) {
1869 if (isset($apiRequest['params'][$alias])) {
1870 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1872 //unset original field nb - need to be careful with this as it may bring inconsistencies
1873 // out of the woodwork but will be implementing only as _spec function extended
1874 unset($apiRequest['params'][$alias]);
1878 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
1879 && isset($apiRequest['params'][$values['name']])
1881 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1882 // note that it would make sense to unset the original field here but tests need to be in place first
1884 if (!isset($apiRequest['params'][$field])
1886 && $field != $uniqueName
1887 && array_key_exists($uniqueName, $apiRequest['params'])
1889 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1890 // note that it would make sense to unset the original field here but tests need to be in place first
1897 * Validate integer fields being passed into API.
1899 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
1901 * @param array $params
1902 * Params from civicrm_api.
1903 * @param string $fieldName
1904 * Uniquename of field being checked.
1905 * @param array $fieldInfo
1906 * Array of fields from getfields function.
1907 * @param string $entity
1909 * @throws API_Exception
1911 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1912 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1913 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1917 if (!empty($fieldValue)) {
1918 // if value = 'user_contact_id' (or similar), replace value with contact id
1919 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
1920 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
1921 if ('unknown-user' === $realContactId) {
1922 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName, "type" => "integer"));
1924 elseif (is_numeric($realContactId)) {
1925 $fieldValue = $realContactId;
1928 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1929 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
1932 // After swapping options, ensure we have an integer(s)
1933 foreach ((array) ($fieldValue) as $value) {
1934 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1935 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1939 // Check our field length
1940 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
1942 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1943 2100, array('field' => $fieldName, "max_length" => $fieldInfo['maxlength'])
1949 $params[$fieldName][$op] = $fieldValue;
1952 $params[$fieldName] = $fieldValue;
1957 * Determine a contact ID using a string expression.
1959 * @param string $contactIdExpr
1960 * E.g. "user_contact_id" or "@user:username".
1962 * @return int|NULL|'unknown-user'
1964 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1965 // If value = 'user_contact_id' replace value with logged in user id.
1966 if ($contactIdExpr == "user_contact_id") {
1967 return CRM_Core_Session
::getLoggedInContactID();
1969 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1970 $config = CRM_Core_Config
::singleton();
1972 $ufID = $config->userSystem
->getUfId($matches[1]);
1974 return 'unknown-user';
1977 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
1979 return 'unknown-user';
1988 * Validate html (check for scripting attack).
1990 * @param array $params
1991 * @param string $fieldName
1992 * @param array $fieldInfo
1994 * @throws API_Exception
1996 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
1997 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1998 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
2002 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2003 throw new API_Exception('Illegal characters in input (potential scripting attack)', array("field" => $fieldName, "error_code" => "xss"));
2009 * Validate string fields being passed into API.
2011 * @param array $params
2012 * Params from civicrm_api.
2013 * @param string $fieldName
2014 * Uniquename of field being checked.
2015 * @param array $fieldInfo
2016 * Array of fields from getfields function.
2017 * @param string $entity
2019 * @throws API_Exception
2022 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2023 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2024 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
2028 if (!is_array($fieldValue)) {
2029 $fieldValue = (string) $fieldValue;
2032 //@todo what do we do about passed in arrays. For many of these fields
2033 // the missing piece of functionality is separating them to a separated string
2034 // & many save incorrectly. But can we change them wholesale?
2037 foreach ((array) $fieldValue as $value) {
2038 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2039 throw new Exception('Illegal characters in input (potential scripting attack)');
2041 if ($fieldName == 'currency') {
2042 //When using IN operator $fieldValue is a array of currency codes
2043 if (!CRM_Utils_Rule
::currencyCode($value)) {
2044 throw new Exception("Currency not a valid code: $currency");
2049 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2050 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
2052 // Check our field length
2053 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2054 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2055 2100, array('field' => $fieldName)
2060 $params[$fieldName][$op] = $fieldValue;
2063 $params[$fieldName] = $fieldValue;
2068 * Validate & swap out any pseudoconstants / options.
2070 * @param mixed $fieldValue
2071 * @param string $entity : api entity name
2072 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2073 * @param array $fieldInfo : getfields meta-data
2075 * @throws \API_Exception
2077 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo) {
2078 $options = CRM_Utils_Array
::value('options', $fieldInfo);
2081 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2082 // We need to get the options from the entity the field relates to.
2083 $entity = $fieldInfo['entity'];
2085 $options = civicrm_api($entity, 'getoptions', array(
2087 'field' => $fieldInfo['name'],
2088 'context' => 'validate',
2090 $options = CRM_Utils_Array
::value('values', $options, array());
2093 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2095 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2096 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
2099 // If passed multiple options, validate each.
2100 if (is_array($fieldValue)) {
2101 foreach ($fieldValue as &$value) {
2102 if (!is_array($value)) {
2103 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
2106 // TODO: unwrap the call to implodePadded from the conditional and do it always
2107 // need to verify that this is safe and doesn't break anything though.
2108 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2110 CRM_Utils_Array
::implodePadded($fieldValue);
2114 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName);
2119 * Validate & swap a single option value for a field.
2121 * @param string $value field value
2122 * @param array $options array of options for this field
2123 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2125 * @throws API_Exception
2127 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
2128 // If option is a key, no need to translate
2129 // or if no options are avaiable for pseudoconstant 'table' property
2130 if (array_key_exists($value, $options) ||
!$options) {
2134 // Translate value into key
2135 $newValue = array_search($value, $options);
2136 if ($newValue !== FALSE) {
2140 // Case-insensitive matching
2141 $newValue = strtolower($value);
2142 $options = array_map("strtolower", $options);
2143 $newValue = array_search($newValue, $options);
2144 if ($newValue === FALSE) {
2145 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
2151 * Returns the canonical name of a field.
2154 * api entity name (string should already be standardized - no camelCase).
2156 * any variation of a field's name (name, unique_name, api.alias).
2158 * @return bool|string
2159 * fieldName or FALSE if the field does not exist
2161 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
2162 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2165 if ($fieldName == "{$entity}_id") {
2168 $result = civicrm_api($entity, 'getfields', array(
2170 'action' => 'create',
2172 $meta = $result['values'];
2173 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2174 $fieldName = $fieldName . '_id';
2176 if (isset($meta[$fieldName])) {
2177 return $meta[$fieldName]['name'];
2179 foreach ($meta as $info) {
2180 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2181 return $info['name'];
2183 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
2184 return $info['name'];
2191 * Check if the function is deprecated.
2193 * @param string $entity
2194 * @param array $result
2196 * @return string|array|null
2198 function _civicrm_api3_deprecation_check($entity, $result = array()) {
2200 $apiFile = 'api/v3/' . _civicrm_api_get_camel_name($entity) . '.php';
2201 if (CRM_Utils_File
::isIncludable($apiFile)) {
2202 require_once $apiFile;
2204 $entity = _civicrm_api_get_entity_name_from_camel($entity);
2205 $fnName = "_civicrm_api3_{$entity}_deprecation";
2206 if (function_exists($fnName)) {
2207 return $fnName($result);
2213 * Get the actual field value.
2215 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2216 * So this function returns the actual field value
2218 * @param array $params
2219 * @param string $fieldName
2223 function _civicrm_api3_field_value_check(&$params, $fieldName) {
2224 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2227 if (!empty($fieldValue) && is_array($fieldValue) && array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators())) {
2228 $op = key($fieldValue);
2229 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2231 return array($fieldValue, $op);