3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * File for CiviCRM APIv3 utilitity functions
31 * @package CiviCRM_APIv3
32 * @subpackage API_utils
34 * @copyright CiviCRM LLC (c) 2004-2014
35 * @version $Id: utils.php 30879 2010-11-22 15:45:55Z shot $
39 * Initialize CiviCRM - should be run at the start of each API function.
41 function _civicrm_api3_initialize() {
42 require_once 'CRM/Core/ClassLoader.php';
43 CRM_Core_ClassLoader
::singleton()->register();
44 CRM_Core_Config
::singleton();
48 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking.
50 * @param array $params
51 * Array of fields to check.
52 * @param array $daoName
53 * String DAO to check for required fields (create functions only).
54 * @param array $keyoptions
55 * List of required fields options. One of the options is required.
57 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = array()) {
58 $keys = array(array());
59 foreach ($keyoptions as $key) {
62 civicrm_api3_verify_mandatory($params, $daoName, $keys);
66 * Check mandatory fields are included.
68 * @param array $params
69 * Array of fields to check.
70 * @param array $daoName
71 * String DAO to check for required fields (create functions only).
73 * List of required fields. A value can be an array denoting that either this or that is required.
74 * @param bool $verifyDAO
76 * @throws \API_Exception
78 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = array(), $verifyDAO = TRUE) {
81 if ($daoName != NULL && $verifyDAO && empty($params['id'])) {
82 $unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
83 if (!is_array($unmatched)) {
88 if (!empty($params['id'])) {
89 $keys = array('version');
92 if (!in_array('version', $keys)) {
93 // required from v3 onwards
97 foreach ($keys as $key) {
100 $optionset = array();
101 foreach ($key as $subkey) {
102 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
103 $optionset[] = $subkey;
106 // as long as there is one match then we don't need to rtn anything
110 if (empty($match) && !empty($optionset)) {
111 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
115 // Disallow empty values except for the number zero.
116 // TODO: create a utility for this since it's needed in many places
117 if (!array_key_exists($key, $params) ||
(empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
122 if (!empty($unmatched)) {
123 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched), "mandatory_missing", array("fields" => $unmatched));
128 * Create error array.
135 function civicrm_api3_create_error($msg, $data = array()) {
136 $data['is_error'] = 1;
137 $data['error_message'] = $msg;
138 // we will show sql to privileged user only (not sure of a specific
139 // security hole here but seems sensible - perhaps should apply to the trace as well?)
140 if (isset($data['sql']) && CRM_Core_Permission
::check('Administer CiviCRM')) {
141 // Isn't this redundant?
142 $data['debug_information'] = $data['sql'];
151 * Format array in result output style.
153 * @param array|int $values values generated by API operation (the result)
154 * @param array $params
155 * Parameters passed into API call.
156 * @param string $entity
157 * The entity being acted on.
158 * @param string $action
159 * The action passed to the API.
161 * DAO object to be freed here.
162 * @param array $extraReturnValues
163 * Additional values to be added to top level of result array(.
164 * - this param is currently used for legacy behaviour support
168 function civicrm_api3_create_success($values = 1, $params = array(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
170 $result['is_error'] = 0;
171 //lets set the ['id'] field if it's not set & we know what the entity is
172 if (is_array($values) && !empty($entity) && $action != 'getfields') {
173 foreach ($values as $key => $item) {
174 if (empty($item['id']) && !empty($item[$entity . "_id"])) {
175 $values[$key]['id'] = $item[$entity . "_id"];
177 if (!empty($item['financial_type_id'])) {
178 //4.3 legacy handling
179 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
181 if (!empty($item['next_sched_contribution_date'])) {
182 // 4.4 legacy handling
183 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
188 if (is_array($params) && !empty($params['debug'])) {
189 if (is_string($action) && $action != 'getfields') {
190 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) +
$params);
192 elseif ($action != 'getfields') {
193 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
199 $allFields = array();
200 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
201 $allFields = array_keys($apiFields['values']);
203 $paramFields = array_keys($params);
204 $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), array(
223 $result['undefined_fields'] = array_merge($undefined);
226 if (is_object($dao)) {
230 $result['version'] = 3;
231 if (is_array($values)) {
232 $result['count'] = (int) count($values);
234 // Convert value-separated strings to array
235 _civicrm_api3_separate_values($values);
237 if ($result['count'] == 1) {
238 list($result['id']) = array_keys($values);
240 elseif (!empty($values['id']) && is_int($values['id'])) {
241 $result['id'] = $values['id'];
245 $result['count'] = !empty($values) ?
1 : 0;
248 if (is_array($values) && isset($params['sequential']) &&
249 $params['sequential'] == 1
251 $result['values'] = array_values($values);
254 $result['values'] = $values;
256 if (!empty($params['options']['metadata'])) {
257 // We've made metadata an array but only supporting 'fields' atm.
258 if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
259 $fields = civicrm_api3($entity, 'getfields', array(
260 'action' => substr($action, 0, 3) == 'get' ?
'get' : 'create',
262 $result['metadata']['fields'] = $fields['values'];
265 // Report deprecations.
266 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
267 // Always report "update" action as deprecated.
268 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'update')) {
269 $deprecated = ((array) $deprecated) +
array('update' => 'The "update" action is deprecated. Use "create" with an id instead.');
272 // Metadata-level deprecations or wholesale entity deprecations.
273 if ($entity == 'entity' ||
$action == 'getactions' ||
is_string($deprecated)) {
274 $result['deprecated'] = $deprecated;
276 // Action-specific deprecations
277 elseif (!empty($deprecated[$action])) {
278 $result['deprecated'] = $deprecated[$action];
281 return array_merge($result, $extraReturnValues);
285 * Load the DAO of the entity.
291 function _civicrm_api3_load_DAO($entity) {
292 $dao = _civicrm_api3_get_DAO($entity);
301 * Return the DAO of the function or Entity.
303 * @param string $name
304 * Either a function of the api (civicrm_{entity}_create or the entity name.
305 * return the DAO name to manipulate this function
306 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
308 * @return mixed|string
310 function _civicrm_api3_get_DAO($name) {
311 if (strpos($name, 'civicrm_api3') !== FALSE) {
312 $last = strrpos($name, '_');
313 // len ('civicrm_api3_') == 13
314 $name = substr($name, 13, $last - 13);
317 $name = _civicrm_api_get_camel_name($name, 3);
319 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
323 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
325 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
326 if ($name == 'MailingEventQueue') {
327 return 'CRM_Mailing_Event_DAO_Queue';
329 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
330 // but am not confident mailing_recipients is tested so have not tackled.
331 if ($name == 'MailingRecipients') {
332 return 'CRM_Mailing_DAO_Recipients';
334 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
335 if ($name == 'MailingComponent') {
336 return 'CRM_Mailing_DAO_Component';
338 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
339 if ($name == 'AclRole') {
340 return 'CRM_ACL_DAO_EntityRole';
342 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
343 // But this would impact SMS extensions so need to coordinate
344 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
345 if ($name == 'SmsProvider') {
346 return 'CRM_SMS_DAO_Provider';
348 // FIXME: DAO names should follow CamelCase convention
349 if ($name == 'Im' ||
$name == 'Acl') {
350 $name = strtoupper($name);
352 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
353 if ($dao ||
!$name) {
357 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
358 if (file_exists("api/v3/$name.php")) {
359 include_once "api/v3/$name.php";
362 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
363 if (function_exists($daoFn)) {
371 * Return the DAO of the function or Entity.
373 * @param string $name
374 * Is either a function of the api (civicrm_{entity}_create or the entity name.
375 * return the DAO name to manipulate this function
376 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
380 function _civicrm_api3_get_BAO($name) {
381 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
382 if ($name == 'PrintLabel') {
383 return 'CRM_Badge_BAO_Layout';
385 $dao = _civicrm_api3_get_DAO($name);
389 $bao = str_replace("DAO", "BAO", $dao);
390 $file = strtr($bao, '_', '/') . '.php';
391 // Check if this entity actually has a BAO. Fall back on the DAO if not.
392 return stream_resolve_include_path($file) ?
$bao : $dao;
396 * Recursive function to explode value-separated strings into arrays.
400 function _civicrm_api3_separate_values(&$values) {
401 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
402 foreach ($values as $key => & $value) {
403 if (is_array($value)) {
404 _civicrm_api3_separate_values($value);
406 elseif (is_string($value)) {
407 // This is to honor the way case API was originally written.
408 if ($key == 'case_type_id') {
409 $value = trim(str_replace($sp, ',', $value), ',');
411 elseif (strpos($value, $sp) !== FALSE) {
412 $value = explode($sp, trim($value, $sp));
419 * This is a legacy wrapper for api_store_values.
421 * It checks suitable fields using getfields rather than DAO->fields.
423 * Getfields has handling for how to deal with unique names which dao->fields doesn't
425 * Note this is used by BAO type create functions - eg. contribution
427 * @param string $entity
428 * @param array $params
429 * @param array $values
431 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
432 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
433 $fields = $fields['values'];
434 _civicrm_api3_store_values($fields, $params, $values);
439 * @param array $fields
440 * @param array $params
441 * @param array $values
445 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
448 $keys = array_intersect_key($params, $fields);
449 foreach ($keys as $name => $value) {
450 if ($name !== 'id') {
451 $values[$name] = $value;
459 * Get function for query object api.
461 * The API supports 2 types of get request. The more complex uses the BAO query object.
462 * This is a generic function for those functions that call it
464 * At the moment only called by contact we should extend to contribution &
465 * others that use the query object. Note that this function passes permission information in.
468 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
472 * @param array $params
473 * As passed into api get or getcount function.
474 * @param array $additional_options
475 * Array of options (so we can modify the filter).
476 * @param bool $getCount
477 * Are we just after the count.
481 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL) {
483 // Convert id to e.g. contact_id
484 if (empty($params[$entity . '_id']) && isset($params['id'])) {
485 $params[$entity . '_id'] = $params['id'];
487 unset($params['id']);
489 $options = _civicrm_api3_get_options_from_params($params, TRUE);
491 $inputParams = array_merge(
492 CRM_Utils_Array
::value('input_params', $options, array()),
493 CRM_Utils_Array
::value('input_params', $additional_options, array())
495 $returnProperties = array_merge(
496 CRM_Utils_Array
::value('return', $options, array()),
497 CRM_Utils_Array
::value('return', $additional_options, array())
499 if (empty($returnProperties)) {
500 $returnProperties = NULL;
502 if (!empty($params['check_permissions'])) {
503 // we will filter query object against getfields
504 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
505 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
506 $fields['values'][$entity . '_id'] = array();
507 $varsToFilter = array('returnProperties', 'inputParams');
508 foreach ($varsToFilter as $varToFilter) {
509 if (!is_array($
$varToFilter)) {
512 //I was going to throw an exception rather than silently filter out - but
513 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
514 //so we are silently ignoring parts of their request
515 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
516 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
519 $options = array_merge($options, $additional_options);
520 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
521 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
522 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
523 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
527 $returnProperties = NULL;
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;
544 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
546 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
558 // only return the count of contacts
566 * Get dao query object based on input params.
568 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
571 * @param array $params
572 * @param string $mode
573 * @param string $entity
576 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
578 function _civicrm_api3_get_query_object($params, $mode, $entity) {
579 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
580 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
581 $offset = CRM_Utils_Array
::value('offset', $options);
582 $rowCount = CRM_Utils_Array
::value('limit', $options);
583 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
584 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
585 if (empty($returnProperties)) {
586 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
589 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
590 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
592 empty($params['check_permissions'])
594 list($select, $from, $where, $having) = $query->query();
596 $sql = "$select $from $where $having";
599 $sql .= " ORDER BY $sort ";
601 if (!empty($rowCount)) {
602 $sql .= " LIMIT $offset, $rowCount ";
604 $dao = CRM_Core_DAO
::executeQuery($sql);
605 return array($dao, $query);
609 * Function transfers the filters being passed into the DAO onto the params object.
611 * @param CRM_Core_DAO $dao
612 * @param array $params
613 * @param bool $unique
614 * @param string $entity
616 * @throws API_Exception
619 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $entity) {
620 $entity = substr($dao->__table
, 8);
621 if (!empty($params[$entity . "_id"]) && empty($params['id'])) {
622 //if entity_id is set then treat it as ID (will be overridden by id if set)
623 $params['id'] = $params[$entity . "_id"];
625 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
626 $fields = array_intersect(array_keys($allfields), array_keys($params));
628 $options = _civicrm_api3_get_options_from_params($params);
629 //apply options like sort
630 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
632 //accept filters like filter.activity_date_time_high
633 // std is now 'filters' => ..
634 if (strstr(implode(',', array_keys($params)), 'filter')) {
635 if (isset($params['filters']) && is_array($params['filters'])) {
636 foreach ($params['filters'] as $paramkey => $paramvalue) {
637 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
641 foreach ($params as $paramkey => $paramvalue) {
642 if (strstr($paramkey, 'filter')) {
643 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
652 foreach ($fields as $field) {
653 if (is_array($params[$field])) {
654 //get the actual fieldname from db
655 $fieldName = $allfields[$field]['name'];
656 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
657 if (!empty($where)) {
658 $dao->whereAdd($where);
663 $daoFieldName = $allfields[$field]['name'];
664 if (empty($daoFieldName)) {
665 throw new API_Exception("Failed to determine field name for \"$field\"");
667 $dao->{$daoFieldName} = $params[$field];
670 $dao->$field = $params[$field];
674 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
676 // Ensure 'id' is included.
677 $options['return']['id'] = TRUE;
678 $allfields = _civicrm_api3_get_unique_name_array($dao);
679 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
680 foreach ($returnMatched as $returnValue) {
681 $dao->selectAdd($returnValue);
684 // Not already matched on the field names.
685 $unmatchedFields = array_diff(
686 array_keys($options['return']),
690 $returnUniqueMatched = array_intersect(
692 // But a match for the field keys.
693 array_flip($allfields)
695 foreach ($returnUniqueMatched as $uniqueVal) {
696 $dao->selectAdd($allfields[$uniqueVal]);
699 $dao->setApiFilter($params);
703 * Apply filters (e.g. high, low) to DAO object (prior to find).
705 * @param string $filterField
706 * Field name of filter.
707 * @param string $filterValue
708 * Field value of filter.
712 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
713 if (strstr($filterField, 'high')) {
714 $fieldName = substr($filterField, 0, -5);
715 $dao->whereAdd("($fieldName <= $filterValue )");
717 if (strstr($filterField, 'low')) {
718 $fieldName = substr($filterField, 0, -4);
719 $dao->whereAdd("($fieldName >= $filterValue )");
721 if ($filterField == 'is_current' && $filterValue == 1) {
722 $todayStart = date('Ymd000000', strtotime('now'));
723 $todayEnd = date('Ymd235959', strtotime('now'));
724 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
725 if (property_exists($dao, 'is_active')) {
726 $dao->whereAdd('is_active = 1');
732 * Get sort, limit etc options from the params - supporting old & new formats.
734 * Get returnProperties for legacy
736 * @param array $params
737 * Params array as passed into civicrm_api.
738 * @param bool $queryObject
739 * Is this supporting a queryObject api (e.g contact) - if so we support more options.
740 * for legacy report & return a unique fields array
742 * @param string $entity
743 * @param string $action
745 * @throws API_Exception
747 * options extracted from params
749 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
751 $sort = CRM_Utils_Array
::value('sort', $params, 0);
752 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
753 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
755 $offset = CRM_Utils_Array
::value('offset', $params, 0);
756 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
757 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
758 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
760 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
761 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
762 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
764 if (is_array(CRM_Utils_Array
::value('options', $params))) {
765 // is count is set by generic getcount not user
766 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
767 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
768 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
769 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
772 $returnProperties = array();
773 // handle the format return =sort_name,display_name...
774 if (array_key_exists('return', $params)) {
775 if (is_array($params['return'])) {
776 $returnProperties = array_fill_keys($params['return'], 1);
779 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
780 $returnProperties = array_fill_keys($returnProperties, 1);
783 if ($entity && $action == 'get') {
784 if (!empty($returnProperties['id'])) {
785 $returnProperties[$entity . '_id'] = 1;
786 unset($returnProperties['id']);
788 switch (trim(strtolower($sort))) {
792 $sort = str_replace('id', $entity . '_id', $sort);
797 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
798 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
799 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
800 'is_count' => $is_count,
801 'return' => !empty($returnProperties) ?
$returnProperties : array(),
804 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
805 throw new API_Exception('invalid string in sort options');
811 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
812 // if the queryobject is being used this should be used
813 $inputParams = array();
814 $legacyreturnProperties = array();
816 'sort', 'offset', 'rowCount', 'options', 'return',
818 foreach ($params as $n => $v) {
819 if (substr($n, 0, 7) == 'return.') {
820 $legacyreturnProperties[substr($n, 7)] = $v;
822 elseif ($n == 'id') {
823 $inputParams[$entity . '_id'] = $v;
825 elseif (in_array($n, $otherVars)) {
828 $inputParams[$n] = $v;
829 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
830 throw new API_Exception('invalid string');
834 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
835 $options['input_params'] = $inputParams;
840 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
842 * @param array $params
843 * Params array as passed into civicrm_api.
848 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
850 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
851 if (!$options['is_count']) {
852 if (!empty($options['limit'])) {
853 $dao->limit((int) $options['offset'], (int) $options['limit']);
855 if (!empty($options['sort'])) {
856 $dao->orderBy($options['sort']);
862 * Build fields array.
864 * This is the array of fields as it relates to the given DAO
865 * returns unique fields as keys by default but if set but can return by DB fields
867 * @param CRM_Core_DAO $bao
868 * @param bool $unique
872 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
873 $fields = $bao->fields();
875 if (empty($fields['id'])) {
876 $entity = _civicrm_api_get_entity_name_from_dao($bao);
877 $fields['id'] = $fields[$entity . '_id'];
878 unset($fields[$entity . '_id']);
883 foreach ($fields as $field) {
884 $dbFields[$field['name']] = $field;
890 * Build fields array.
892 * This is the array of fields as it relates to the given DAO
893 * returns unique fields as keys by default but if set but can return by DB fields
895 * @param CRM_Core_DAO $bao
899 function _civicrm_api3_get_unique_name_array(&$bao) {
900 $fields = $bao->fields();
901 foreach ($fields as $field => $values) {
902 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
904 return $uniqueFields;
908 * Converts an DAO object to an array.
910 * @param CRM_Core_DAO $dao
912 * @param array $params
913 * @param bool $uniqueFields
914 * @param string $entity
915 * @param bool $autoFind
919 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
921 if (isset($params['options']) && !empty($params['options']['is_count'])) {
922 return $dao->count();
927 if ($autoFind && !$dao->find()) {
931 if (isset($dao->count
)) {
935 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
937 while ($dao->fetch()) {
939 foreach ($fields as $key) {
940 if (array_key_exists($key, $dao)) {
941 // not sure on that one
942 if ($dao->$key !== NULL) {
943 $tmp[$key] = $dao->$key;
947 $result[$dao->id
] = $tmp;
949 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
950 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
958 * Determine if custom fields need to be retrieved.
960 * We currently retrieve all custom fields or none at this level so if we know the entity
961 * && 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
962 * @todo filter so only required fields are queried
964 * @param string $entity
965 * Entity name in CamelCase.
966 * @param array $params
970 function _civicrm_api3_custom_fields_are_required($entity, $params) {
971 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
974 $options = _civicrm_api3_get_options_from_params($params);
975 // We check for possibility of 'custom' => 1 as well as specific custom fields.
976 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
977 if (stristr($returnString, 'custom')) {
982 * Converts an object to an array.
985 * (reference) object to convert.
986 * @param array $values
988 * @param array|bool $uniqueFields
990 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
992 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
993 foreach ($fields as $key => $value) {
994 if (array_key_exists($key, $dao)) {
995 $values[$key] = $dao->$key;
1001 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1008 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1009 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1013 * Format custom parameters.
1015 * @param array $params
1016 * @param array $values
1017 * @param string $extends
1018 * Entity that this custom field extends (e.g. contribution, event, contact).
1019 * @param string $entityId
1020 * ID of entity per $extends.
1022 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1023 $values['custom'] = array();
1024 $checkCheckBoxField = FALSE;
1026 if (in_array($extends, array('Household', 'Individual', 'Organization'))) {
1027 $entity = 'Contact';
1030 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
1031 if (!$fields['is_error']) {
1032 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1033 $fields = $fields['values'];
1034 $checkCheckBoxField = TRUE;
1037 foreach ($params as $key => $value) {
1038 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
1039 if ($customFieldID && (!is_null($value))) {
1040 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1041 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1044 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1045 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1052 * Format parameters for create action.
1054 * @param array $params
1057 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1058 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1060 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery
::$extendsMap, array_fill_keys($nonGenericEntities, 1));
1061 if (!array_key_exists($entity, $customFieldEntities)) {
1065 _civicrm_api3_custom_format_params($params, $values, $entity);
1066 $params = array_merge($params, $values);
1070 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1072 * We should look at pushing to BAO function
1073 * 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
1074 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1076 * 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
1077 * don't touch - lots of very cautious code in here
1079 * The resulting array should look like
1085 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1087 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1088 * be fixed in future
1090 * @param mixed $checkboxFieldValue
1091 * @param string $customFieldLabel
1092 * @param string $entity
1094 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1096 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1097 // We can assume it's pre-formatted.
1100 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1101 if (!empty($options['is_error'])) {
1102 // The check is precautionary - can probably be removed later.
1106 $options = $options['values'];
1108 if (is_array($checkboxFieldValue)) {
1109 foreach ($checkboxFieldValue as $key => $value) {
1110 if (!array_key_exists($key, $options)) {
1111 $validValue = FALSE;
1115 // we have been passed an array that is already in the 'odd' custom field format
1120 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1121 // if the array only has one item we'll treat it like any other string
1122 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1123 $possibleValue = reset($checkboxFieldValue);
1125 if (is_string($checkboxFieldValue)) {
1126 $possibleValue = $checkboxFieldValue;
1128 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1129 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1132 elseif (is_array($checkboxFieldValue)) {
1133 // so this time around we are considering the values in the array
1134 $possibleValues = $checkboxFieldValue;
1135 $formatValue = TRUE;
1137 elseif (stristr($checkboxFieldValue, ',')) {
1138 $formatValue = TRUE;
1139 //lets see if we should separate it - we do this near the end so we
1140 // ensure we have already checked that the comma is not part of a legitimate match
1141 // and of course, we don't make any changes if we don't now have matches
1142 $possibleValues = explode(',', $checkboxFieldValue);
1145 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1149 foreach ($possibleValues as $index => $possibleValue) {
1150 if (array_key_exists($possibleValue, $options)) {
1151 // 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)
1153 elseif (array_key_exists(trim($possibleValue), $options)) {
1154 $possibleValues[$index] = trim($possibleValue);
1157 $formatValue = FALSE;
1161 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1166 * This function ensures that we have the right input parameters.
1170 * This function is only called when $dao is passed into verify_mandatory.
1171 * The practice of passing $dao into verify_mandatory turned out to be
1172 * unsatisfactory as the required fields @ the dao level is so different to the abstract
1173 * api level. Hence the intention is to remove this function
1174 * & the associated param from verify_mandatory
1176 * @param array $params
1177 * Associative array of property name/value.
1178 * pairs to insert in new history.
1179 * @param string $daoName
1180 * @param bool $return
1182 * @daoName string DAO to check params agains
1185 * Should the missing fields be returned as an array (core error created as default)
1186 * true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1188 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1189 //@deprecated - see notes
1190 if (isset($params['extends'])) {
1191 if (($params['extends'] == 'Activity' ||
1192 $params['extends'] == 'Phonecall' ||
1193 $params['extends'] == 'Meeting' ||
1194 $params['extends'] == 'Group' ||
1195 $params['extends'] == 'Contribution'
1197 ($params['style'] == 'Tab')
1199 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1203 $dao = new $daoName();
1204 $fields = $dao->fields();
1207 foreach ($fields as $k => $v) {
1208 if ($v['name'] == 'id') {
1212 if (!empty($v['required'])) {
1213 // 0 is a valid input for numbers, CRM-8122
1214 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1220 if (!empty($missing)) {
1221 if (!empty($return)) {
1225 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1233 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1235 * @param string $bao_name
1237 * @param array $params
1239 * @param bool $returnAsSuccess
1240 * Return in api success format.
1241 * @param string $entity
1245 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1246 $bao = new $bao_name();
1247 _civicrm_api3_dao_set_filter($bao, $params, TRUE, $entity);
1248 if ($returnAsSuccess) {
1249 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1252 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity, 'get');
1257 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1259 * @param string $bao_name
1260 * Name of BAO Class.
1261 * @param array $params
1262 * Parameters passed into the api call.
1263 * @param string $entity
1264 * Entity - pass in if entity is non-standard & required $ids array.
1266 * @throws API_Exception
1269 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1270 _civicrm_api3_format_params_for_create($params, $entity);
1271 $args = array(&$params);
1272 if (!empty($entity)) {
1273 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1277 if (method_exists($bao_name, 'create')) {
1279 $fct_name = $bao_name . '::' . $fct;
1280 $bao = call_user_func_array(array($bao_name, $fct), $args);
1282 elseif (method_exists($bao_name, 'add')) {
1284 $fct_name = $bao_name . '::' . $fct;
1285 $bao = call_user_func_array(array($bao_name, $fct), $args);
1288 $fct_name = '_civicrm_api3_basic_create_fallback';
1289 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1292 if (is_null($bao)) {
1293 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1295 elseif (is_a($bao, 'CRM_Core_Error')) {
1296 //some wierd circular thing means the error takes itself as an argument
1297 $msg = $bao->getMessages($bao);
1298 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1299 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1300 // so we need to reset the error object here to avoid getting concatenated errors
1301 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1302 CRM_Core_Error
::singleton()->reset();
1303 throw new API_Exception($msg);
1307 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1308 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1313 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1315 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1316 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1318 * @param string $bao_name
1319 * @param array $params
1321 * @throws API_Exception
1323 * @return CRM_Core_DAO|NULL
1324 * An instance of the BAO
1326 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1327 $dao_name = get_parent_class($bao_name);
1328 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1329 $dao_name = $bao_name;
1331 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1332 if (empty($entityName)) {
1333 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1334 'class_name' => $bao_name,
1337 $hook = empty($params['id']) ?
'create' : 'edit';
1339 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1340 $instance = new $dao_name();
1341 $instance->copyValues($params);
1343 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1349 * Function to do a 'standard' api del.
1351 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1353 * @param string $bao_name
1354 * @param array $params
1358 * @throws API_Exception
1360 function _civicrm_api3_basic_delete($bao_name, &$params) {
1362 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1363 $args = array(&$params['id']);
1364 if (method_exists($bao_name, 'del')) {
1365 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1366 if ($bao !== FALSE) {
1367 return civicrm_api3_create_success(TRUE);
1369 throw new API_Exception('Could not delete entity id ' . $params['id']);
1371 elseif (method_exists($bao_name, 'delete')) {
1372 $dao = new $bao_name();
1373 $dao->id
= $params['id'];
1375 while ($dao->fetch()) {
1377 return civicrm_api3_create_success();
1381 throw new API_Exception('Could not delete entity id ' . $params['id']);
1385 throw new API_Exception('no delete method found');
1389 * Get custom data for the given entity & Add it to the returnArray.
1391 * This looks like 'custom_123' = 'custom string' AND
1392 * 'custom_123_1' = 'custom string'
1393 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1395 * @param array $returnArray
1396 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1397 * @param string $entity
1398 * E.g membership, event.
1399 * @param int $entity_id
1400 * @param int $groupID
1401 * Per CRM_Core_BAO_CustomGroup::getTree.
1402 * @param int $subType
1403 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1404 * @param string $subName
1405 * Subtype of entity.
1407 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1408 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1409 CRM_Core_DAO
::$_nullObject,
1415 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1416 $customValues = array();
1417 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1418 $fieldInfo = array();
1419 foreach ($groupTree as $set) {
1420 $fieldInfo +
= $set['fields'];
1422 if (!empty($customValues)) {
1423 foreach ($customValues as $key => $val) {
1424 // per standard - return custom_fieldID
1425 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1426 $returnArray['custom_' . $id] = $val;
1428 //not standard - but some api did this so guess we should keep - cheap as chips
1429 $returnArray[$key] = $val;
1431 // Shim to restore legacy behavior of ContactReference custom fields
1432 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1433 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1434 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1441 * Validate fields being passed into API.
1443 * This function relies on the getFields function working accurately
1444 * for the given API. If error mode is set to TRUE then it will also check
1447 * As of writing only date was implemented.
1449 * @param string $entity
1450 * @param string $action
1451 * @param array $params
1453 * @param array $fields
1454 * Response from getfields all variables are the same as per civicrm_api.
1455 * @param bool $errorMode
1456 * ErrorMode do intensive post fail checks?.
1460 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = FALSE) {
1461 $fields = array_intersect_key($fields, $params);
1462 foreach ($fields as $fieldName => $fieldInfo) {
1463 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1464 case CRM_Utils_Type
::T_INT
:
1465 //field is of type integer
1466 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1471 case CRM_Utils_Type
::T_TIMESTAMP
:
1472 //field is of type date or datetime
1473 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1478 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1481 case CRM_Utils_Type
::T_STRING
:
1482 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1485 case CRM_Utils_Type
::T_MONEY
:
1486 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1487 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1490 foreach ((array) $fieldValue as $fieldvalue) {
1491 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1492 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1498 // intensive checks - usually only called after DB level fail
1499 if (!empty($errorMode) && strtolower($action) == 'create') {
1500 if (!empty($fieldInfo['FKClassName'])) {
1501 if (!empty($fieldValue)) {
1502 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1504 elseif (!empty($fieldInfo['required'])) {
1505 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1508 if (!empty($fieldInfo['api.unique'])) {
1509 $params['entity'] = $entity;
1510 _civicrm_api3_validate_unique_key($params, $fieldName);
1517 * Validate date fields being passed into API.
1519 * It currently converts both unique fields and DB field names to a mysql date.
1520 * @todo - probably the unique field handling & the if exists handling is now done before this
1521 * function is reached in the wrapper - can reduce this code down to assume we
1522 * are only checking the passed in field
1524 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1525 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1527 * @param array $params
1528 * Params from civicrm_api.
1529 * @param string $fieldName
1530 * Uniquename of field being checked.
1531 * @param array $fieldInfo
1532 * Array of fields from getfields function.
1536 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1537 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1538 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1541 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1542 if (!empty($params[$fieldInfo['name']])) {
1543 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1545 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1546 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1550 $params[$fieldName][$op] = $fieldValue;
1553 $params[$fieldName] = $fieldValue;
1558 * Convert date into BAO friendly date.
1560 * We accept 'whatever strtotime accepts'
1562 * @param string $dateValue
1563 * @param string $fieldName
1569 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1570 if (is_array($dateValue)) {
1571 foreach ($dateValue as $key => $value) {
1572 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1576 if (strtotime($dateValue) === FALSE) {
1577 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1579 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1580 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1584 * Validate foreign constraint fields being passed into API.
1586 * @param mixed $fieldValue
1587 * @param string $fieldName
1588 * Uniquename of field being checked.
1589 * @param array $fieldInfo
1590 * Array of fields from getfields function.
1592 * @throws \API_Exception
1594 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1595 $daoName = $fieldInfo['FKClassName'];
1596 $dao = new $daoName();
1597 $dao->id
= $fieldValue;
1599 $dao->selectAdd('id');
1600 if (!$dao->find()) {
1601 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1606 * Validate foreign constraint fields being passed into API.
1608 * @param array $params
1609 * Params from civicrm_api.
1610 * @param string $fieldName
1611 * Uniquename of field being checked.
1615 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1616 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1617 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1620 $existing = civicrm_api($params['entity'], 'get', array(
1621 'version' => $params['version'],
1622 $fieldName => $fieldValue,
1624 // an entry already exists for this unique field
1625 if ($existing['count'] == 1) {
1626 // question - could this ever be a security issue?
1627 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1632 * Generic implementation of the "replace" action.
1634 * Replace the old set of entities (matching some given keys) with a new set of
1635 * entities (matching the same keys).
1637 * Note: This will verify that 'values' is present, but it does not directly verify
1638 * any other parameters.
1640 * @param string $entity
1642 * @param array $params
1643 * Params from civicrm_api, including:.
1644 * - 'values': an array of records to save
1645 * - all other items: keys which identify new/pre-existing records.
1649 function _civicrm_api3_generic_replace($entity, $params) {
1651 $transaction = new CRM_Core_Transaction();
1653 if (!is_array($params['values'])) {
1654 throw new Exception("Mandatory key(s) missing from params array: values");
1657 // Extract the keys -- somewhat scary, don't think too hard about it
1658 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1660 // Lookup pre-existing records
1661 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1662 if (civicrm_error($preexisting)) {
1663 $transaction->rollback();
1664 return $preexisting;
1667 // Save the new/updated records
1669 foreach ($params['values'] as $replacement) {
1670 // Sugar: Don't force clients to duplicate the 'key' data
1671 $replacement = array_merge($baseParams, $replacement);
1672 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1673 $create = civicrm_api($entity, $action, $replacement);
1674 if (civicrm_error($create)) {
1675 $transaction->rollback();
1678 foreach ($create['values'] as $entity_id => $entity_value) {
1679 $creates[$entity_id] = $entity_value;
1683 // Remove stale records
1684 $staleIDs = array_diff(
1685 array_keys($preexisting['values']),
1686 array_keys($creates)
1688 foreach ($staleIDs as $staleID) {
1689 $delete = civicrm_api($entity, 'delete', array(
1690 'version' => $params['version'],
1693 if (civicrm_error($delete)) {
1694 $transaction->rollback();
1699 return civicrm_api3_create_success($creates, $params);
1701 catch(PEAR_Exception
$e) {
1702 $transaction->rollback();
1703 return civicrm_api3_create_error($e->getMessage());
1705 catch(Exception
$e) {
1706 $transaction->rollback();
1707 return civicrm_api3_create_error($e->getMessage());
1712 * Replace base parameters.
1714 * @param array $params
1718 function _civicrm_api3_generic_replace_base_params($params) {
1719 $baseParams = $params;
1720 unset($baseParams['values']);
1721 unset($baseParams['sequential']);
1722 unset($baseParams['options']);
1727 * Returns fields allowable by api.
1730 * String Entity to query.
1731 * @param bool $unique
1732 * Index by unique fields?.
1733 * @param array $params
1737 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1738 $unsetIfEmpty = array(
1745 $dao = _civicrm_api3_get_DAO($entity);
1750 $fields = $d->fields();
1751 // replace uniqueNames by the normal names as the key
1752 if (empty($unique)) {
1753 foreach ($fields as $name => &$field) {
1754 //getting rid of unused attributes
1755 foreach ($unsetIfEmpty as $attr) {
1756 if (empty($field[$attr])) {
1757 unset($field[$attr]);
1760 if ($name == $field['name']) {
1763 if (array_key_exists($field['name'], $fields)) {
1764 $field['error'] = 'name conflict';
1765 // it should never happen, but better safe than sorry
1768 $fields[$field['name']] = $field;
1769 $fields[$field['name']]['uniqueName'] = $name;
1770 unset($fields[$name]);
1773 // Translate FKClassName to the corresponding api
1774 foreach ($fields as $name => &$field) {
1775 if (!empty($field['FKClassName'])) {
1776 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1778 $field['FKApiName'] = $FKApi;
1782 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1787 * Return an array of fields for a given entity.
1789 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1792 * @param array $params
1796 function _civicrm_api_get_custom_fields($entity, &$params) {
1797 $entity = _civicrm_api_get_camel_name($entity);
1798 if ($entity == 'Contact') {
1799 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1800 $entity = CRM_Utils_Array
::value('contact_type', $params);
1802 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1805 // we could / should probably test for other subtypes here - e.g. activity_type_id
1806 CRM_Utils_Array
::value('contact_sub_type', $params),
1815 foreach ($customfields as $key => $value) {
1816 // Regular fields have a 'name' property
1817 $value['name'] = 'custom_' . $key;
1818 $value['title'] = $value['label'];
1819 $value['type'] = _getStandardTypeFromCustomDataType($value['data_type']);
1820 $ret['custom_' . $key] = $value;
1826 * Translate the custom field data_type attribute into a std 'type'.
1832 function _getStandardTypeFromCustomDataType($dataType) {
1834 'String' => CRM_Utils_Type
::T_STRING
,
1835 'Int' => CRM_Utils_Type
::T_INT
,
1836 'Money' => CRM_Utils_Type
::T_MONEY
,
1837 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1838 'Float' => CRM_Utils_Type
::T_FLOAT
,
1839 'Date' => CRM_Utils_Type
::T_DATE
,
1840 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1841 'StateProvince' => CRM_Utils_Type
::T_INT
,
1842 'File' => CRM_Utils_Type
::T_STRING
,
1843 'Link' => CRM_Utils_Type
::T_STRING
,
1844 'ContactReference' => CRM_Utils_Type
::T_INT
,
1845 'Country' => CRM_Utils_Type
::T_INT
,
1847 return $mapping[$dataType];
1852 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
1854 * If multiple aliases the last takes precedence
1856 * Function also swaps unique fields for non-unique fields & vice versa.
1858 * @param $apiRequest
1861 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1862 foreach ($fields as $field => $values) {
1863 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1864 if (!empty($values['api.aliases'])) {
1865 // if aliased field is not set we try to use field alias
1866 if (!isset($apiRequest['params'][$field])) {
1867 foreach ($values['api.aliases'] as $alias) {
1868 if (isset($apiRequest['params'][$alias])) {
1869 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1871 //unset original field nb - need to be careful with this as it may bring inconsistencies
1872 // out of the woodwork but will be implementing only as _spec function extended
1873 unset($apiRequest['params'][$alias]);
1877 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
1878 && isset($apiRequest['params'][$values['name']])
1880 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1881 // note that it would make sense to unset the original field here but tests need to be in place first
1883 if (!isset($apiRequest['params'][$field])
1885 && $field != $uniqueName
1886 && array_key_exists($uniqueName, $apiRequest['params'])
1888 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1889 // note that it would make sense to unset the original field here but tests need to be in place first
1896 * Validate integer fields being passed into API.
1898 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
1900 * @param array $params
1901 * Params from civicrm_api.
1902 * @param string $fieldName
1903 * Uniquename of field being checked.
1904 * @param array $fieldInfo
1905 * Array of fields from getfields function.
1906 * @param string $entity
1908 * @throws API_Exception
1910 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1911 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1912 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1916 if (!empty($fieldValue)) {
1917 // if value = 'user_contact_id' (or similar), replace value with contact id
1918 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
1919 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
1920 if ('unknown-user' === $realContactId) {
1921 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName, "type" => "integer"));
1923 elseif (is_numeric($realContactId)) {
1924 $fieldValue = $realContactId;
1927 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1928 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
1931 // After swapping options, ensure we have an integer(s)
1932 foreach ((array) ($fieldValue) as $value) {
1933 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1934 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1938 // Check our field length
1939 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
1941 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1942 2100, array('field' => $fieldName, "max_length" => $fieldInfo['maxlength'])
1948 $params[$fieldName][$op] = $fieldValue;
1951 $params[$fieldName] = $fieldValue;
1956 * Determine a contact ID using a string expression.
1958 * @param string $contactIdExpr
1959 * E.g. "user_contact_id" or "@user:username".
1961 * @return int|NULL|'unknown-user'
1963 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1964 // If value = 'user_contact_id' replace value with logged in user id.
1965 if ($contactIdExpr == "user_contact_id") {
1966 return CRM_Core_Session
::getLoggedInContactID();
1968 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1969 $config = CRM_Core_Config
::singleton();
1971 $ufID = $config->userSystem
->getUfId($matches[1]);
1973 return 'unknown-user';
1976 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
1978 return 'unknown-user';
1987 * Validate html (check for scripting attack).
1989 * @param array $params
1990 * @param string $fieldName
1991 * @param array $fieldInfo
1993 * @throws API_Exception
1995 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
1996 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1997 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
2001 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2002 throw new API_Exception('Illegal characters in input (potential scripting attack)', array("field" => $fieldName, "error_code" => "xss"));
2008 * Validate string fields being passed into API.
2010 * @param array $params
2011 * Params from civicrm_api.
2012 * @param string $fieldName
2013 * Uniquename of field being checked.
2014 * @param array $fieldInfo
2015 * Array of fields from getfields function.
2016 * @param string $entity
2018 * @throws API_Exception
2021 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2022 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2023 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
2027 if (!is_array($fieldValue)) {
2028 $fieldValue = (string) $fieldValue;
2031 //@todo what do we do about passed in arrays. For many of these fields
2032 // the missing piece of functionality is separating them to a separated string
2033 // & many save incorrectly. But can we change them wholesale?
2036 foreach ((array) $fieldValue as $value) {
2037 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2038 throw new Exception('Illegal characters in input (potential scripting attack)');
2040 if ($fieldName == 'currency') {
2041 //When using IN operator $fieldValue is a array of currency codes
2042 if (!CRM_Utils_Rule
::currencyCode($value)) {
2043 throw new Exception("Currency not a valid code: $currency");
2048 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2049 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
2051 // Check our field length
2052 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2053 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2054 2100, array('field' => $fieldName)
2059 $params[$fieldName][$op] = $fieldValue;
2062 $params[$fieldName] = $fieldValue;
2067 * Validate & swap out any pseudoconstants / options.
2069 * @param mixed $fieldValue
2070 * @param string $entity : api entity name
2071 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2072 * @param array $fieldInfo : getfields meta-data
2074 * @throws \API_Exception
2076 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo) {
2077 $options = CRM_Utils_Array
::value('options', $fieldInfo);
2080 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2081 // We need to get the options from the entity the field relates to.
2082 $entity = $fieldInfo['entity'];
2084 $options = civicrm_api($entity, 'getoptions', array(
2086 'field' => $fieldInfo['name'],
2087 'context' => 'validate',
2089 $options = CRM_Utils_Array
::value('values', $options, array());
2092 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2094 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2095 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
2098 // If passed multiple options, validate each.
2099 if (is_array($fieldValue)) {
2100 foreach ($fieldValue as &$value) {
2101 if (!is_array($value)) {
2102 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
2105 // TODO: unwrap the call to implodePadded from the conditional and do it always
2106 // need to verify that this is safe and doesn't break anything though.
2107 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2109 CRM_Utils_Array
::implodePadded($fieldValue);
2113 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName);
2118 * Validate & swap a single option value for a field.
2120 * @param string $value field value
2121 * @param array $options array of options for this field
2122 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2124 * @throws API_Exception
2126 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
2127 // If option is a key, no need to translate
2128 // or if no options are avaiable for pseudoconstant 'table' property
2129 if (array_key_exists($value, $options) ||
!$options) {
2133 // Translate value into key
2134 $newValue = array_search($value, $options);
2135 if ($newValue !== FALSE) {
2139 // Case-insensitive matching
2140 $newValue = strtolower($value);
2141 $options = array_map("strtolower", $options);
2142 $newValue = array_search($newValue, $options);
2143 if ($newValue === FALSE) {
2144 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
2150 * Returns the canonical name of a field.
2153 * api entity name (string should already be standardized - no camelCase).
2155 * any variation of a field's name (name, unique_name, api.alias).
2157 * @return bool|string
2158 * fieldName or FALSE if the field does not exist
2160 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
2161 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2164 if ($fieldName == "{$entity}_id") {
2167 $result = civicrm_api($entity, 'getfields', array(
2169 'action' => 'create',
2171 $meta = $result['values'];
2172 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2173 $fieldName = $fieldName . '_id';
2175 if (isset($meta[$fieldName])) {
2176 return $meta[$fieldName]['name'];
2178 foreach ($meta as $info) {
2179 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2180 return $info['name'];
2182 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
2183 return $info['name'];
2190 * Check if the function is deprecated.
2192 * @param string $entity
2193 * @param array $result
2195 * @return string|array|null
2197 function _civicrm_api3_deprecation_check($entity, $result = array()) {
2199 $apiFile = 'api/v3/' . _civicrm_api_get_camel_name($entity) . '.php';
2200 if (CRM_Utils_File
::isIncludable($apiFile)) {
2201 require_once $apiFile;
2203 $entity = _civicrm_api_get_entity_name_from_camel($entity);
2204 $fnName = "_civicrm_api3_{$entity}_deprecation";
2205 if (function_exists($fnName)) {
2206 return $fnName($result);
2212 * Get the actual field value.
2214 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2215 * So this function returns the actual field value
2217 * @param array $params
2218 * @param string $fieldName
2222 function _civicrm_api3_field_value_check(&$params, $fieldName) {
2223 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2226 if (!empty($fieldValue) && is_array($fieldValue) && array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators())) {
2227 $op = key($fieldValue);
2228 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2230 return array($fieldValue, $op);